fongci commited on
Commit
5efaf20
·
1 Parent(s): 984fc95

Update application

Browse files
Files changed (1) hide show
  1. app.py +64 -1
app.py CHANGED
@@ -1,8 +1,71 @@
 
 
1
  from fastapi import FastAPI
 
2
 
3
- app = FastAPI()
4
 
5
  @app.get("/")
6
  def greet_json():
7
  return {"Hello": "World!"}
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
  from fastapi import FastAPI
4
+ from typing import Dict, Any
5
 
6
+ app = FastAPI(title="Hugging Face Space Monitor", version="1.0.0")
7
 
8
  @app.get("/")
9
  def greet_json():
10
  return {"Hello": "World!"}
11
 
12
+ @app.get("/storage")
13
+ def get_storage_info() -> Dict[str, Any]:
14
+ """取得目前 Space 的存儲使用情況"""
15
+ try:
16
+ # 取得根目錄的磁碟使用情況
17
+ total, used, free = shutil.disk_usage("/")
18
+
19
+ # 取得當前工作目錄大小
20
+ app_size = get_directory_size("/app")
21
+
22
+ # 取得 /tmp 目錄使用情況(臨時檔案)
23
+ tmp_size = get_directory_size("/tmp")
24
+
25
+ return {
26
+ "disk_usage": {
27
+ "total_bytes": total,
28
+ "used_bytes": used,
29
+ "free_bytes": free,
30
+ "total_gb": round(total / (1024**3), 2),
31
+ "used_gb": round(used / (1024**3), 2),
32
+ "free_gb": round(free / (1024**3), 2),
33
+ "usage_percentage": round((used / total) * 100, 2)
34
+ },
35
+ "application": {
36
+ "app_size_bytes": app_size,
37
+ "app_size_mb": round(app_size / (1024**2), 2),
38
+ "tmp_size_bytes": tmp_size,
39
+ "tmp_size_mb": round(tmp_size / (1024**2), 2)
40
+ },
41
+ "environment": {
42
+ "current_dir": os.getcwd(),
43
+ "space_id": os.getenv("SPACE_ID", "unknown"),
44
+ "space_author": os.getenv("SPACE_AUTHOR_NAME", "unknown")
45
+ }
46
+ }
47
+ except Exception as e:
48
+ return {"error": str(e)}
49
+
50
+ def get_directory_size(path: str) -> int:
51
+ """計算目錄大小"""
52
+ total_size = 0
53
+ try:
54
+ for dirpath, dirnames, filenames in os.walk(path):
55
+ for filename in filenames:
56
+ filepath = os.path.join(dirpath, filename)
57
+ try:
58
+ total_size += os.path.getsize(filepath)
59
+ except (OSError, FileNotFoundError):
60
+ continue
61
+ except (OSError, FileNotFoundError):
62
+ pass
63
+ return total_size
64
+
65
+ @app.get("/health")
66
+ def health_check():
67
+ """健康檢查端點"""
68
+ return {
69
+ "status": "healthy",
70
+ "message": "Space is running normally"
71
+ }