python 通过代理服务器 连接 huggingface下载模型,并运行 pipeline

news2024/10/5 12:44:10

想在Python 代码中运行时下载模型,启动代理服务器客户端后

1. 检查能否科学上网

$ curl -x socks5h://127.0.0.1:1080 https://www.example.com
<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        
    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 2em;
        background-color: #fdfdff;
        border-radius: 0.5em;
        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        div {
            margin: 0 auto;
            width: auto;
        }
    }
    </style>    
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>

2. 用 Python 代码检验

test_proxy.py :

import requests

url1 = 'https://www.example.com'
url2 = 'https://huggingface.co/'
proxies = {
    'http': 'socks5h://localhost:1080',
    'https': 'socks5h://localhost:1080'
}

try:
    response = requests.get(url1, proxies=proxies)
    if response.status_code == 200:
        print("成功连接到代理服务器并获取数据!")
        print("响应内容:", response.text)
    else:
        print("连接到代理服务器失败。请检查代理设置和网络连接。")
except requests.exceptions.RequestException as e:
    print("请求发生异常:", str(e))

输出结果:

成功连接到代理服务器并获取数据!
响应内容: <!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        
    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 2em;
        background-color: #fdfdff;
        border-radius: 0.5em;
        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        div {
            margin: 0 auto;
            width: auto;
        }
    }
    </style>    
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>


Process finished with exit code 0

成功连接

3. 运行下载模型的代码

download_model.py

import os
import json
import requests
from uuid import uuid4
from tqdm import tqdm

proxies = {
    'http': 'socks5h://localhost:1080',
    'https': 'socks5h://localhost:1080'
}

#使用uuid4()函数生成一个唯一的会话ID,用于在请求的标头中加以标识
SESSIONID = uuid4().hex

VOCAB_FILE = "vocab.txt"
CONFIG_FILE = "config.json"
MODEL_FILE = "pytorch_model.bin"
BASE_URL = "https://huggingface.co/{}/resolve/main/{}"

headers = {'user-agent': 'transformers/4.38.2; python/3.11.8;  \
			session_id/{}; torch/2.2.1; tensorflow/2.15.0; \
			file_type/model; framework/pytorch; from_auto_class/False'.format(SESSIONID)}

model_id = "distilbert-base-uncased-finetuned-sst-2-english"

# 创建模型对应的文件夹

model_dir = model_id.replace("/", "-")

print(model_dir)

if not os.path.exists(model_dir):
	os.mkdir(model_dir)


# vocab 和 config 文件可以直接下载
# 使用requests.get()函数向Hugging Face的API发送GET请求来下载词典文件和配置文件
r = requests.get(BASE_URL.format(model_id, VOCAB_FILE), headers=headers,proxies=proxies)
r.encoding = "utf-8"
with open(os.path.join(model_dir, VOCAB_FILE), "w", encoding="utf-8") as f:
	# print(r.text)
	f.write(r.text)
	print("{}词典文件下载完毕!".format(model_id))

r = requests.get(BASE_URL.format(model_id, CONFIG_FILE), headers=headers,proxies=proxies)
r.encoding = "utf-8"
with open(os.path.join(model_dir, CONFIG_FILE), "w", encoding="utf-8") as f:
	# print(r.status_code)
	# print(r.text)
	json.dump(r.json(), f, indent="\t")
	print("{}配置文件下载完毕!".format(model_id))


# 模型文件需要分两步进行

# Step1 获取模型下载的真实地址
r = requests.head(BASE_URL.format(model_id, MODEL_FILE), headers=headers,proxies=proxies)
r.raise_for_status()
if 300 <= r.status_code <= 399:
	url_to_download = r.headers["Location"]

# Step2 请求真实地址下载模型
# stream=True 启用逐块下载模式,响应内容将被分成多个小块进行下载
r = requests.get(url_to_download, stream=True,headers=None,proxies=proxies)
r.raise_for_status()

# 这里的进度条是可选项,直接使用了transformers包中的代码
# headers.get()方法从响应头中获取"Content-Length"字段的值。"Content-Length"表示下载文件的总大小,以字节为单位。
content_length = r.headers.get("Content-Length")
total = int(content_length) if content_length is not None else None
"""
参数unit="B"表示进度条以字节为单位。
unit_scale=True将自动调整进度条的单位以便更好地显示,例如,以KB、MB或GB为单位。
total参数设置进度条的总大小。initial=0表示进度条的初始值为0。
desc="Downloading Model"是进度条的描述,用于显示在进度条前面"""
progress = tqdm(
	unit="B",
	unit_scale=True,
	total=total,
	initial=0,
	desc="Downloading Model",
)
"""
使用iter_content()方法以指定的块大小(这里是1024字节)迭代下载的内容。
每次迭代,将一个块的内容存储在chunk变量中。
在每个块的迭代过程中,首先通过条件if chunk过滤掉空的块,以排除保持连接的新块。"""
with open(os.path.join(model_dir, MODEL_FILE), "wb") as temp_file:
	for chunk in r.iter_content(chunk_size=1024):
		if chunk:  # filter out keep-alive new chunks
			progress.update(len(chunk))
			temp_file.write(chunk)
progress.close()

print("{}模型文件下载完毕!".format(model_id))

速度还是可以的:
在这里插入图片描述
如果想运行pipeline 代码:

text_classification = pipeline("text-classification")

会出现:

No model was supplied, defaulted to distilbert/distilbert-base-uncased-finetuned-sst-2-english and revision af0f99b (https://hf-mirror.com/distilbert/distilbert-base-uncased-finetuned-sst-2-english).
Using a pipeline without specifying a model name and revision in production is not recommended.

这时把上面改上面代码:

model_id = "distilbert-base-uncased-finetuned-sst-2-english"

4. 运行 pipeline 代码

pipeline.py

from transformers import pipeline
import urllib.request


print(urllib.request.getproxies())

text_classification = pipeline("text-classification")
result = text_classification("Hello, world!")
print(result)

结果报错:

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/wxf/PycharmProjects/llm/pipe.py", line 21, in <module>
    text_classification = pipeline("text-classification")
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/wxf/lib/anaconda/envs/transformers/lib/python3.11/site-packages/transformers/pipelines/__init__.py", line 879, in pipeline
    config = AutoConfig.from_pretrained(model, _from_pipeline=task, **hub_kwargs, **model_kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/wxf/lib/anaconda/envs/transformers/lib/python3.11/site-packages/transformers/models/auto/configuration_auto.py", line 1111, in from_pretrained
    config_dict, unused_kwargs = PretrainedConfig.get_config_dict(pretrained_model_name_or_path, **kwargs)
                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/wxf/lib/anaconda/envs/transformers/lib/python3.11/site-packages/transformers/configuration_utils.py", line 633, in get_config_dict
    config_dict, kwargs = cls._get_config_dict(pretrained_model_name_or_path, **kwargs)
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/wxf/lib/anaconda/envs/transformers/lib/python3.11/site-packages/transformers/configuration_utils.py", line 688, in _get_config_dict
    resolved_config_file = cached_file(
                           ^^^^^^^^^^^^
  File "/home/wxf/lib/anaconda/envs/transformers/lib/python3.11/site-packages/transformers/utils/hub.py", line 441, in cached_file
    raise EnvironmentError(
OSError: We couldn't connect to 'https://hf-mirror.com' to load this file, couldn't find it in the cached files and it looks like distilbert/distilbert-base-uncased-finetuned-sst-2-english is not the path to a directory containing a file named config.json.
Checkout your internet connection or see how to run the library in offline mode at 'https://huggingface.co/docs/transformers/installation#offline-mode'.

代码 /home/wxf/lib/anaconda/envs/transformers/lib/python3.11/site-packages/transformers/configuration_utils.py
改成:

resolved_config_file = cached_file(
                    pretrained_model_name_or_path,
                    configuration_file,
                    cache_dir=cache_dir,
                    force_download=force_download,
                    proxies={
                    'http': 'socks5h://localhost:1080',
                    'https': 'socks5h://localhost:1080'
                    },
                    resume_download=resume_download,
                    local_files_only=local_files_only,
                    token=token,
                    user_agent=user_agent,
                    revision=revision,
                    subfolder=subfolder,
                    _commit_hash=commit_hash,
                )

然后运行结果:

No model was supplied, defaulted to distilbert/distilbert-base-uncased-finetuned-sst-2-english and revision af0f99b (https://hf-mirror.com/distilbert/distilbert-base-uncased-finetuned-sst-2-english).
Using a pipeline without specifying a model name and revision in production is not recommended.
[{'label': 'POSITIVE', 'score': 0.9997164607048035}]

5. 参考

  1. huggingface transformers预训练模型如何下载至本地,并使用?
  2. 国内用户 HuggingFace 高速下载
  3. huggingface transformers预训练模型如何下载至本地,并使用?
  4. Huggingface的from pretrained的下载代理服务器方法设置

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1510953.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Python: 如何绘制核密度散点图和箱线图?

01 数据样式 这是数据样式&#xff1a; 要求&#xff08;我就懒得再复述一遍了&#xff0c;直接贴图&#xff09;&#xff1a; Note&#xff1a;数据中存在无效值NA&#xff08;包括后续的DEM&#xff09;&#xff0c;需要注意 02 提取DEM 这里我就使用gdal去提取一下DEM列…

./ 相对路径与node程序的启动目录有关

node:internal/fs/sync:78 return binding.openSync( ^ Error: ENOENT: no such file or directory, open D:\前端的学习之路\项目\codeHub\keys\private_key.pem at Object.open (node:internal/fs/sync:78:18) at Object.openSync (node:fs:565:…

Java后台面试相关知识点解析

文章目录 JavaJava中四种引用类型及使用场景集合HashMap源码及扩容策略HashMap死循环问题ConcurrentHashMap与HashtableConCurrentHashMap 1.8 相比 1.7判断单链表是否有环&#xff0c;并且找出环的入口 IO线程池线程池的几种创建方式判断线程是否可以回收线程池的7大核心参数线…

菜鸟学会Linux的方法

系统安装是初学者的门槛&#xff0c;系统安装完毕后&#xff0c; 很多初学者不知道该如何学习&#xff0c;不知道如何快速进阶&#xff0c; 下面作者总结了菜鸟学好Linux技能的大绝招&#xff1a; 初学者完成Linux系统分区及安装之后&#xff0c;需熟练掌握Linux系统管理必备命…

蓝桥省赛倒计时 35 天-bfs 和 dfs

#include <iostream> using namespace std; int t; int m,n; char mp[55][55];//不能写成 int 数组 bool vis[55][55]; int dx[ ]{1,0,-1,0},dy[ ]{0,1,0,-1}; int res;void dfs_1(int x,int y){vis[x][y] true;//陆地向四个方向拓展for(int i0;i<4;i){int nx xdx[i…

蓝桥杯练习系统(算法训练)ALGO-973 唯一的傻子

资源限制 内存限制&#xff1a;256.0MB C/C时间限制&#xff1a;1.0s Java时间限制&#xff1a;3.0s Python时间限制&#xff1a;5.0s 问题描述 腿铮找2255有点事&#xff0c;但2255太丑了&#xff0c;所以腿铮不知道他的长相。正愁不知道到如何找他的时候&#xff0c;…

基于React低代码平台开发:直击最新高效应用构建

&#x1f3e1;浩泽学编程&#xff1a;个人主页 &#x1f525; 推荐专栏&#xff1a;《深入浅出SpringBoot》《java对AI的调用开发》 《RabbitMQ》《Spring》《SpringMVC》《项目实战》 &#x1f6f8;学无止境&#xff0c;不骄不躁&#xff0c;知行合一 文章目录…

2024鸿蒙迎来大爆发,有必要转行鸿蒙开发吗?

鸿蒙开发&#xff0c;这个名字最近在科技圈引起了不小的轰动。 那么&#xff0c;鸿蒙开发到底是什么呢&#xff1f;它又能给我们带来怎样的影响呢&#xff1f; 鸿蒙开发&#xff0c;简单来说&#xff0c;就是基于鸿蒙操作系统的一种应用开发方式。鸿蒙系统&#xff0c;作为华为…

记录 Dubbo+Zookeeper 学习Demo

DubboZookeeper ZookeeperZookeeper 下载可能出现的问题 辅助程序下载dubbo-admin项目打包工程打包常见问题 SpringBoot集成Dubbo项目依赖定义服务接口服务端实现服务端配置依赖代码实现 消费端实现服务端配置依赖代码实现 启动 结合Dubbo官网学习如何完成SpringBootDubboZooke…

webstorm 保存自动格式化

webstorm 保存自动格式化 全局安装 prettier npm i -g prettierwebstorm设置

谷歌seo外链重要还是内容重要?

想做网站&#xff0c;内容跟外链缺一不可&#xff0c;如果真的要说哪个更重要&#xff0c;那内容依旧是网站的核心&#xff0c;而外链则是额外的加分项 内容永远是王道&#xff0c;不管谷歌seo的算法怎么变&#xff0c;只要你的内容没问题&#xff0c;那就肯定不会牵扯到你的网…

【牛客】HJ73 计算日期到天数转换

目录 题目链接:计算日期到天数转换_牛客题霸_牛客网 (nowcoder.com) 解题思路: 代码实现: 题目链接:计算日期到天数转换_牛客题霸_牛客网 (nowcoder.com) 解题思路: 用一个数组存放每月的天数 输入的日期天数 当月的天数 当月之前的累积天数 如果包含二月&#xff0c;再去判…

新一代国产人工心脏推出,《2024心衰器械白皮书》重磅发布

2024年3月2日&#xff0c;永仁心医疗“EVA-Pulsar™新品发布会”在京举办。在国内外众多领域知名专家、投资人、企业家的共同见证下&#xff0c;永仁心最新一代EVA-Pulsar™人工心脏&#xff08;心室辅助装置&#xff09;重磅发布。 这款人工心脏集长期植入、超小体积、脉动血…

报错:Nginx 部署后刷新页面 404 问题

文章目录 问题分析解决 问题 在部署完项目后 刷新页面&#xff0c;页面进入了404 分析 加载单页应用后路由改变均由浏览器处理&#xff0c;而刷新时将会请求当前的链接&#xff0c;而Nginx无法找到对应的页面 关键代码try_files,剩下俩如果其他地方配置了则可以省略。 在这…

CentOS 7 基于开源项目制作openssh 9.7p1二进制rpm包(内含ssh-copy-id、显示openssl版本信息)—— 筑梦之路

可参考之前的文章&#xff1a;CentOS 5/6/7 基于开源项目制作openssh 9.6p1 rpm包—— 筑梦之路_centos6 openssh9.6rpm-CSDN博客 2024年3月12日 植树节制作&#xff0c;相关文件见我的资源

【Golang】Windows与Linux交叉编译保姆级教程

【Golang】Windows与Linux交叉编译 大家好 我是寸铁&#x1f44a; 总结了一篇【golang】Windows与Linux交叉编译的文章✨ 喜欢的小伙伴可以点点关注 &#x1f49d; 问题背景 今天寸铁想将Windows中的程序部到Linux下跑&#xff0c;我们知道在从Windows与Linux下要进行交叉编译…

韶音运动耳机好用吗?南卡、墨觉、韶音骨传导耳机三款全面评测

音乐是我生活中不可或缺的调味品&#xff0c;它伴随着我度过了无数个清晨的慢跑以及夜晚的悠闲散步。但是传统入耳式耳机总是让我感到不适&#xff0c;虽然它有着不错的降噪能力&#xff0c;但是很容易忽视周围环境的安全&#xff0c;而且运动的时候老容易掉。然后我遇到了骨传…

程序员如何设定人生目标?用OW64曼陀罗计划表!

工作后&#xff0c;我们常常过着十分紧凑的生活&#xff0c;要做的事很多&#xff0c;时间却很少&#xff0c;尤其是现在快节奏的生活&#xff0c;我们时常面临各种任务和目标&#xff0c;如何有效地管理目标和时间&#xff0c;成了一个关键问题。这个时候&#xff0c;曼陀罗计…

Spring Cloud Gateway基础内容(一)

文章目录 参考文章一、Gateway概述1、工作原理概述2、gateway特点 &#xff08;官方描述&#xff09;3、网关的重要性&#xff08;来自尚硅谷&#xff09;4、基础配置 二、简单实现SpringCloudnacos1、新建Spring项目2、添加基础的配置文件3、添加gateway配置断言规则 三、网关…

游戏行业需要堡垒机吗?用哪款堡垒机好?

相信大家对于游戏都不陌生&#xff0c;上到老&#xff0c;下到小&#xff0c;越来越多的小伙伴开始玩游戏。随着游戏用户的增加&#xff0c;如何保障用户资料安全&#xff0c;如何确保游戏公司数据安全等是一个不容忽视的问题。因此不少人在问&#xff0c;游戏行业需要堡垒机吗…