import os import shutil import platform import time import threading import requests import gradio as gr import psutil try: import spaces import torch HAS_SPACES = True except ImportError: HAS_SPACES = False # --------------------------------------------------------------------------- # Telegram Default Configuration # --------------------------------------------------------------------------- DEFAULT_BOT_TOKEN = os.environ.get("TG_BOT_TOKEN", "8845031533:AAF0LPdd5P3HWV_b2PyGGWIWcQs-_slffIU") DEFAULT_CHANNEL_ID = os.environ.get("TG_CHANNEL_ID", "") SELF_URL = os.environ.get("SPACE_HOST", "https://prajwalg4230-fluxcloud.hf.space") # --------------------------------------------------------------------------- # 24/7 Self-Keep-Alive Heartbeat Daemon Thread # --------------------------------------------------------------------------- heartbeat_state = { "total_pings": 0, "last_ping_time": "Initializing...", "last_ping_status": "Active (Loop Running)", "started_at": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()), } def self_keep_alive_daemon(): time.sleep(25) # wait for space to be ready while True: try: r = requests.get(SELF_URL, timeout=12) heartbeat_state["total_pings"] += 1 heartbeat_state["last_ping_time"] = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()) heartbeat_state["last_ping_status"] = f"HTTP {r.status_code} OK (Awake)" except Exception as e: heartbeat_state["last_ping_time"] = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()) heartbeat_state["last_ping_status"] = f"Ping note: {str(e)[:35]}" time.sleep(600) # Ping every 10 minutes (HF timeout is 48 hours) heartbeat_thread = threading.Thread(target=self_keep_alive_daemon, daemon=True) heartbeat_thread.start() # --------------------------------------------------------------------------- # System Stats & Hardware Inspector # --------------------------------------------------------------------------- def get_system_stats(): mem = psutil.virtual_memory() total_ram = round(mem.total / (1024 ** 3), 2) free_ram = round(mem.available / (1024 ** 3), 2) ram_pct = mem.percent disk = shutil.disk_usage("/") total_disk = round(disk.total / (1024 ** 3), 2) free_disk = round(disk.free / (1024 ** 3), 2) cpu_count = os.cpu_count() cpu_pct = psutil.cpu_percent(interval=0.3) return f""" ### 📊 Hugging Face Space Live Status: | Resource | Allocated / Total | Free / Available | Usage % | | :--- | :--- | :--- | :--- | | 🧠 **RAM (Memory)** | **`{total_ram} GB`** | **`{free_ram} GB`** | `{ram_pct}%` | | 💾 **Disk Storage** | **`{total_disk} GB`** | **`{free_disk} GB`** | `{round((1 - free_disk/total_disk)*100, 1)}%` | | âš™ī¸ **CPU Cores** | **`{cpu_count} vCPUs`** | Active | `{cpu_pct}%` | | 🔄 **24/7 Keep-Alive** | `{heartbeat_state['total_pings']} Pings` | Status: `{heartbeat_state['last_ping_status']}` | Last: `{heartbeat_state['last_ping_time']}` | | 🌐 **Endpoint Host** | `{SELF_URL}` | Protocol: HTTPS | Ready | """ # --------------------------------------------------------------------------- # Telegram Upload & Stream Operations # --------------------------------------------------------------------------- def telegram_upload_action(file_obj, bot_token_input, channel_id_input): if not file_obj: return "âš ī¸ Please select a file first.", "" token = bot_token_input.strip() if bot_token_input else DEFAULT_BOT_TOKEN chat = channel_id_input.strip() if channel_id_input else DEFAULT_CHANNEL_ID if not token or not chat: return "❌ Error: Both Telegram Bot Token and Channel ID are required.", "" file_path = file_obj.name if hasattr(file_obj, 'name') else str(file_obj) file_name = os.path.basename(file_path) try: with open(file_path, "rb") as fp: resp = requests.post( f"https://api.telegram.org/bot{token}/sendDocument", data={"chat_id": chat}, files={"document": (file_name, fp)}, timeout=120 ) if resp.status_code == 200 and resp.json().get("ok"): res = resp.json()["result"] doc = res.get("document") or res.get("video") or res.get("audio") fid = doc["file_id"] if doc else str(res["message_id"]) msg = f""" ✅ **Upload to Telegram SUCCESSFUL!** - 📁 **File Name:** `{file_name}` - 🆔 **Telegram File ID:** `{fid}` - đŸ’Ŧ **Message ID:** `{res['message_id']}` - â˜ī¸ **Stored In:** Channel `{chat}` *(You can now paste this File ID into the 'Fetch & Stream from Telegram' tool below to access it instantly!)* """ return msg, fid else: return f"❌ Upload Failed: {resp.text}", "" except Exception as e: return f"❌ Error: {str(e)}", "" def telegram_stream_fetch(file_id_input, bot_token_input): fid = file_id_input.strip() if file_id_input else "" token = bot_token_input.strip() if bot_token_input else DEFAULT_BOT_TOKEN if not fid or not token: return None, "âš ī¸ Please provide both Telegram File ID and Bot Token." try: info_resp = requests.get( f"https://api.telegram.org/bot{token}/getFile?file_id={fid}", timeout=20 ) if info_resp.status_code != 200 or not info_resp.json().get("ok"): return None, f"❌ Failed to resolve file info: {info_resp.text}" file_path = info_resp.json()["result"]["file_path"] download_url = f"https://api.telegram.org/file/bot{token}/{file_path}" # Download to local temp cache to stream/serve via Gradio local_filename = os.path.basename(file_path) local_target = os.path.join("/tmp", local_filename) with requests.get(download_url, stream=True, timeout=180) as r: r.raise_for_status() with open(local_target, "wb") as f: for chunk in r.iter_content(chunk_size=128 * 1024): f.write(chunk) file_size_mb = round(os.path.getsize(local_target) / (1024 * 1024), 2) return local_target, f"✅ **File Stream Ready!** `{local_filename}` ({file_size_mb} MB) successfully fetched from Telegram." except Exception as e: return None, f"❌ Stream error: {str(e)}" # --------------------------------------------------------------------------- # ZeroGPU probe # --------------------------------------------------------------------------- if HAS_SPACES: @spaces.GPU(duration=5) def test_gpu_quota(): start = time.time() if torch.cuda.is_available(): dev_name = torch.cuda.get_device_name(0) vram = round(torch.cuda.get_device_properties(0).total_memory / (1024 ** 3), 2) lat = round(time.time() - start, 3) return f"✅ **ZeroGPU Active!** `{dev_name}` ({vram} GB VRAM) allocated in `{lat}s`." return "âš ī¸ CUDA unavailable" else: def test_gpu_quota(): return "â„šī¸ ZeroGPU module not present in this runtime." # --------------------------------------------------------------------------- # UI Layout # --------------------------------------------------------------------------- with gr.Blocks(theme=gr.themes.Soft(), title="FluxCloud 24/7 Telegram & System Hub") as demo: gr.Markdown("# ⚡ FluxCloud 24/7 Engine & Telegram Storage Hub") gr.Markdown(f"Permanent Host: `{SELF_URL}` | **24/7 Automated Keep-Alive Active**") with gr.Tabs(): with gr.TabItem("📊 System Status & 24/7 Monitor"): with gr.Row(): refresh_btn = gr.Button("🔄 Refresh Stats", variant="primary") gpu_test_btn = gr.Button("🎮 Probe ZeroGPU Quota", variant="secondary") stats_display = gr.Markdown(value=get_system_stats) gpu_display = gr.Markdown(value="*Click 'Probe ZeroGPU Quota' to test dynamic GPU allocation.*") refresh_btn.click(fn=get_system_stats, outputs=stats_display) gpu_test_btn.click(fn=test_gpu_quota, outputs=gpu_display) with gr.TabItem("🤖 Telegram Cloud Storage & Streamer"): gr.Markdown("### 1. Upload to Telegram Cloud Channel") with gr.Row(): token_box = gr.Textbox(label="Telegram Bot Token", value=DEFAULT_BOT_TOKEN, placeholder="Enter Bot Token") channel_box = gr.Textbox(label="Channel ID / Chat ID", value=DEFAULT_CHANNEL_ID, placeholder="-100xxxxxxxxxx or @channel") test_file = gr.File(label="Choose File to Upload") upload_btn = gr.Button("🚀 Upload to Telegram Cloud", variant="primary") tg_output = gr.Markdown(label="Upload Result") cached_fid = gr.Textbox(label="Generated File ID", interactive=False) upload_btn.click( fn=telegram_upload_action, inputs=[test_file, token_box, channel_box], outputs=[tg_output, cached_fid], ) gr.Markdown("---") gr.Markdown("### 2. Stream / Download File on Demand from Telegram") with gr.Row(): fid_input = gr.Textbox(label="Telegram File ID to Stream", placeholder="Paste File ID here") stream_btn = gr.Button("â–ļī¸ Fetch & Stream from Telegram", variant="secondary") stream_status = gr.Markdown() streamed_file_output = gr.File(label="Streamed Media / File") stream_btn.click( fn=telegram_stream_fetch, inputs=[fid_input, token_box], outputs=[streamed_file_output, stream_status], ) demo.launch()