from flask import Flask, request, jsonify, Response, render_template_string import os import time import gc import threading import sys import urllib.parse import subprocess from datetime import datetime import signal import psutil import glob import re import pytz 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 def jupyter(): os.system('jupyter lab --ip=0.0.0.0 --port=8002 --no-browser --allow-root --notebook-dir=/data --NotebookApp.token=qilan --ServerApp.disable_check_xsrf=True') # threading.Thread(target=jupyter, daemon=True).start() app = Flask(__name__) # HTML 页面内容 HTML_PAGE = """ Flask 应用

🚀 Flask 应用主页

欢迎来到 Flask 应用!这是一个简单的 HTML 页面。

您可以访问以下端点:

/hello - JSON API / - 主页
""" def compress_folder(folder_path, output_dir): try: # 确保输出目录存在 os.makedirs(output_dir, exist_ok=True) # 使用 pytz 获取中国时区的当前时间戳(毫秒级) import pytz from datetime import datetime # 设置中国时区 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 # 如果压缩包数量超过5个,删除最旧的 if len(existing_archives) >= 5: # 按时间戳排序 existing_archives.sort(key=extract_timestamp) # 删除最旧的压缩包 oldest_archive = existing_archives[0] os.remove(oldest_archive) print(f"删除最旧的压缩包:{oldest_archive}") # tar.gz 压缩 result = subprocess.run( ['tar', '-czvf', 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}") # 返回压缩包名和大小信息 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}') 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.chdir(f'/data/{HF_REPO}') if type == 2: os.chdir(f'/data/{HF_REPO}') print("开始备份上传HF") # 清理 LFS 存储 os.system('git lfs prune') # 备份上传仓库 new_archive_info = compress_folder('/data/dv1', f'/data/{HF_REPO}') if new_archive_info: new_archive, file_size_info = new_archive_info.split(' MB:') os.system(f'git add .') os.system(f'git commit -m "{file_size_info}"') # os.system('git push -u origin main') # 使用强制推送并清理 os.system('git push -f origin main') os.system('git gc --prune=now') else: print("压缩失败,无法提交") @app.route('/') def index(): """根路由,返回 HTML 页面""" return render_template_string(HTML_PAGE) @app.route('/hello', methods=['GET']) def hello(): return jsonify({"message": "Hello, World!"}) @app.route('/greet', methods=['POST']) def greet(): data = request.json name = data.get('name', 'Guest') return jsonify({"greeting": f"Hello, {name}!"}) @app.route('/bf', methods=['GET']) def bf(): github(2) return jsonify({"message": "OK"}) @app.route('/log', methods=['GET']) def get_log_content(): try: # 使用绝对路径读取文件 file_path = '/data/app.log' # 检查文件是否存在 if not os.path.exists(file_path): return jsonify({"error": "File not found"}), 404 # 读取最近的日志内容,限制大小 with open(file_path, 'r', encoding='utf-8') as file: # 读取最后1000行 lines = file.readlines()[-1000:] content = ''.join(lines) # 处理中文和换行 return Response( content, mimetype='text/plain; charset=utf-8' ) except PermissionError: return jsonify({"error": "Permission denied to read the file"}), 403 except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/sub', methods=['GET']) def get_sub_content(): try: # 使用绝对路径读取文件 file_path = '/data/sub.txt' # 检查文件是否存在 if not os.path.exists(file_path): return jsonify({"error": "File not found"}), 404 # 读取文件内容 with open(file_path, 'r', encoding='utf-8') as file: content = file.read() # return jsonify({"content": content}) return content except PermissionError: return jsonify({"error": "Permission denied to read the file"}), 403 except Exception as e: return jsonify({"error": str(e)}), 500 def perform_cleanup(): """执行清理操作的函数""" # Python垃圾回收 collected = gc.collect() # 清理Python模块缓存 for module in list(sys.modules.keys()): if module.startswith('temp') or module.startswith('_'): del sys.modules[module] # 清理可能存在的临时文件 temp_dir = '/tmp' if os.path.exists(temp_dir) and os.access(temp_dir, os.W_OK): for f in os.listdir(temp_dir): if f.startswith('flask-') or f.startswith('tmp'): try: os.remove(os.path.join(temp_dir, f)) except: pass return collected @app.route('/xx', methods=['GET']) def system_info(): try: # 检查是否有清理参数 cleanup = request.args.get('cleanup', 'false').lower() == 'true' # 如果需要清理,执行清理操作 if cleanup: # 在后台线程中执行清理,避免阻塞请求 def cleanup_task(): collected = perform_cleanup() print(f"清理完成,回收了 {collected} 个对象") thread = threading.Thread(target=cleanup_task) thread.daemon = True thread.start() cleanup_message = "已开始执行清理操作(Python垃圾回收和临时文件清理)\n\n" else: cleanup_message = "" # 获取CPU信息 cpu_cores = os.cpu_count() # 获取CPU使用率 - 使用/proc/stat计算 def get_cpu_usage(): with open('/proc/stat', 'r') as f: lines = f.readlines() for line in lines: if line.startswith('cpu '): fields = line.split() total_time = sum(int(x) for x in fields[1:]) idle_time = int(fields[4]) return total_time, idle_time return 0, 0 # 第一次读取 total1, idle1 = get_cpu_usage() time.sleep(0.1) # 短暂延迟 # 第二次读取 total2, idle2 = get_cpu_usage() if total2 - total1 > 0: cpu_usage = 100 * (1 - (idle2 - idle1) / (total2 - total1)) else: cpu_usage = 0 # 获取内存信息 with open('/proc/meminfo', 'r') as f: mem_lines = f.readlines() mem_total = 0 mem_available = 0 mem_free = 0 for line in mem_lines: if line.startswith('MemTotal:'): mem_total = int(line.split()[1]) elif line.startswith('MemAvailable:'): mem_available = int(line.split()[1]) elif line.startswith('MemFree:'): mem_free = int(line.split()[1]) mem_used = mem_total - mem_available if mem_available > 0 else mem_total - mem_free mem_usage_percent = 100 * mem_used / mem_total if mem_total > 0 else 0 # 转换为GB mem_total_gb = round(mem_total / 1024 / 1024, 2) mem_used_gb = round(mem_used / 1024 / 1024, 2) mem_free_gb = round(mem_free / 1024 / 1024, 2) # 获取系统运行时间 with open('/proc/uptime', 'r') as f: uptime_seconds = float(f.readline().split()[0]) # 格式化运行时间 uptime_days = int(uptime_seconds // 86400) uptime_hours = int((uptime_seconds % 86400) // 3600) uptime_minutes = int((uptime_seconds % 3600) // 60) # 获取负载平均值 with open('/proc/loadavg', 'r') as f: load_avg = f.readline().split()[0:3] # 构建格式化的中文响应 response_text = f""" ============ 系统信息 ============ {cleanup_message} CPU信息: 核心数: {cpu_cores} 核 使用率: {cpu_usage:.2f}% 内存信息: 总内存: {mem_total_gb} GB 已使用: {mem_used_gb} GB 空闲内存: {mem_free_gb} GB 使用率: {mem_usage_percent:.2f}% 系统运行时间: {uptime_days}天 {uptime_hours}小时 {uptime_minutes}分钟 系统负载: 1分钟平均: {load_avg[0]} 5分钟平均: {load_avg[1]} 15分钟平均: {load_avg[2]} ================================== 提示: 访问 /xx?cleanup=true 可以尝试清理Python资源 注意: 由于权限限制,只能清理Python层面的资源 """ print(response_text) return Response(response_text, mimetype='text/plain; charset=utf-8') except Exception as e: error_text = f"获取系统信息时出错: {str(e)}" return Response(error_text, mimetype='text/plain; charset=utf-8'), 500 if __name__ == '__main__': app.run(host='0.0.0.0', port=7860, debug=True)