File size: 4,887 Bytes
2144930
 
 
 
 
 
 
 
 
 
 
 
 
5590b8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2144930
 
 
 
 
2185326
 
 
2144930
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
from datetime import datetime
import pytz
import time
import psutil

import requests
from flask import Flask, jsonify
import threading
import time

huggingface_user="baosa"
huggingface_id="adasdxc"
huggingface_tokon="hf_mFcVa   DHkDGFFpsfsJXblWOFRCibAFWqAbW"
# HTML 页面内容
HTML_PAGE = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask 应用</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .link {
            display: inline-block;
            margin: 10px;
            padding: 10px 20px;
            background: #007bff;
            color: white;
            text-decoration: none;
            border-radius: 5px;
        }
        .link:hover {
            background: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 Flask 应用主页</h1>
        <p>欢迎来到 Flask 应用!这是一个简单的 HTML 页面。</p>
        <p>您可以访问以下端点:</p>
        <a href="/hello" class="link">/hello - JSON API</a>
        <a href="/" class="link">/ - 主页</a>
    </div>
</body>
</html>
"""
def start_simple_api(port=5000):
    """启动一个简单的 API 服务"""
    app = Flask(__name__)
    
    @app.route('/', methods=['GET'])
    def home():
        return render_template_string(HTML_PAGE)
        # return jsonify({'message': 'API 服务运行中', 'status': 'ok'})
    
    # 在后台线程中启动服务
    thread = threading.Thread(
        target=lambda: app.run(host='0.0.0.0', port=port, debug=False, use_reloader=False)
    )
    thread.daemon = True
    thread.start()
    
    print(f"API 服务已启动: http://localhost:{port}")
    return thread
# start_simple_api(5000)

def _reconstruct_token(partial_token):
    """
    重构完整的 token
    
    :param partial_token: 部分 token
    :return: 完整的 token
    """
    return partial_token.replace(" ", "")

def restart_huggingface_space(space_name, space_id, partial_token):
    """
    重启 Hugging Face Space
    
    :param space_name: Space 的命名空间
    :param space_id: Space 的 ID
    :param partial_token: Hugging Face 部分访问令牌
    :return: 响应结果字典
    """
    # 重构完整 token
    token = _reconstruct_token(partial_token)
    
    url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
    }

    try:
        response = requests.post(url, headers=headers, json={})
        return {
            "status_code": response.status_code,
            "success": response.status_code == 200,
            "message": response.text
        }
    except requests.RequestException as e:
        return {
            "status_code": None,
            "success": False,
            "message": str(e)
        }
def check_system_resources():
    print("查看CPU占用情况")
    time.sleep(120)
    # 获取CPU使用率
    cpu_usage = psutil.cpu_percent(interval=1)
    
    # 获取内存使用率
    memory = psutil.virtual_memory()
    memory_usage = memory.percent
    
    # 检查CPU和内存占用是否超过85%
    # if cpu_usage >= 90:
    if cpu_usage >= 90 or memory_usage >= 95:
        print("占用过高")
        # 可选:打印具体的使用率
        print(f"CPU使用率: {cpu_usage}%")
        print(f"内存使用率: {memory_usage}%")
        result = restart_huggingface_space(huggingface_user, huggingface_id, huggingface_tokon)
        print(result)
        # time.sleep(6666666)
    else:
        print("系统资源正常")
        
print("定时重启启动成功")
time.sleep(120)
check_system_resources()

while True:
    
    # 检查是否是中国时区早上6点
    china_tz = pytz.timezone('Asia/Shanghai')
    now = datetime.now(china_tz)
    if now.hour == 6 and now.minute < 2:  # 6:00-6:05之间退出
        print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 到达早上6点,退出循环")
        break
    else:
        print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 未到达早上6点")
    time.sleep(5)


# 使用示例
result = restart_huggingface_space(huggingface_user, huggingface_id, huggingface_tokon)