Prajwal commited on
Commit
d4a75e5
Β·
1 Parent(s): e974dab

Pure Gradio 24/7 keep-alive and Telegram storage streamer

Browse files
Files changed (2) hide show
  1. app.py +80 -163
  2. requirements.txt +0 -4
app.py CHANGED
@@ -4,11 +4,6 @@ import platform
4
  import time
5
  import threading
6
  import requests
7
- import httpx
8
- import uvicorn
9
- from fastapi import FastAPI, UploadFile, File, Form, Request, HTTPException
10
- from fastapi.responses import StreamingResponse, JSONResponse
11
- from fastapi.middleware.cors import CORSMiddleware
12
  import gradio as gr
13
  import psutil
14
 
@@ -31,160 +26,29 @@ SELF_URL = os.environ.get("SPACE_HOST", "https://prajwalg4230-fluxcloud.hf.space
31
  # ---------------------------------------------------------------------------
32
  heartbeat_state = {
33
  "total_pings": 0,
34
- "last_ping_time": "Starting up...",
35
- "last_ping_status": "Active",
36
  "started_at": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
37
  }
38
 
39
  def self_keep_alive_daemon():
40
- time.sleep(15) # wait for uvicorn to bind port
41
  while True:
42
  try:
43
- target = f"{SELF_URL}/heartbeat"
44
- r = requests.get(target, timeout=12)
45
  heartbeat_state["total_pings"] += 1
46
  heartbeat_state["last_ping_time"] = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
47
- heartbeat_state["last_ping_status"] = f"HTTP {r.status_code} OK"
48
  except Exception as e:
49
  heartbeat_state["last_ping_time"] = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
50
  heartbeat_state["last_ping_status"] = f"Ping note: {str(e)[:35]}"
51
- time.sleep(600) # Ping every 10 minutes
52
 
53
  heartbeat_thread = threading.Thread(target=self_keep_alive_daemon, daemon=True)
54
  heartbeat_thread.start()
55
 
56
  # ---------------------------------------------------------------------------
57
- # FastAPI REST Endpoints
58
- # ---------------------------------------------------------------------------
59
- api = FastAPI(title="FluxCloud 24/7 Telegram & System Hub")
60
-
61
- api.add_middleware(
62
- CORSMiddleware,
63
- allow_origins=["*"],
64
- allow_credentials=True,
65
- allow_methods=["*"],
66
- allow_headers=["*"],
67
- )
68
-
69
- @api.get("/heartbeat")
70
- def heartbeat_endpoint():
71
- return {
72
- "status": "alive",
73
- "service": "FluxCloud 24/7 Engine",
74
- "pings": heartbeat_state["total_pings"],
75
- "last_ping": heartbeat_state["last_ping_time"],
76
- "timestamp": time.time(),
77
- }
78
-
79
- @api.post("/api/tg/upload")
80
- async def telegram_upload(
81
- file: UploadFile = File(...),
82
- bot_token: str = Form(None),
83
- channel_id: str = Form(None),
84
- ):
85
- token = bot_token.strip() if bot_token else DEFAULT_BOT_TOKEN
86
- chat = channel_id.strip() if channel_id else DEFAULT_CHANNEL_ID
87
-
88
- if not token:
89
- raise HTTPException(status_code=400, detail="Telegram Bot Token is required.")
90
- if not chat:
91
- raise HTTPException(status_code=400, detail="Telegram Channel/Chat ID is required.")
92
-
93
- file_bytes = await file.read()
94
- orig_name = file.filename or "file.bin"
95
- content_type = file.content_type or "application/octet-stream"
96
-
97
- tg_url = f"https://api.telegram.org/bot{token}/sendDocument"
98
- files = {"document": (orig_name, file_bytes, content_type)}
99
- data = {"chat_id": chat}
100
-
101
- async with httpx.AsyncClient(timeout=120) as client:
102
- resp = await client.post(tg_url, data=data, files=files)
103
-
104
- if resp.status_code != 200:
105
- return JSONResponse(
106
- status_code=resp.status_code,
107
- content={"success": False, "error": "Telegram upload failed", "detail": resp.text},
108
- )
109
-
110
- res_json = resp.json()
111
- if not res_json.get("ok"):
112
- return JSONResponse(
113
- status_code=400,
114
- content={"success": False, "error": res_json.get("description", "Unknown Telegram error")},
115
- )
116
-
117
- doc = res_json["result"].get("document") or res_json["result"].get("video") or res_json["result"].get("audio")
118
- file_id = doc["file_id"] if doc else str(res_json["result"].get("message_id"))
119
-
120
- stream_link = f"{SELF_URL}/stream/{file_id}?token={token}"
121
- download_link = f"{SELF_URL}/download/{file_id}?token={token}"
122
-
123
- return {
124
- "success": True,
125
- "file_id": file_id,
126
- "file_name": orig_name,
127
- "size": len(file_bytes),
128
- "stream_url": stream_link,
129
- "download_url": download_link,
130
- "message_id": res_json["result"]["message_id"],
131
- }
132
-
133
- @api.get("/stream/{file_id}")
134
- async def stream_file(file_id: str, token: str = None, request: Request = None):
135
- use_token = token.strip() if token else DEFAULT_BOT_TOKEN
136
- if not use_token:
137
- raise HTTPException(status_code=400, detail="Bot token is required")
138
-
139
- async with httpx.AsyncClient(timeout=20) as client:
140
- info_resp = await client.get(f"https://api.telegram.org/bot{use_token}/getFile?file_id={file_id}")
141
-
142
- if info_resp.status_code != 200:
143
- raise HTTPException(status_code=404, detail="File info could not be fetched from Telegram")
144
-
145
- info_json = info_resp.json()
146
- if not info_json.get("ok"):
147
- raise HTTPException(status_code=404, detail=info_json.get("description", "File not found on Telegram"))
148
-
149
- file_path = info_json["result"]["file_path"]
150
- download_upstream_url = f"https://api.telegram.org/file/bot{use_token}/{file_path}"
151
-
152
- client = httpx.AsyncClient(timeout=300)
153
- req_headers = {}
154
- if request and "range" in request.headers:
155
- req_headers["range"] = request.headers["range"]
156
-
157
- upstream_req = client.build_request("GET", download_upstream_url, headers=req_headers)
158
- upstream_resp = await client.send(upstream_req, stream=True)
159
-
160
- async def body_streamer():
161
- try:
162
- async for chunk in upstream_resp.aiter_bytes(chunk_size=128 * 1024):
163
- yield chunk
164
- finally:
165
- await upstream_resp.aclose()
166
- await client.aclose()
167
-
168
- headers = dict(upstream_resp.headers)
169
- headers["Access-Control-Allow-Origin"] = "*"
170
- headers["Access-Control-Allow-Methods"] = "GET, HEAD, OPTIONS"
171
- headers["Cache-Control"] = "public, max-age=86400"
172
- headers["Content-Disposition"] = f'inline; filename="{os.path.basename(file_path)}"'
173
-
174
- return StreamingResponse(
175
- body_streamer(),
176
- status_code=upstream_resp.status_code,
177
- headers=headers,
178
- )
179
-
180
- @api.get("/download/{file_id}")
181
- async def download_file(file_id: str, token: str = None, request: Request = None):
182
- resp = await stream_file(file_id, token, request)
183
- resp.headers["Content-Disposition"] = f'attachment; filename="{file_id}"'
184
- return resp
185
-
186
- # ---------------------------------------------------------------------------
187
- # Gradio Dashboard & System Inspector
188
  # ---------------------------------------------------------------------------
189
  def get_system_stats():
190
  mem = psutil.virtual_memory()
@@ -207,17 +71,21 @@ def get_system_stats():
207
  | πŸ’Ύ **Disk Storage** | **`{total_disk} GB`** | **`{free_disk} GB`** | `{round((1 - free_disk/total_disk)*100, 1)}%` |
208
  | βš™οΈ **CPU Cores** | **`{cpu_count} vCPUs`** | Active | `{cpu_pct}%` |
209
  | πŸ”„ **24/7 Keep-Alive** | `{heartbeat_state['total_pings']} Pings` | Status: `{heartbeat_state['last_ping_status']}` | Last: `{heartbeat_state['last_ping_time']}` |
 
210
  """
211
 
212
- def direct_tg_upload_gradio(file_obj, bot_token_input, channel_id_input):
 
 
 
213
  if not file_obj:
214
- return "⚠️ Please select a file first."
215
 
216
  token = bot_token_input.strip() if bot_token_input else DEFAULT_BOT_TOKEN
217
  chat = channel_id_input.strip() if channel_id_input else DEFAULT_CHANNEL_ID
218
 
219
  if not token or not chat:
220
- return "❌ Error: Both Telegram Bot Token and Channel ID are required."
221
 
222
  file_path = file_obj.name if hasattr(file_obj, 'name') else str(file_obj)
223
  file_name = os.path.basename(file_path)
@@ -236,24 +104,58 @@ def direct_tg_upload_gradio(file_obj, bot_token_input, channel_id_input):
236
  doc = res.get("document") or res.get("video") or res.get("audio")
237
  fid = doc["file_id"] if doc else str(res["message_id"])
238
 
239
- stream_url = f"{SELF_URL}/stream/{fid}?token={token}"
240
- download_url = f"{SELF_URL}/download/{fid}?token={token}"
241
-
242
- return f"""
243
  βœ… **Upload to Telegram SUCCESSFUL!**
244
 
245
  - πŸ“ **File Name:** `{file_name}`
246
  - πŸ†” **Telegram File ID:** `{fid}`
247
  - πŸ’¬ **Message ID:** `{res['message_id']}`
248
- - πŸš€ **Direct Stream Link:** [Open Stream]({stream_url})
249
- - ⬇️ **Direct Download Link:** [Download File]({download_url})
 
250
  """
 
251
  else:
252
- return f"❌ Upload Failed: {resp.text}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  except Exception as e:
254
- return f"❌ Error: {str(e)}"
255
 
256
- # ZeroGPU burst probe
 
 
257
  if HAS_SPACES:
258
  @spaces.GPU(duration=5)
259
  def test_gpu_quota():
@@ -268,6 +170,9 @@ else:
268
  def test_gpu_quota():
269
  return "ℹ️ ZeroGPU module not present in this runtime."
270
 
 
 
 
271
  with gr.Blocks(theme=gr.themes.Soft(), title="FluxCloud 24/7 Telegram & System Hub") as demo:
272
  gr.Markdown("# ⚑ FluxCloud 24/7 Engine & Telegram Storage Hub")
273
  gr.Markdown(f"Permanent Host: `{SELF_URL}` | **24/7 Automated Keep-Alive Active**")
@@ -284,8 +189,8 @@ with gr.Blocks(theme=gr.themes.Soft(), title="FluxCloud 24/7 Telegram & System H
284
  refresh_btn.click(fn=get_system_stats, outputs=stats_display)
285
  gpu_test_btn.click(fn=test_gpu_quota, outputs=gpu_display)
286
 
287
- with gr.TabItem("πŸ€– Telegram Cloud Storage Tester"):
288
- gr.Markdown("Upload any file to test direct storage into your Telegram Channel with instant streaming links.")
289
  with gr.Row():
290
  token_box = gr.Textbox(label="Telegram Bot Token", value=DEFAULT_BOT_TOKEN, placeholder="Enter Bot Token")
291
  channel_box = gr.Textbox(label="Channel ID / Chat ID", value=DEFAULT_CHANNEL_ID, placeholder="-100xxxxxxxxxx or @channel")
@@ -293,15 +198,27 @@ with gr.Blocks(theme=gr.themes.Soft(), title="FluxCloud 24/7 Telegram & System H
293
  test_file = gr.File(label="Choose File to Upload")
294
  upload_btn = gr.Button("πŸš€ Upload to Telegram Cloud", variant="primary")
295
  tg_output = gr.Markdown(label="Upload Result")
 
296
 
297
  upload_btn.click(
298
- fn=direct_tg_upload_gradio,
299
  inputs=[test_file, token_box, channel_box],
300
- outputs=tg_output,
301
  )
302
 
303
- # Mount Gradio app into FastAPI
304
- app = gr.mount_gradio_app(api, demo, path="/")
 
 
 
 
 
 
 
 
 
 
 
 
305
 
306
- if __name__ == "__main__":
307
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
4
  import time
5
  import threading
6
  import requests
 
 
 
 
 
7
  import gradio as gr
8
  import psutil
9
 
 
26
  # ---------------------------------------------------------------------------
27
  heartbeat_state = {
28
  "total_pings": 0,
29
+ "last_ping_time": "Initializing...",
30
+ "last_ping_status": "Active (Loop Running)",
31
  "started_at": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
32
  }
33
 
34
  def self_keep_alive_daemon():
35
+ time.sleep(25) # wait for space to be ready
36
  while True:
37
  try:
38
+ r = requests.get(SELF_URL, timeout=12)
 
39
  heartbeat_state["total_pings"] += 1
40
  heartbeat_state["last_ping_time"] = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
41
+ heartbeat_state["last_ping_status"] = f"HTTP {r.status_code} OK (Awake)"
42
  except Exception as e:
43
  heartbeat_state["last_ping_time"] = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
44
  heartbeat_state["last_ping_status"] = f"Ping note: {str(e)[:35]}"
45
+ time.sleep(600) # Ping every 10 minutes (HF timeout is 48 hours)
46
 
47
  heartbeat_thread = threading.Thread(target=self_keep_alive_daemon, daemon=True)
48
  heartbeat_thread.start()
49
 
50
  # ---------------------------------------------------------------------------
51
+ # System Stats & Hardware Inspector
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  # ---------------------------------------------------------------------------
53
  def get_system_stats():
54
  mem = psutil.virtual_memory()
 
71
  | πŸ’Ύ **Disk Storage** | **`{total_disk} GB`** | **`{free_disk} GB`** | `{round((1 - free_disk/total_disk)*100, 1)}%` |
72
  | βš™οΈ **CPU Cores** | **`{cpu_count} vCPUs`** | Active | `{cpu_pct}%` |
73
  | πŸ”„ **24/7 Keep-Alive** | `{heartbeat_state['total_pings']} Pings` | Status: `{heartbeat_state['last_ping_status']}` | Last: `{heartbeat_state['last_ping_time']}` |
74
+ | 🌐 **Endpoint Host** | `{SELF_URL}` | Protocol: HTTPS | Ready |
75
  """
76
 
77
+ # ---------------------------------------------------------------------------
78
+ # Telegram Upload & Stream Operations
79
+ # ---------------------------------------------------------------------------
80
+ def telegram_upload_action(file_obj, bot_token_input, channel_id_input):
81
  if not file_obj:
82
+ return "⚠️ Please select a file first.", ""
83
 
84
  token = bot_token_input.strip() if bot_token_input else DEFAULT_BOT_TOKEN
85
  chat = channel_id_input.strip() if channel_id_input else DEFAULT_CHANNEL_ID
86
 
87
  if not token or not chat:
88
+ return "❌ Error: Both Telegram Bot Token and Channel ID are required.", ""
89
 
90
  file_path = file_obj.name if hasattr(file_obj, 'name') else str(file_obj)
91
  file_name = os.path.basename(file_path)
 
104
  doc = res.get("document") or res.get("video") or res.get("audio")
105
  fid = doc["file_id"] if doc else str(res["message_id"])
106
 
107
+ msg = f"""
 
 
 
108
  βœ… **Upload to Telegram SUCCESSFUL!**
109
 
110
  - πŸ“ **File Name:** `{file_name}`
111
  - πŸ†” **Telegram File ID:** `{fid}`
112
  - πŸ’¬ **Message ID:** `{res['message_id']}`
113
+ - ☁️ **Stored In:** Channel `{chat}`
114
+
115
+ *(You can now paste this File ID into the 'Fetch & Stream from Telegram' tool below to access it instantly!)*
116
  """
117
+ return msg, fid
118
  else:
119
+ return f"❌ Upload Failed: {resp.text}", ""
120
+ except Exception as e:
121
+ return f"❌ Error: {str(e)}", ""
122
+
123
+ def telegram_stream_fetch(file_id_input, bot_token_input):
124
+ fid = file_id_input.strip() if file_id_input else ""
125
+ token = bot_token_input.strip() if bot_token_input else DEFAULT_BOT_TOKEN
126
+
127
+ if not fid or not token:
128
+ return None, "⚠️ Please provide both Telegram File ID and Bot Token."
129
+
130
+ try:
131
+ info_resp = requests.get(
132
+ f"https://api.telegram.org/bot{token}/getFile?file_id={fid}",
133
+ timeout=20
134
+ )
135
+ if info_resp.status_code != 200 or not info_resp.json().get("ok"):
136
+ return None, f"❌ Failed to resolve file info: {info_resp.text}"
137
+
138
+ file_path = info_resp.json()["result"]["file_path"]
139
+ download_url = f"https://api.telegram.org/file/bot{token}/{file_path}"
140
+
141
+ # Download to local temp cache to stream/serve via Gradio
142
+ local_filename = os.path.basename(file_path)
143
+ local_target = os.path.join("/tmp", local_filename)
144
+
145
+ with requests.get(download_url, stream=True, timeout=180) as r:
146
+ r.raise_for_status()
147
+ with open(local_target, "wb") as f:
148
+ for chunk in r.iter_content(chunk_size=128 * 1024):
149
+ f.write(chunk)
150
+
151
+ file_size_mb = round(os.path.getsize(local_target) / (1024 * 1024), 2)
152
+ return local_target, f"βœ… **File Stream Ready!** `{local_filename}` ({file_size_mb} MB) successfully fetched from Telegram."
153
  except Exception as e:
154
+ return None, f"❌ Stream error: {str(e)}"
155
 
156
+ # ---------------------------------------------------------------------------
157
+ # ZeroGPU probe
158
+ # ---------------------------------------------------------------------------
159
  if HAS_SPACES:
160
  @spaces.GPU(duration=5)
161
  def test_gpu_quota():
 
170
  def test_gpu_quota():
171
  return "ℹ️ ZeroGPU module not present in this runtime."
172
 
173
+ # ---------------------------------------------------------------------------
174
+ # UI Layout
175
+ # ---------------------------------------------------------------------------
176
  with gr.Blocks(theme=gr.themes.Soft(), title="FluxCloud 24/7 Telegram & System Hub") as demo:
177
  gr.Markdown("# ⚑ FluxCloud 24/7 Engine & Telegram Storage Hub")
178
  gr.Markdown(f"Permanent Host: `{SELF_URL}` | **24/7 Automated Keep-Alive Active**")
 
189
  refresh_btn.click(fn=get_system_stats, outputs=stats_display)
190
  gpu_test_btn.click(fn=test_gpu_quota, outputs=gpu_display)
191
 
192
+ with gr.TabItem("πŸ€– Telegram Cloud Storage & Streamer"):
193
+ gr.Markdown("### 1. Upload to Telegram Cloud Channel")
194
  with gr.Row():
195
  token_box = gr.Textbox(label="Telegram Bot Token", value=DEFAULT_BOT_TOKEN, placeholder="Enter Bot Token")
196
  channel_box = gr.Textbox(label="Channel ID / Chat ID", value=DEFAULT_CHANNEL_ID, placeholder="-100xxxxxxxxxx or @channel")
 
198
  test_file = gr.File(label="Choose File to Upload")
199
  upload_btn = gr.Button("πŸš€ Upload to Telegram Cloud", variant="primary")
200
  tg_output = gr.Markdown(label="Upload Result")
201
+ cached_fid = gr.Textbox(label="Generated File ID", interactive=False)
202
 
203
  upload_btn.click(
204
+ fn=telegram_upload_action,
205
  inputs=[test_file, token_box, channel_box],
206
+ outputs=[tg_output, cached_fid],
207
  )
208
 
209
+ gr.Markdown("---")
210
+ gr.Markdown("### 2. Stream / Download File on Demand from Telegram")
211
+ with gr.Row():
212
+ fid_input = gr.Textbox(label="Telegram File ID to Stream", placeholder="Paste File ID here")
213
+ stream_btn = gr.Button("▢️ Fetch & Stream from Telegram", variant="secondary")
214
+
215
+ stream_status = gr.Markdown()
216
+ streamed_file_output = gr.File(label="Streamed Media / File")
217
+
218
+ stream_btn.click(
219
+ fn=telegram_stream_fetch,
220
+ inputs=[fid_input, token_box],
221
+ outputs=[streamed_file_output, stream_status],
222
+ )
223
 
224
+ demo.launch()
 
requirements.txt CHANGED
@@ -1,6 +1,2 @@
1
  psutil
2
  requests
3
- fastapi
4
- python-multipart
5
- httpx
6
- uvicorn
 
1
  psutil
2
  requests