Update Dockerfile
Browse files- Dockerfile +9 -31
Dockerfile
CHANGED
|
@@ -140,11 +140,14 @@ from pathlib import Path
|
|
| 140 |
from watchdog.observers import Observer
|
| 141 |
from watchdog.events import FileSystemEventHandler
|
| 142 |
from huggingface_hub import HfApi
|
| 143 |
-
from huggingface_hub
|
| 144 |
import base64
|
| 145 |
from datetime import datetime
|
| 146 |
import pytz
|
| 147 |
|
|
|
|
|
|
|
|
|
|
| 148 |
# 配置日志,使用北京时间
|
| 149 |
beijing_tz = pytz.timezone('Asia/Shanghai')
|
| 150 |
logging.basicConfig(
|
|
@@ -154,7 +157,7 @@ logging.basicConfig(
|
|
| 154 |
)
|
| 155 |
logger = logging.getLogger(__name__)
|
| 156 |
|
| 157 |
-
# 自定义日志格式化器
|
| 158 |
class BeijingTimeFormatter(logging.Formatter):
|
| 159 |
def formatTime(self, record, datefmt=None):
|
| 160 |
dt = datetime.fromtimestamp(record.created, tz=beijing_tz)
|
|
@@ -162,7 +165,6 @@ class BeijingTimeFormatter(logging.Formatter):
|
|
| 162 |
return dt.strftime(datefmt)
|
| 163 |
return dt.strftime("%Y-%m-%d %H:%M:%S %Z")
|
| 164 |
|
| 165 |
-
# 应用自定义格式化器
|
| 166 |
for handler in logging.getLogger().handlers:
|
| 167 |
handler.setFormatter(BeijingTimeFormatter(
|
| 168 |
fmt='%(asctime)s - %(levelname)s - %(message)s',
|
|
@@ -170,47 +172,39 @@ for handler in logging.getLogger().handlers:
|
|
| 170 |
))
|
| 171 |
|
| 172 |
class DataDirectoryHandler(FileSystemEventHandler):
|
| 173 |
-
"""处理 /data 目录文件变化的监控器"""
|
| 174 |
-
|
| 175 |
def __init__(self, repo_id, hf_token, data_directory="/data"):
|
| 176 |
self.repo_id = repo_id
|
| 177 |
self.hf_token = hf_token
|
| 178 |
self.data_directory = data_directory
|
| 179 |
self.api = HfApi(token=hf_token)
|
| 180 |
self.last_commit_time = 0
|
| 181 |
-
self.commit_delay = 1
|
| 182 |
-
self.pending_changes = []
|
| 183 |
logger.info(f"初始化监控器,监控目录: {data_directory},目标仓库: {repo_id}")
|
| 184 |
|
| 185 |
def on_any_event(self, event):
|
| 186 |
-
"""捕获所有文件系统事件"""
|
| 187 |
if event.is_directory:
|
| 188 |
return
|
| 189 |
self.pending_changes.append((event.event_type, event.src_path))
|
| 190 |
self.schedule_commit(f"文件{event.event_type}")
|
| 191 |
|
| 192 |
def schedule_commit(self, change_type):
|
| 193 |
-
"""安排提交任务,带有防抖机制"""
|
| 194 |
current_time = time.time()
|
| 195 |
if current_time - self.last_commit_time > self.commit_delay:
|
| 196 |
self.last_commit_time = current_time
|
| 197 |
asyncio.run(self.commit_changes(change_type))
|
| 198 |
|
| 199 |
async def commit_changes(self, change_type):
|
| 200 |
-
"""异步提交变更到 Hugging Face Hub,带重试机制 + 全局禁用进度条"""
|
| 201 |
max_retries = 3
|
| 202 |
retry_delay = 5
|
| 203 |
change_summary = f"{change_type} ({len(self.pending_changes)} 文件)"
|
| 204 |
-
self.pending_changes = []
|
| 205 |
|
| 206 |
for attempt in range(max_retries):
|
| 207 |
try:
|
| 208 |
commit_message = f"自动提交: {change_summary} - {time.strftime('%Y-%m-%d %H:%M:%S')}"
|
| 209 |
logger.info(f"开始上传: {commit_message}")
|
| 210 |
|
| 211 |
-
# 全局禁用所有 Hugging Face 进度条
|
| 212 |
-
disable_progress_bars()
|
| 213 |
-
|
| 214 |
await asyncio.to_thread(
|
| 215 |
self.api.upload_folder,
|
| 216 |
folder_path=self.data_directory,
|
|
@@ -220,27 +214,18 @@ class DataDirectoryHandler(FileSystemEventHandler):
|
|
| 220 |
ignore_patterns=["*.tmp", "*.log", "*.temp", ".git/*"]
|
| 221 |
)
|
| 222 |
|
| 223 |
-
# 恢复进度条(防止影响其他库)
|
| 224 |
-
enable_progress_bars()
|
| 225 |
-
|
| 226 |
logger.info(f"成功提交变更到 Hugging Face Hub: {commit_message}")
|
| 227 |
return
|
| 228 |
|
| 229 |
except Exception as e:
|
| 230 |
-
# 出错时也恢复进度条
|
| 231 |
-
enable_progress_bars()
|
| 232 |
logger.error(f"提交失败 (尝试 {attempt + 1}/{max_retries}): {e}")
|
| 233 |
if attempt < max_retries - 1:
|
| 234 |
logger.info(f"将在 {retry_delay} 秒后重试...")
|
| 235 |
await asyncio.sleep(retry_delay)
|
| 236 |
|
| 237 |
-
# 最终失败也恢复
|
| 238 |
-
enable_progress_bars()
|
| 239 |
logger.error(f"达到最大重试次数,上传失败")
|
| 240 |
|
| 241 |
def start_directory_monitoring(data_directory="/data", repo_id=None, hf_token=None):
|
| 242 |
-
"""启动目录监控服务"""
|
| 243 |
-
# 硬编码的 base64 编码的 HF_TOKEN
|
| 244 |
if not hf_token:
|
| 245 |
hf_token_encoded = "aGZfcXllTEJnUUtPb2FUbHBMZ0FuTGFGTmJPV2xjUUtJT0VycQ=="
|
| 246 |
hf_token = base64.b64decode(hf_token_encoded).decode('utf-8')
|
|
@@ -267,7 +252,6 @@ def start_directory_monitoring(data_directory="/data", repo_id=None, hf_token=No
|
|
| 267 |
return observer
|
| 268 |
|
| 269 |
def start_gitea_server(port=7860):
|
| 270 |
-
"""启动 Gitea 服务器"""
|
| 271 |
def run_gitea():
|
| 272 |
try:
|
| 273 |
gitea_process = subprocess.Popen(
|
|
@@ -306,8 +290,6 @@ def start_gitea_server(port=7860):
|
|
| 306 |
return gitea_thread
|
| 307 |
|
| 308 |
async def main():
|
| 309 |
-
"""主函数 - 启动 Gitea 和目录监控服务,带崩溃重启功能"""
|
| 310 |
-
# 配置参数
|
| 311 |
CONFIG = {
|
| 312 |
"data_directory": "/data",
|
| 313 |
"repo_id": os.getenv("REPO_ID", "02engine/02gitea"),
|
|
@@ -322,17 +304,13 @@ async def main():
|
|
| 322 |
try:
|
| 323 |
logger.info(f"启动集成服务 (尝试 {retry_count + 1}/{max_retries})...")
|
| 324 |
|
| 325 |
-
# 先运行 pullhf.py 拉取最新数据集
|
| 326 |
logger.info("运行 pullhf.py 拉取最新数据集")
|
| 327 |
pull_result = subprocess.run(["python3", "/pullhf.py"], check=True)
|
| 328 |
if pull_result.returncode != 0:
|
| 329 |
logger.error("pullhf.py 执行失败,退出")
|
| 330 |
exit(1)
|
| 331 |
|
| 332 |
-
# 启动 Gitea 服务器
|
| 333 |
gitea_thread = start_gitea_server(CONFIG["gitea_port"])
|
| 334 |
-
|
| 335 |
-
# 启动目录监控服务
|
| 336 |
observer = start_directory_monitoring(
|
| 337 |
data_directory=CONFIG["data_directory"],
|
| 338 |
repo_id=CONFIG["repo_id"],
|
|
@@ -340,7 +318,7 @@ async def main():
|
|
| 340 |
)
|
| 341 |
|
| 342 |
logger.info("所有服务已启动完成!")
|
| 343 |
-
logger.info("目录监控: /data
|
| 344 |
logger.info("Gitea 服务: http://localhost:7860")
|
| 345 |
logger.info("按 Ctrl+C 停止所有服务")
|
| 346 |
|
|
|
|
| 140 |
from watchdog.observers import Observer
|
| 141 |
from watchdog.events import FileSystemEventHandler
|
| 142 |
from huggingface_hub import HfApi
|
| 143 |
+
from huggingface_hub import utils # 关键:正确导入
|
| 144 |
import base64
|
| 145 |
from datetime import datetime
|
| 146 |
import pytz
|
| 147 |
|
| 148 |
+
# 全局禁用所有 Hugging Face 进度条(启动时立即执行)
|
| 149 |
+
utils.disable_progress_bars()
|
| 150 |
+
|
| 151 |
# 配置日志,使用北京时间
|
| 152 |
beijing_tz = pytz.timezone('Asia/Shanghai')
|
| 153 |
logging.basicConfig(
|
|
|
|
| 157 |
)
|
| 158 |
logger = logging.getLogger(__name__)
|
| 159 |
|
| 160 |
+
# 自定义日志格式化器
|
| 161 |
class BeijingTimeFormatter(logging.Formatter):
|
| 162 |
def formatTime(self, record, datefmt=None):
|
| 163 |
dt = datetime.fromtimestamp(record.created, tz=beijing_tz)
|
|
|
|
| 165 |
return dt.strftime(datefmt)
|
| 166 |
return dt.strftime("%Y-%m-%d %H:%M:%S %Z")
|
| 167 |
|
|
|
|
| 168 |
for handler in logging.getLogger().handlers:
|
| 169 |
handler.setFormatter(BeijingTimeFormatter(
|
| 170 |
fmt='%(asctime)s - %(levelname)s - %(message)s',
|
|
|
|
| 172 |
))
|
| 173 |
|
| 174 |
class DataDirectoryHandler(FileSystemEventHandler):
|
|
|
|
|
|
|
| 175 |
def __init__(self, repo_id, hf_token, data_directory="/data"):
|
| 176 |
self.repo_id = repo_id
|
| 177 |
self.hf_token = hf_token
|
| 178 |
self.data_directory = data_directory
|
| 179 |
self.api = HfApi(token=hf_token)
|
| 180 |
self.last_commit_time = 0
|
| 181 |
+
self.commit_delay = 1
|
| 182 |
+
self.pending_changes = []
|
| 183 |
logger.info(f"初始化监控器,监控目录: {data_directory},目标仓库: {repo_id}")
|
| 184 |
|
| 185 |
def on_any_event(self, event):
|
|
|
|
| 186 |
if event.is_directory:
|
| 187 |
return
|
| 188 |
self.pending_changes.append((event.event_type, event.src_path))
|
| 189 |
self.schedule_commit(f"文件{event.event_type}")
|
| 190 |
|
| 191 |
def schedule_commit(self, change_type):
|
|
|
|
| 192 |
current_time = time.time()
|
| 193 |
if current_time - self.last_commit_time > self.commit_delay:
|
| 194 |
self.last_commit_time = current_time
|
| 195 |
asyncio.run(self.commit_changes(change_type))
|
| 196 |
|
| 197 |
async def commit_changes(self, change_type):
|
|
|
|
| 198 |
max_retries = 3
|
| 199 |
retry_delay = 5
|
| 200 |
change_summary = f"{change_type} ({len(self.pending_changes)} 文件)"
|
| 201 |
+
self.pending_changes = []
|
| 202 |
|
| 203 |
for attempt in range(max_retries):
|
| 204 |
try:
|
| 205 |
commit_message = f"自动提交: {change_summary} - {time.strftime('%Y-%m-%d %H:%M:%S')}"
|
| 206 |
logger.info(f"开始上传: {commit_message}")
|
| 207 |
|
|
|
|
|
|
|
|
|
|
| 208 |
await asyncio.to_thread(
|
| 209 |
self.api.upload_folder,
|
| 210 |
folder_path=self.data_directory,
|
|
|
|
| 214 |
ignore_patterns=["*.tmp", "*.log", "*.temp", ".git/*"]
|
| 215 |
)
|
| 216 |
|
|
|
|
|
|
|
|
|
|
| 217 |
logger.info(f"成功提交变更到 Hugging Face Hub: {commit_message}")
|
| 218 |
return
|
| 219 |
|
| 220 |
except Exception as e:
|
|
|
|
|
|
|
| 221 |
logger.error(f"提交失败 (尝试 {attempt + 1}/{max_retries}): {e}")
|
| 222 |
if attempt < max_retries - 1:
|
| 223 |
logger.info(f"将在 {retry_delay} 秒后重试...")
|
| 224 |
await asyncio.sleep(retry_delay)
|
| 225 |
|
|
|
|
|
|
|
| 226 |
logger.error(f"达到最大重试次数,上传失败")
|
| 227 |
|
| 228 |
def start_directory_monitoring(data_directory="/data", repo_id=None, hf_token=None):
|
|
|
|
|
|
|
| 229 |
if not hf_token:
|
| 230 |
hf_token_encoded = "aGZfcXllTEJnUUtPb2FUbHBMZ0FuTGFGTmJPV2xjUUtJT0VycQ=="
|
| 231 |
hf_token = base64.b64decode(hf_token_encoded).decode('utf-8')
|
|
|
|
| 252 |
return observer
|
| 253 |
|
| 254 |
def start_gitea_server(port=7860):
|
|
|
|
| 255 |
def run_gitea():
|
| 256 |
try:
|
| 257 |
gitea_process = subprocess.Popen(
|
|
|
|
| 290 |
return gitea_thread
|
| 291 |
|
| 292 |
async def main():
|
|
|
|
|
|
|
| 293 |
CONFIG = {
|
| 294 |
"data_directory": "/data",
|
| 295 |
"repo_id": os.getenv("REPO_ID", "02engine/02gitea"),
|
|
|
|
| 304 |
try:
|
| 305 |
logger.info(f"启动集成服务 (尝试 {retry_count + 1}/{max_retries})...")
|
| 306 |
|
|
|
|
| 307 |
logger.info("运行 pullhf.py 拉取最新数据集")
|
| 308 |
pull_result = subprocess.run(["python3", "/pullhf.py"], check=True)
|
| 309 |
if pull_result.returncode != 0:
|
| 310 |
logger.error("pullhf.py 执行失败,退出")
|
| 311 |
exit(1)
|
| 312 |
|
|
|
|
| 313 |
gitea_thread = start_gitea_server(CONFIG["gitea_port"])
|
|
|
|
|
|
|
| 314 |
observer = start_directory_monitoring(
|
| 315 |
data_directory=CONFIG["data_directory"],
|
| 316 |
repo_id=CONFIG["repo_id"],
|
|
|
|
| 318 |
)
|
| 319 |
|
| 320 |
logger.info("所有服务已启动完成!")
|
| 321 |
+
logger.info("目录监控: /data to Hugging Face Hub")
|
| 322 |
logger.info("Gitea 服务: http://localhost:7860")
|
| 323 |
logger.info("按 Ctrl+C 停止所有服务")
|
| 324 |
|