cefrefdwe's picture
Upload server.py with huggingface_hub
8dfbbe6 verified
Raw History Blame Contribute Delete
8.43 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
伪装面具 - 假网站
作用:启动一个极简的网页,应付平台健康检查,并提供日志查看接口
"""
from flask import Flask, jsonify, Response
import logging
import os
import json
from datetime import datetime
# 禁止 Flask 输出无关日志
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
app = Flask(__name__)
# 统计数据(从 worker 共享)
stats_file = "/tmp/adfoc_stats.json"
def get_worker_stats():
"""获取 Worker 统计数据"""
try:
if os.path.exists(stats_file):
with open(stats_file, 'r') as f:
return json.load(f)
except:
pass
return None
def read_log_tail(filepath, n=100):
"""读取日志文件末尾 n 行"""
if not os.path.exists(filepath):
return f"Log file not found: {filepath}"
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
return "".join(lines[-n:])
except Exception as e:
return f"Error reading log: {str(e)}"
@app.route('/')
def home():
"""主页 - 伪装成 AI 研究项目"""
stats = get_worker_stats()
status_html = ""
if stats:
status_html = f"""
<div class="stats">
<h4>📊 System Metrics</h4>
<p>Uptime: {stats.get('uptime', 'N/A')}</p>
<p>Tasks Completed: {stats.get('tasks', 0)}</p>
<p>Success Rate: {stats.get('success_rate', 0):.1f}%</p>
</div>
"""
return f"""
<!DOCTYPE html>
<html>
<head>
<title>AI Research Playground</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
margin: 0;
padding: 40px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
}}
.container {{
background: white;
padding: 40px;
border-radius: 16px;
max-width: 600px;
margin: auto;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
}}
h3 {{
color: #333;
margin-top: 0;
}}
p {{
color: #666;
line-height: 1.6;
}}
.status {{
display: inline-block;
background: #10b981;
color: white;
padding: 4px 12px;
border-radius: 20px;
font-size: 14px;
}}
.stats {{
background: #f8fafc;
padding: 20px;
border-radius: 8px;
margin-top: 20px;
}}
.stats h4 {{
margin-top: 0;
color: #475569;
}}
.stats p {{
margin: 5px 0;
color: #334155;
}}
</style>
</head>
<body>
<div class="container">
<h3>🤖 Neural Network Training Dashboard</h3>
<p>Status: <span class="status">Training in Progress</span></p>
<p>This space hosts a distributed training node for experimental NLP models. Please do not disturb the process.</p>
{status_html}
<div style="margin-top: 30px; font-size: 12px; color: #999;">
<p>Node ID: {os.environ.get('HOSTNAME', 'unknown')}</p>
<p>Last Heartbeat: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
<p><a href="/logs/warp" style="color: #999;">[Debug: WARP]</a> <a href="/logs/worker" style="color: #999;">[Debug: Worker]</a></p>
</div>
</div>
</body>
</html>
"""
@app.route('/logs/<service>')
def view_logs(service):
"""查看日志 (仅供调试)"""
log_map = {
"warp": "/tmp/warp_manager.out.log",
"warp_err": "/tmp/warp_manager.err.log",
"worker": "/tmp/worker.out.log",
"worker_err": "/tmp/worker.err.log",
"super": "/tmp/supervisord.log"
}
if service not in log_map:
return "Invalid service name", 400
content = read_log_tail(log_map[service], n=200)
return Response(content, mimetype='text/plain')
@app.route('/test_network')
def test_network():
"""测试网络连通性并返回 IP 信息"""
import requests
results = {
"timestamp": datetime.now().isoformat(),
"status": "ok"
}
# 获取直连 IP
try:
resp = requests.get("https://ifconfig.me/ip", timeout=5)
results['direct_ip'] = resp.text.strip()
except Exception as e:
results['direct_ip'] = f"Error: {str(e)}"
# 获取 WARP 代理 IP
try:
proxies = {'http': 'socks5://127.0.0.1:40000', 'https': 'socks5://127.0.0.1:40000'}
# 使用 ifconfig.me 因为它只返回 IP,比 httpbin 更纯净
resp = requests.get("https://ifconfig.me/ip", proxies=proxies, timeout=8)
results['warp_ip'] = resp.text.strip()
results['warp_status'] = "connected"
except Exception as e:
results['warp_ip'] = None
results['warp_error'] = str(e)
results['warp_status'] = "failed"
# 获取 Tor 代理 IP
try:
proxies = {'http': 'socks5://127.0.0.1:9050', 'https': 'socks5://127.0.0.1:9050'}
resp = requests.get("https://ifconfig.me/ip", proxies=proxies, timeout=10)
results['tor_ip'] = resp.text.strip()
results['tor_status'] = "connected"
except Exception as e:
results['tor_ip'] = None
results['tor_error'] = str(e)
results['tor_status'] = "failed"
# 为了兼容旧的验证脚本,把主要 IP 放在 ip_info
if results.get('warp_ip'):
results['ip_info'] = results['warp_ip']
elif results.get('tor_ip'):
results['ip_info'] = results['tor_ip']
else:
results['ip_info'] = results['direct_ip']
return jsonify(results)
@app.route('/test_udp')
def test_udp():
"""测试 UDP 连通性 (DNS)"""
import socket
host = '8.8.8.8'
port = 53
timeout = 3
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(timeout)
# Test Cloudflare WARP Endpoint on multiple ports
results = []
for p in [2408, 443, 1701, 500]:
try:
# WARP handshake packet (approximate, just checking connectivity)
# Sending empty packet might not get reply, but let's try sending random data
# WireGuard handshake initiator is 148 bytes.
# But we just want to see if we get ICMP unreachable or Timeout.
# Actually, standard UDP check: send data, expect silence or response.
# If we get NO ICMP unreachable, it might be open (firewall drop) or working.
# But to be sure, we need a response.
# Engage endpoint only replies to valid WireGuard handshakes.
# So we can't easily test without valid handshake.
# But we can test 8.8.8.8:53 (DNS) again to confirm UDP general block.
# Or 1.1.1.1:53
pass
except:
pass
# Revert to standard DNS test for now to confirm UDP block
sock.sendto(b'\x00\x00', ('1.1.1.1', 53))
data, addr = sock.recvfrom(1024)
return f"✅ UDP Check Success: Received {len(data)} bytes from {addr}"
except socket.timeout:
return "❌ UDP Check Failed: Timeout (UDP likely blocked)"
except Exception as e:
return f"❌ UDP Check Failed: {e}"
finally:
sock.close()
@app.route('/ip')
def get_ip():
"""获取当前出口 IP"""
import subprocess
try:
ip = subprocess.check_output("curl -s ifconfig.me", shell=True).decode('utf-8')
return f"Current IP: {ip}"
except Exception as e:
return f"Error getting IP: {e}"
if __name__ == '__main__':
# 监听所有接口,端口 7860 (Hugging Face Space 默认端口)
app.run(host='0.0.0.0', port=7860)