Deep-sea commited on
Commit
ce28db5
·
verified ·
1 Parent(s): 914e3a0

Update Dockerfile

Browse files
Files changed (1) hide show
  1. Dockerfile +93 -44
Dockerfile CHANGED
@@ -8,8 +8,8 @@ RUN apk update && \
8
  apk add python3 py3-pip git && \
9
  pip3 install --break-system-packages --upgrade pip
10
 
11
- # 安装 Python 包
12
- RUN pip3 install --break-system-packages watchdog huggingface_hub aiohttp
13
 
14
  # 预创建 Gitea 所需目录并设置权限
15
  RUN mkdir -p /data/gitea/conf /data/gitea/log /data/gitea/git /data/git /data/ssh && \
@@ -23,14 +23,33 @@ import shutil
23
  from huggingface_hub import snapshot_download
24
  import logging
25
  import base64
 
 
26
 
27
- # 配置日志
 
28
  logging.basicConfig(
29
  level=logging.INFO,
30
- format='%(asctime)s - %(levelname)s - %(message)s'
 
31
  )
32
  logger = logging.getLogger(__name__)
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  def pull_from_hf_hub(repo_id, data_directory="/data"):
35
  """从 Hugging Face Hub 数据集仓库拉取数据替换 /data 目录"""
36
  # 硬编码的 base64 编码的 HF_TOKEN
@@ -109,7 +128,7 @@ if __name__ == "__main__":
109
  exit(1)
110
  EOF
111
 
112
- # 复制上传脚本,移除检测到事件日志
113
  COPY --chown=git:git <<'EOF' /uploadhf.py
114
  import os
115
  import time
@@ -123,14 +142,33 @@ from watchdog.observers import Observer
123
  from watchdog.events import FileSystemEventHandler
124
  from huggingface_hub import HfApi
125
  import base64
 
 
126
 
127
- # 配置日志
 
128
  logging.basicConfig(
129
  level=logging.INFO,
130
- format='%(asctime)s - %(levelname)s - %(message)s'
 
131
  )
132
  logger = logging.getLogger(__name__)
133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  class DataDirectoryHandler(FileSystemEventHandler):
135
  """处理 /data 目录文件变化的监控器"""
136
 
@@ -252,7 +290,7 @@ def start_gitea_server(port=7860):
252
  return gitea_thread
253
 
254
  async def main():
255
- """主函数 - 启动 Gitea 和目录监控服务"""
256
  # 配置参数
257
  CONFIG = {
258
  "data_directory": "/data",
@@ -261,44 +299,56 @@ async def main():
261
  "gitea_port": 7860
262
  }
263
 
264
- logger.info("🚀 启动集成服务...")
 
265
 
266
- try:
267
- # 先运行 pullhf.py 拉取最新数据集
268
- logger.info("运行 pullhf.py 拉取最新数据集")
269
- pull_result = subprocess.run(["python3", "/pullhf.py"], check=True)
270
- if pull_result.returncode != 0:
271
- logger.error("❌ pullhf.py 执行失败,退出")
272
- exit(1)
273
-
274
- # 启动 Gitea 服务器
275
- gitea_thread = start_gitea_server(CONFIG["gitea_port"])
276
-
277
- # 启动目录监控服务
278
- observer = start_directory_monitoring(
279
- data_directory=CONFIG["data_directory"],
280
- repo_id=CONFIG["repo_id"],
281
- hf_token=CONFIG["hf_token"]
282
- )
283
-
284
- logger.info("✅ 所有服务已启动完成!")
285
- logger.info("📁 目录监控: /data → Hugging Face Hub")
286
- logger.info("🌐 Gitea 服务: http://localhost:7860")
287
- logger.info("🛑 按 Ctrl+C 停止所有服务")
288
-
289
  try:
290
- while True:
291
- await asyncio.sleep(1)
292
- except KeyboardInterrupt:
293
- logger.info("正在停止服务...")
294
 
295
- except Exception as e:
296
- logger.error(f" 启动服务时发生错误: {e}")
297
- finally:
298
- if 'observer' in locals():
299
- observer.stop()
300
- observer.join()
301
- logger.info("所有服务已停止")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
 
303
  if __name__ == "__main__":
304
  asyncio.run(main())
@@ -332,5 +382,4 @@ ENV GITEA__database__DB_TYPE=sqlite3 \
332
  USER git
333
 
334
  # 运行 Gitea,显式指定 Spaces 默认端口
335
- RUN cat /uploadhf.py
336
  CMD ["/set_gitea_env.sh", "python3", "/uploadhf.py"]
 
8
  apk add python3 py3-pip git && \
9
  pip3 install --break-system-packages --upgrade pip
10
 
11
+ # 安装 Python 包,包括 pytz 用于处理时区
12
+ RUN pip3 install --break-system-packages watchdog huggingface_hub aiohttp pytz
13
 
14
  # 预创建 Gitea 所需目录并设置权限
15
  RUN mkdir -p /data/gitea/conf /data/gitea/log /data/gitea/git /data/git /data/ssh && \
 
23
  from huggingface_hub import snapshot_download
24
  import logging
25
  import base64
26
+ from datetime import datetime
27
+ import pytz
28
 
29
+ # 配置日志,使用北京时间
30
+ beijing_tz = pytz.timezone('Asia/Shanghai')
31
  logging.basicConfig(
32
  level=logging.INFO,
33
+ format='%(asctime)s - %(levelname)s - %(message)s',
34
+ datefmt='%Y-%m-%d %H:%M:%S %Z'
35
  )
36
  logger = logging.getLogger(__name__)
37
 
38
+ # 自定义日志格式化器以使用北京时间
39
+ class BeijingTimeFormatter(logging.Formatter):
40
+ def formatTime(self, record, datefmt=None):
41
+ dt = datetime.fromtimestamp(record.created, tz=beijing_tz)
42
+ if datefmt:
43
+ return dt.strftime(datefmt)
44
+ return dt.strftime("%Y-%m-%d %H:%M:%S %Z")
45
+
46
+ # 应用自定义格式化器
47
+ for handler in logging.getLogger().handlers:
48
+ handler.setFormatter(BeijingTimeFormatter(
49
+ fmt='%(asctime)s - %(levelname)s - %(message)s',
50
+ datefmt='%Y-%m-%d %H:%M:%S %Z'
51
+ ))
52
+
53
  def pull_from_hf_hub(repo_id, data_directory="/data"):
54
  """从 Hugging Face Hub 数据集仓库拉取数据替换 /data 目录"""
55
  # 硬编码的 base64 编码的 HF_TOKEN
 
128
  exit(1)
129
  EOF
130
 
131
+ # 复制上传脚本,移除检测到事件日志,修改日志为北京时间,添加崩溃重启功能
132
  COPY --chown=git:git <<'EOF' /uploadhf.py
133
  import os
134
  import time
 
142
  from watchdog.events import FileSystemEventHandler
143
  from huggingface_hub import HfApi
144
  import base64
145
+ from datetime import datetime
146
+ import pytz
147
 
148
+ # 配置日志,使用北京时间
149
+ beijing_tz = pytz.timezone('Asia/Shanghai')
150
  logging.basicConfig(
151
  level=logging.INFO,
152
+ format='%(asctime)s - %(levelname)s - %(message)s',
153
+ datefmt='%Y-%m-%d %H:%M:%S %Z'
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)
161
+ if datefmt:
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',
169
+ datefmt='%Y-%m-%d %H:%M:%S %Z'
170
+ ))
171
+
172
  class DataDirectoryHandler(FileSystemEventHandler):
173
  """处理 /data 目录文件变化的监控器"""
174
 
 
290
  return gitea_thread
291
 
292
  async def main():
293
+ """主函数 - 启动 Gitea 和目录监控服务,带崩溃重启功能"""
294
  # 配置参数
295
  CONFIG = {
296
  "data_directory": "/data",
 
299
  "gitea_port": 7860
300
  }
301
 
302
+ max_retries = 5
303
+ retry_count = 0
304
 
305
+ while retry_count < max_retries:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  try:
307
+ logger.info(f"🚀 启动集成服务 (尝试 {retry_count + 1}/{max_retries})...")
 
 
 
308
 
309
+ # 先运行 pullhf.py 拉取最新数据集
310
+ logger.info("运行 pullhf.py 拉取最新数据集")
311
+ pull_result = subprocess.run(["python3", "/pullhf.py"], check=True)
312
+ if pull_result.returncode != 0:
313
+ logger.error("❌ pullhf.py 执行失败,退出")
314
+ exit(1)
315
+
316
+ # 启动 Gitea 服务器
317
+ gitea_thread = start_gitea_server(CONFIG["gitea_port"])
318
+
319
+ # 启动目录监控服务
320
+ observer = start_directory_monitoring(
321
+ data_directory=CONFIG["data_directory"],
322
+ repo_id=CONFIG["repo_id"],
323
+ hf_token=CONFIG["hf_token"]
324
+ )
325
+
326
+ logger.info("✅ 所有服务已启动完成!")
327
+ logger.info("📁 目录监控: /data → Hugging Face Hub")
328
+ logger.info("🌐 Gitea 服务: http://localhost:7860")
329
+ logger.info("🛑 按 Ctrl+C 停止所有服务")
330
+
331
+ try:
332
+ while True:
333
+ await asyncio.sleep(1)
334
+ except KeyboardInterrupt:
335
+ logger.info("正在停止服务...")
336
+ break
337
+
338
+ except Exception as e:
339
+ retry_count += 1
340
+ logger.error(f"❌ 服务崩溃 (尝试 {retry_count}/{max_retries}): {e}")
341
+ if retry_count < max_retries:
342
+ logger.info(f"将在 5 秒后尝试重启...")
343
+ await asyncio.sleep(5)
344
+ else:
345
+ logger.error(f"❌ 达到最大重试次数 ({max_retries}),退出")
346
+ exit(1)
347
+ finally:
348
+ if 'observer' in locals():
349
+ observer.stop()
350
+ observer.join()
351
+ logger.info("所有服务已停止")
352
 
353
  if __name__ == "__main__":
354
  asyncio.run(main())
 
382
  USER git
383
 
384
  # 运行 Gitea,显式指定 Spaces 默认端口
 
385
  CMD ["/set_gitea_env.sh", "python3", "/uploadhf.py"]