Spaces:
Running
Running
Download manage_server.py from bllndebrahim/translet: direct link, hf CLI and curl.
- Browser
- Download file 14.7 kB
-
https://huggingface.co/spaces/bllndebrahim/translet/resolve/main/manage_server.py
- Command line
-
hf download hf://spaces/bllndebrahim/translet/manage_server.py
-
curl -L -o manage_server.py https://huggingface.co/spaces/bllndebrahim/translet/resolve/main/manage_server.py
14.7 kB
| import os | |
| import sys | |
| import time | |
| import subprocess | |
| import re | |
| import socket | |
| import signal | |
| sys.stdout.reconfigure(encoding='utf-8') | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| PID_FILE = os.path.join(BASE_DIR, "server.pid") | |
| LOG_FILE = os.path.join(BASE_DIR, "tunnel_boot.log") | |
| CLOUDFLARED_EXE = os.path.join(BASE_DIR, "cloudflared.exe") | |
| SERVER_PY = os.path.join(BASE_DIR, "server.py") | |
| def get_desktop_path(): | |
| desktop = os.path.join(os.path.expanduser("~"), "Desktop") | |
| if os.path.exists(desktop): | |
| return desktop | |
| return BASE_DIR | |
| def get_local_ip(): | |
| try: | |
| s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
| s.connect(("8.8.8.8", 80)) | |
| ip = s.getsockname()[0] | |
| s.close() | |
| return ip | |
| except Exception: | |
| return "127.0.0.1" | |
| def is_port_open(port=3000): | |
| try: | |
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| s.settimeout(0.5) | |
| res = s.connect_ex(('127.0.0.1', port)) | |
| s.close() | |
| return res == 0 | |
| except Exception: | |
| return False | |
| def copy_to_clipboard(text): | |
| try: | |
| subprocess.run('clip', input=text.strip().encode('utf-8'), check=False, creationflags=0x08000000) | |
| except Exception: | |
| pass | |
| def show_windows_notification(title, msg): | |
| try: | |
| ps_cmd = f''' | |
| [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null | |
| [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null | |
| $template = @" | |
| <toast> | |
| <visual> | |
| <binding template="ToastGeneric"> | |
| <text>{title}</text> | |
| <text>{msg}</text> | |
| </binding> | |
| </visual> | |
| </toast> | |
| "@ | |
| $xml = New-Object Windows.Data.Xml.Dom.XmlDocument | |
| $xml.LoadXml($template) | |
| $toast = [Windows.UI.Notifications.ToastNotification]::new($xml) | |
| [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("Translet AI").Show($toast) | |
| ''' | |
| subprocess.run(["powershell", "-NoProfile", "-Command", ps_cmd], creationflags=0x08000000, timeout=5) | |
| except Exception: | |
| pass | |
| def update_desktop_files(public_url, local_ip): | |
| desktop = get_desktop_path() | |
| txt_path = os.path.join(desktop, "لینکی_مۆبایل.txt") | |
| url_path = os.path.join(desktop, "Translet_Mobile.url") | |
| content = f"""==================================================================== | |
| 🚀 سێرڤەری Translet بۆ مۆبایل چالاکە (ONLINE) | |
| ==================================================================== | |
| 🌟 لینکی هەمیشەیی و نەگۆڕی مۆبایلەکەت (ئەم لینکە هەرگیز ناگۆڕێت): | |
| 👉 https://lalagarmyani.alandblnd8141.workers.dev | |
| (دەتوانیت ئەم لینکە لە مۆبایلەکەت سەیڤ بکەیت یان زیادی بکەیت بۆ شاشەی سەرەکی وەک ئەپ - هەمیشە کاردەکات) | |
| 🔗 لینکی ڕاستەوخۆی Cloudflare: | |
| 👉 {public_url} | |
| 📶 ئەگەر لەسەر هەمان وایفای کۆمپیوتەرەکەت بوویت: | |
| 👉 http://{local_ip}:3000 | |
| ==================================================================== | |
| تێبینی: هەر کاتێک سێرڤەرت ویست، فایلی START دابگرە. | |
| کە تەواو بوویت، فایلی STOP دابگرە بۆ کوژاندنەوەی سێرڤەرەکە. | |
| ==================================================================== | |
| """ | |
| try: | |
| with open(txt_path, "w", encoding="utf-8") as f: | |
| f.write(content) | |
| except Exception as e: | |
| print("Failed to write desktop txt:", e) | |
| try: | |
| with open(url_path, "w", encoding="utf-8") as f: | |
| f.write(f"[InternetShortcut]\nURL={public_url}\n") | |
| except Exception as e: | |
| print("Failed to write desktop url:", e) | |
| def stop_all_services(verbose=True): | |
| """Terminates all running server and cloudflared processes.""" | |
| if verbose: | |
| print("دەستکرا بە کوژاندنەوەی سەرجەم پرۆسێسەکانی سێرڤەر...") | |
| # 1. Kill cloudflared | |
| try: | |
| subprocess.run(["taskkill", "/F", "/IM", "cloudflared.exe"], capture_output=True, creationflags=0x08000000) | |
| except Exception: | |
| pass | |
| # 2. Kill all processes on port 3000 thoroughly via PowerShell & netstat | |
| try: | |
| ps_cmd = "Get-NetTCPConnection -LocalPort 3000 -ErrorAction SilentlyContinue | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue }" | |
| subprocess.run(["powershell", "-NoProfile", "-Command", ps_cmd], capture_output=True, creationflags=0x08000000) | |
| except Exception: | |
| pass | |
| try: | |
| res = subprocess.run(['netstat', '-ano'], capture_output=True, text=True, creationflags=0x08000000) | |
| pids = set() | |
| for line in res.stdout.splitlines(): | |
| if ':3000 ' in line and ('LISTENING' in line or 'Listen' in line): | |
| parts = line.split() | |
| if parts: | |
| pids.add(parts[-1]) | |
| for pid in pids: | |
| subprocess.run(['taskkill', '/F', '/PID', pid], capture_output=True, creationflags=0x08000000) | |
| except Exception: | |
| pass | |
| # 3. Kill from PID file if exists | |
| if os.path.exists(PID_FILE): | |
| try: | |
| with open(PID_FILE, "r") as f: | |
| saved_pids = f.read().split() | |
| for p in saved_pids: | |
| try: | |
| subprocess.run(['taskkill', '/F', '/PID', p], capture_output=True, creationflags=0x08000000) | |
| except Exception: | |
| pass | |
| os.remove(PID_FILE) | |
| except Exception: | |
| pass | |
| time.sleep(1) | |
| if verbose: | |
| print("\n" + "=" * 68) | |
| print(" 🛑 سێرڤەری Translet بە تەواوی کوژایەوە (Server is OFF)") | |
| print("=" * 68) | |
| print("\n سێرڤەر و تەنێڵەکە داخران و هیچ دەنگ و پرۆسەیەک چالاک نەماوە.") | |
| print(" هەر کات ویستت دووبارە بەکاریبهێنیت، تەنها فایلی START دابگرە.\n") | |
| print("=" * 68) | |
| def print_qr_code(url): | |
| try: | |
| import qrcode | |
| qr = qrcode.QRCode(box_size=1, border=2) | |
| qr.add_data(url) | |
| qr.print_ascii(invert=True) | |
| except Exception: | |
| pass | |
| def start_services(): | |
| """Starts fresh server.py and cloudflared tunnel, displays link and QR code.""" | |
| # Step 1: Clean up any old instances first | |
| stop_all_services(verbose=False) | |
| time.sleep(1) | |
| print("\n" + "=" * 68) | |
| print(" 🚀 دەست دەکرێت بە هەڵکردنی سێرڤەری Translet AI...") | |
| print("=" * 68) | |
| # Step 2: Start server.py | |
| print("[1/3] سێرڤەری سەرەکی کارا دەکرێت (Port 3000)...") | |
| server_proc = subprocess.Popen( | |
| [sys.executable, "-u", SERVER_PY, "3000"], | |
| cwd=BASE_DIR, | |
| creationflags=0x08000000 | |
| ) | |
| # Wait for port 3000 to open | |
| for _ in range(20): | |
| if is_port_open(3000): | |
| break | |
| time.sleep(0.5) | |
| if not is_port_open(3000): | |
| print("❌ هەڵە لە کارپێکردنی server.py!") | |
| return | |
| print("✅ سێرڤەری ناوخۆیی ئامادەیە.") | |
| # Step 3: Check cloudflared.exe | |
| if not os.path.isfile(CLOUDFLARED_EXE): | |
| print("داگرتنی cloudflared.exe لە GitHub...") | |
| subprocess.run( | |
| ["curl.exe", "-L", "-o", CLOUDFLARED_EXE, "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe"], | |
| creationflags=0x08000000 | |
| ) | |
| # Step 4: Start Cloudflare Tunnel | |
| print("[2/3] تەنێڵی جیهانی (Cloudflare HTTPS) دادەمەزرێت...") | |
| if os.path.exists(LOG_FILE): | |
| try: | |
| os.remove(LOG_FILE) | |
| except Exception: | |
| try: | |
| with open(LOG_FILE, "w") as f: | |
| f.write("") | |
| except Exception: | |
| pass | |
| tunnel_proc = subprocess.Popen( | |
| [CLOUDFLARED_EXE, "tunnel", "--url", "http://localhost:3000", "--logfile", LOG_FILE], | |
| cwd=BASE_DIR, | |
| creationflags=0x08000000 | |
| ) | |
| # Step 5: Save PIDs | |
| with open(PID_FILE, "w") as f: | |
| f.write(f"{server_proc.pid} {tunnel_proc.pid}") | |
| def extract_public_url(timeout=40): | |
| for _ in range(timeout): | |
| time.sleep(1) | |
| if os.path.exists(LOG_FILE): | |
| try: | |
| with open(LOG_FILE, "r", encoding="utf-8", errors="ignore") as f: | |
| data = f.read() | |
| all_matches = re.findall(r'https://[a-zA-Z0-9\-]+\.trycloudflare\.com', data) | |
| if all_matches: | |
| return all_matches[-1] | |
| except Exception: | |
| pass | |
| return None | |
| def publish_live_url(p_url): | |
| try: | |
| import requests | |
| requests.post( | |
| "https://ntfy.sh/lala_translet_bllnd_789", | |
| data=p_url, | |
| headers={"Title": "LiveURL"}, | |
| timeout=5 | |
| ) | |
| except Exception: | |
| pass | |
| # Step 6: Extract Public URL | |
| print("[3/3] چاوەڕوانی بەستەری ڕاستەوخۆ بۆ مۆبایلەکەت...") | |
| public_url = extract_public_url(40) | |
| local_ip = get_local_ip() | |
| if not public_url: | |
| print("❌ کێشە لە وەرگرتنی لینکی Cloudflare!") | |
| print(f"دەتوانیت لەسەر هەمان وایفای بەکاریبهێنیت: http://{local_ip}:3000") | |
| return | |
| perm_url = "https://lalagarmyani.alandblnd8141.workers.dev" | |
| # Update files & clipboard | |
| update_desktop_files(public_url, local_ip) | |
| copy_to_clipboard(perm_url) | |
| show_windows_notification( | |
| "Translet AI - سێرڤەر ئۆنلاینە", | |
| f"لینکی هەمیشەیی کۆپی کرا: {perm_url}" | |
| ) | |
| # Automatically sync with Cloudflare Worker Permanent Fixed Link | |
| publish_live_url(public_url) | |
| # Display clear banner | |
| print("\n" + "=" * 68) | |
| print(" 🚀 سێرڤەری Translet بە سەرکەوتوویی هەڵکرا (Server ONLINE)") | |
| print("=" * 68) | |
| print("\n🌟 لینکی هەمیشەیی و نەگۆڕی مۆبایلەکەت (ئەم لینکە هەرگیز ناگۆڕێت):") | |
| print(f"👉 \033[92m{perm_url}\033[0m") | |
| print(f"\n🔗 بەستەری کاتیی خێرا: {public_url}") | |
| print("📋 بەستەرە هەمیشەییەکە ئۆتۆماتیکی لە کڵیپبۆرد کۆپی کرا") | |
| print("📄 هەروەها لەسەر دێسکتۆپ لە ناو 'لینکی_مۆبایل.txt' دانراوە.") | |
| print(f"📶 وایفای ناوخۆیی ماڵەوە: http://{local_ip}:3000") | |
| print("\n" + "-" * 68) | |
| print("📷 دەتوانیت کامێرای مۆبایلەکەت ڕووبەڕووی ئەم کۆدە بکەیتەوە:") | |
| print("-" * 68 + "\n") | |
| print_qr_code(perm_url) | |
| print("=" * 68) | |
| print("🟢 ئەم پەنجەرەیە مەبەستە تا سێرڤەرەکە بە کارایی و ئۆنلاین بمێنێتەوە.") | |
| print("🛑 بۆ کوژاندنەوەی سێرڤەر، فایلی STOP_SERVER دابگرە یان ئەم پەنجەرەیە دابخە.") | |
| print("=" * 68 + "\n") | |
| # High-Reliability Self-Healing Monitor loop | |
| last_keepalive_time = time.time() | |
| try: | |
| while True: | |
| time.sleep(3) | |
| # 1. Ensure server.py is running on port 3000 | |
| if not is_port_open(3000): | |
| print("⚡ سێرڤەری پایتۆن لەسەر پۆرت 3000 دووبارە کارا دەکرێتەوە...") | |
| server_proc = subprocess.Popen( | |
| [sys.executable, "-u", SERVER_PY, "3000"], | |
| cwd=BASE_DIR, | |
| creationflags=0x08000000 | |
| ) | |
| time.sleep(1) | |
| # 2. Check if tunnel died | |
| tunnel_dead = (tunnel_proc.poll() is not None) | |
| # 3. Keepalive ping every 20 seconds to prevent tunnel timeout | |
| now = time.time() | |
| if not tunnel_dead and (now - last_keepalive_time > 20): | |
| last_keepalive_time = now | |
| try: | |
| import requests | |
| requests.get("http://localhost:3000", timeout=2) | |
| if public_url: | |
| requests.head(public_url, timeout=3) | |
| except Exception: | |
| pass | |
| # 4. If tunnel died or disconnected, auto-heal and refresh Cloudflare Worker link | |
| if tunnel_dead: | |
| print("\n⚠️ تەنێڵی Cloudflare پچڕا، دەستبەجێ بە شێوەیەکی خۆکارانە دووبارە بەسترایەوە...") | |
| try: | |
| subprocess.run(["taskkill", "/F", "/IM", "cloudflared.exe"], capture_output=True, creationflags=0x08000000) | |
| except Exception: | |
| pass | |
| try: | |
| if os.path.exists(LOG_FILE): | |
| with open(LOG_FILE, "w") as f: | |
| f.write("") | |
| except Exception: | |
| pass | |
| time.sleep(15) | |
| tunnel_proc = subprocess.Popen( | |
| [CLOUDFLARED_EXE, "tunnel", "--url", "http://localhost:3000", "--logfile", LOG_FILE], | |
| cwd=BASE_DIR, | |
| creationflags=0x08000000 | |
| ) | |
| with open(PID_FILE, "w") as f: | |
| f.write(f"{server_proc.pid} {tunnel_proc.pid}") | |
| new_url = extract_public_url(timeout=30) | |
| if new_url: | |
| public_url = new_url | |
| publish_live_url(public_url) | |
| update_desktop_files(public_url, local_ip) | |
| print(f"✅ بەستەری نوێ دەستبەجێ دروستکرایەوە و مۆبایل بەستراوەیەوە:\n👉 {perm_url}\n👉 {public_url}\n") | |
| except KeyboardInterrupt: | |
| print("\nداواکاری کوژاندنەوە وەرگیرا...") | |
| stop_all_services(verbose=True) | |
| if __name__ == "__main__": | |
| if len(sys.argv) > 1 and sys.argv[1].lower() == "stop": | |
| stop_all_services(verbose=True) | |
| elif len(sys.argv) > 1 and sys.argv[1].lower() == "start": | |
| start_services() | |
| else: | |
| print("Usage: python manage_server.py [start|stop]") | |