Spaces:
Sleeping
Sleeping
File size: 3,172 Bytes
80c0e03 |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
#!/usr/bin/env python3
"""
启动脚本 - 设置环境变量以解决 Hugging Face Spaces 中的权限问题
"""
import os
import tempfile
import sys
def setup_environment():
"""设置所有必要的环境变量"""
# 检测是否在 Hugging Face Spaces 中运行
is_hf_space = bool(os.environ.get('SPACE_ID') or os.environ.get('HF_SPACE_ID'))
if is_hf_space:
print("检测到 Hugging Face Spaces 环境,设置临时目录...")
# 创建临时目录
temp_base = tempfile.mkdtemp()
# 设置 matplotlib 配置目录
matplotlib_dir = os.path.join(temp_base, "matplotlib")
os.makedirs(matplotlib_dir, exist_ok=True)
os.environ["MPLCONFIGDIR"] = matplotlib_dir
# 设置 XDG 缓存目录
os.environ["XDG_CACHE_HOME"] = temp_base
# 设置 numba 缓存目录
numba_dir = os.path.join(temp_base, "numba_cache")
os.makedirs(numba_dir, exist_ok=True)
os.environ["NUMBA_CACHE_DIR"] = numba_dir
# 设置 Hugging Face 缓存目录
hf_dir = os.path.join(temp_base, "hf_cache")
os.makedirs(hf_dir, exist_ok=True)
os.environ["HF_HOME"] = hf_dir
os.environ["HF_HUB_CACHE"] = os.path.join(hf_dir, "hub")
print(f"环境变量已设置:")
print(f" MPLCONFIGDIR: {matplotlib_dir}")
print(f" XDG_CACHE_HOME: {temp_base}")
print(f" NUMBA_CACHE_DIR: {numba_dir}")
print(f" HF_HOME: {hf_dir}")
print(f" HF_HUB_CACHE: {os.environ['HF_HUB_CACHE']}")
else:
print("本地环境,使用默认缓存目录")
return is_hf_space
def check_imports():
"""检查关键导入是否正常工作"""
try:
print("检查导入...")
# 检查 langchain 相关导入
from langchain_community.embeddings import HuggingFaceEmbeddings
print("✅ langchain_community.embeddings 导入成功")
from langchain_text_splitters import RecursiveCharacterTextSplitter
print("✅ langchain_text_splitters 导入成功")
# 检查其他关键库
import torch
print("✅ PyTorch 导入成功")
import transformers
print("✅ Transformers 导入成功")
import matplotlib
print("✅ Matplotlib 导入成功")
import numba
print("✅ Numba 导入成功")
return True
except ImportError as e:
print(f"❌ 导入失败: {e}")
return False
if __name__ == "__main__":
print("=== 环境设置脚本 ===")
# 设置环境变量
is_hf_space = setup_environment()
# 检查导入
if check_imports():
print("\n✅ 环境设置完成,所有导入正常")
if is_hf_space:
print("💡 提示: 在 Hugging Face Spaces 中使用临时目录作为缓存")
else:
print("💡 提示: 在本地环境中使用默认缓存目录")
else:
print("\n❌ 环境设置失败,请检查依赖安装")
sys.exit(1) |