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

想在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 thisdomain 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 requestsurl1 = '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 thisdomain 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 tqdmproxies = {'http': 'socks5h://localhost:1080','https': 'socks5h://localhost:1080'
}#使用uuid4()函数生成一个唯一的会话ID,用于在请求的标头中加以标识
SESSIONID = uuid4().hexVOCAB_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 chunksprogress.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.requestprint(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 pipelineconfig = 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_pretrainedconfig_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_dictconfig_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_dictresolved_config_file = cached_file(^^^^^^^^^^^^File "/home/wxf/lib/anaconda/envs/transformers/lib/python3.11/site-packages/transformers/utils/hub.py", line 441, in cached_fileraise 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.mzph.cn/news/739480.shtml

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

相关文章

前端css 纯数字或者字母 溢出不换行

问题&#xff1a;一个div元素盒子 宽度固定 内容是中文到达盒子宽度放不下时会自动换行&#xff0c;但是如果输入的事纯数字或者字母 会发现内容区会溢出 异常现象&#xff1a;11111超出div盒子 解决方案&#xff1a;添加属性 word-break: break-all; 原理&#xff1a;浏览器…

Spring Data的Repositories----自定义存储库实现

【Spring连载】使用Spring Data的Repositories----自定义存储库实现 一、定制单个存储库1.1 配置1.2 歧义的解决1.3 手动装配 二、自定义基础存储库 Spring Data提供了各种选项&#xff0c;可以用很少的编码来创建查询方法。但是&#xff0c;当这些选项不能满足你的需求时&…

13年老鸟整理,性能测试技术知识体系总结,从零开始打通...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 从个人的实践经验…

多线程案例及常用模式

一.单例模式——经典的设计模式 什么是单例模式&#xff1a;就是规定一个类只能创建一个对象&#xff0c;也就是保证某个类在程序中只存在唯一一个实例&#xff0c;而不会创建出多个实例 根据对象创建的时机不同&#xff0c;可以分为饿汉模式和懒汉模式 1.饿汉模式 在类加载…

Cloudflare Tunnel:无惧DDOS_随时随地安全访问局域网Web应用

利用此方法&#xff0c;您可以在局域网&#xff08;尤其是NAS&#xff09;上搭建的Web应用支持公网访问&#xff0c;成本低而且操作简单&#xff01; 如果这是博客的话&#xff0c;它还可以有效防止DDOS攻击&#xff01; 准备工作&#xff1a; 需要一个域名&#xff08;推荐N…

类模板和函数模板

在 C 中&#xff0c;类模板和函数模板是用来创建通用类型的模板&#xff0c;允许在编写代码时将类型参数化。这种泛型编程方式可以帮助我们编写更通用、更灵活的代码&#xff0c;提高代码的重用性和可维护性。 类模板&#xff08;Class Templates&#xff09; 类模板允许在类定…

服务端请求伪造(SSRF)

漏洞概述 服务器会根据用户提交的 URL 发送一个 HTTP 请求。使用用户指定的 URL &#xff0c; Web 应用可以获取图片或者文件资源等。典型的例子是百度识图功能。 如果没有对用户提交 URL 和远端服务器所返回的信息做合适的验证或过滤&#xff0c;就有可能存在 “ 请求伪造…

【微服务学习笔记(二)】Docker、RabbitMQ、SpringAMQP、Elasticseach

【微服务学习笔记&#xff08;二&#xff09;】Docker、RabbitMQ、SpringAMQP、Elasticseach Docker镜像和容器安装基础命令Dockerfile自定义镜像 MQ&#xff08;服务异步通讯&#xff09;RabbitMQ安装使用消息模型 SpringAMQP消息发送消息接收Work Queue 工作队列发布订阅Fano…

抖音小店精选联盟关闭了,是什么原因?怎么解决?

大家好&#xff0c;我是电商糖果 不知道大家有没有出现这样的情况&#xff0c;店铺后台的精选联盟莫名其妙的关闭了。 这里糖果就来给大家列举一下&#xff0c;出现联盟关闭的几种原因&#xff0c;以及怎么解决。 第一种&#xff1a;体验分低于70 这个是联盟关闭最常出现的情…

Python中的运算符介绍

前言: 零基础学Python:Python从0到100最新最全教程。 想做这件事情很久了,这次我更新了自己所写过的所有博客,汇集成了Python从0到100,共一百节课,帮助大家一个月时间里从零基础到学习Python基础语法、Python爬虫、Web开发、 计算机视觉、机器学习、神经网络以及人工智能…

使用Docker搭建Caddy

使用Docker搭建Caddy&#xff0c;可以快速部署一个轻量级的、支持自动HTTPS的web服务器。下面将分别介绍使用Docker CLI和Docker Compose两种方式来搭建Caddy服务器&#xff0c;并给出配置文件示例以及参数解释。 使用Docker CLI搭建Caddy 首先&#xff0c;确保你的系统上已安…

VR全景在智慧园区中的应用

VR全景如今以及广泛的应用于生产制造业、零售、展厅、房产等领域&#xff0c;如今720云VR全景更是在智慧园区的建设中&#xff0c;以其独特的优势&#xff0c;发挥着越来越重要的作用。VR全景作为打造智慧园区的重要角色和呈现方式已经受到了越来越多智慧园区企业的选择和应用。…

vue3 实现一个tab切换组件

一. 效果图 二. 代码 文件 WqTab.vue: <template><div ref"wqTabs" class"wq-tab"><template v-for"tab in tabs" :key"tab"><div class"tab-item" :class"{ ac: tabActive tab.key }" c…

网络地址转换协议NAT

网络地址转换协议NAT NAT的定义 NAT&#xff08;Network Address Translation&#xff0c;网络地址转换&#xff09;是1994年提出的。当在专用网内部的一些主机本来已经分配到了本地IP地址&#xff08;即仅在本专用网内使用的专用地址&#xff09;&#xff0c;但现在又想和因…

浏览器缓存 四种缓存分类 两种缓存类型

浏览器缓存 本文主要包含以下内容&#xff1a; 什么是浏览器缓存按照缓存位置分类 Service WorkerMemory CacheDisk CachePush Cache 按照缓存类型分类 强制缓存协商缓存 缓存读取规则浏览器行为 什么是浏览器缓存 在正式开始讲解浏览器缓存之前&#xff0c;我们先来回顾一…

Python 的练手项目有哪些值得推荐?

Python 是一种强大的编程语言&#xff0c;有许多值得推荐的练手项目。以下是一些例子&#xff1a; 数据分析&#xff1a;利用 Python 的数据分析库&#xff08;如 pandas 和 NumPy&#xff09;处理和分析数据。你可以尝试对数据进行清洗、可视化&#xff0c;或者构建简单的预测…

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

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

C++ 错误: 不能将“System::Object^“类型的值分配到“double“类型的实体

错误信息&#xff1a; 错误: 不能将"System::Object^"类型的值分配到"double"类型的实体 解决方案&#xff1a; 这个错误在C/CLI编程环境下出现&#xff0c;是因为你正在尝试将.NET类型System::Object^&#xff08;托管对象指针&#xff09;直接赋值给一…

个人博客网站前端页面的实现

博客网站前端页面的实现 博客登录页 相关代码 login.html <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><…

8U VPX通用系统平台

19” 上架机箱&#xff0c;8U高 ? 外形尺寸532.6mm x 482.6mm x 387.2mm (HxWxD)&#xff0c; ? 前部支持12个标准6U5HP板卡插槽&#xff0c;2个6U10HP VPX电源插槽 ? 支持12个标准6U5HP RTM卡插槽 ? 底部可拆卸风扇盘&#xff0c;散热风道由下至上 ?…