Spaces:
Sleeping
Sleeping
Create check_port.py
Browse files- check_port.py +39 -0
check_port.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# 由 Copilot 生成 - 端口測試腳本
|
| 3 |
+
|
| 4 |
+
import socket
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
def find_free_port(start_port=7860, max_attempts=10):
|
| 8 |
+
"""尋找可用的端口"""
|
| 9 |
+
for port in range(start_port, start_port + max_attempts):
|
| 10 |
+
try:
|
| 11 |
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
| 12 |
+
s.bind(('0.0.0.0', port))
|
| 13 |
+
print(f"端口 {port} 可用")
|
| 14 |
+
return port
|
| 15 |
+
except OSError:
|
| 16 |
+
print(f"端口 {port} 被佔用")
|
| 17 |
+
continue
|
| 18 |
+
return None
|
| 19 |
+
|
| 20 |
+
if __name__ == "__main__":
|
| 21 |
+
print("檢查可用端口...")
|
| 22 |
+
|
| 23 |
+
# 檢查環境變數
|
| 24 |
+
env_port = os.environ.get("GRADIO_SERVER_PORT") or os.environ.get("PORT")
|
| 25 |
+
if env_port:
|
| 26 |
+
print(f"環境變數指定端口: {env_port}")
|
| 27 |
+
|
| 28 |
+
# 檢查 Hugging Face Spaces 環境
|
| 29 |
+
if "SPACE_ID" in os.environ:
|
| 30 |
+
print("檢測到 Hugging Face Spaces 環境")
|
| 31 |
+
print(f"SPACE_ID: {os.environ.get('SPACE_ID')}")
|
| 32 |
+
|
| 33 |
+
# 尋找可用端口
|
| 34 |
+
free_port = find_free_port()
|
| 35 |
+
if free_port:
|
| 36 |
+
print(f"建議使用端口: {free_port}")
|
| 37 |
+
os.environ["GRADIO_SERVER_PORT"] = str(free_port)
|
| 38 |
+
else:
|
| 39 |
+
print("未找到可用端口")
|