Prajwal commited on
Commit
c3e9e82
ยท
1 Parent(s): 0da7c20

Launch Gradio with embedded FastAPI Telegram endpoints

Browse files
Files changed (1) hide show
  1. app.py +127 -130
app.py CHANGED
@@ -5,8 +5,8 @@ import time
5
  import threading
6
  import requests
7
  import httpx
8
- from fastapi import FastAPI, UploadFile, File, Form, Request, HTTPException
9
- from fastapi.responses import StreamingResponse, JSONResponse, RedirectResponse
10
  from fastapi.middleware.cors import CORSMiddleware
11
  import gradio as gr
12
  import psutil
@@ -30,13 +30,13 @@ SELF_URL = os.environ.get("SPACE_HOST", "https://prajwalg4230-fluxcloud.hf.space
30
  # ---------------------------------------------------------------------------
31
  heartbeat_state = {
32
  "total_pings": 0,
33
- "last_ping_time": "Initializing...",
34
- "last_ping_status": "Starting",
35
  "started_at": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
36
  }
37
 
38
  def self_keep_alive_daemon():
39
- time.sleep(15) # initial wait before first ping
40
  while True:
41
  try:
42
  target = f"{SELF_URL}/heartbeat"
@@ -46,16 +46,133 @@ def self_keep_alive_daemon():
46
  heartbeat_state["last_ping_status"] = f"HTTP {r.status_code} OK"
47
  except Exception as e:
48
  heartbeat_state["last_ping_time"] = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
49
- heartbeat_state["last_ping_status"] = f"Warning: {str(e)[:40]}"
50
- time.sleep(600) # Ping every 10 minutes (Hugging Face idle timeout is 48 hours)
51
 
52
  heartbeat_thread = threading.Thread(target=self_keep_alive_daemon, daemon=True)
53
  heartbeat_thread.start()
54
 
55
  # ---------------------------------------------------------------------------
56
- # FastAPI REST Engine
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  # ---------------------------------------------------------------------------
58
- api = FastAPI(title="FluxCloud Telegram & 24/7 Engine")
59
 
60
  api.add_middleware(
61
  CORSMiddleware,
@@ -134,7 +251,6 @@ async def stream_file(file_id: str, token: str = None, request: Request = None):
134
  if not use_token:
135
  raise HTTPException(status_code=400, detail="Bot token is required")
136
 
137
- # Step 1: get file_path from Telegram getFile
138
  async with httpx.AsyncClient(timeout=20) as client:
139
  info_resp = await client.get(f"https://api.telegram.org/bot{use_token}/getFile?file_id={file_id}")
140
 
@@ -148,7 +264,6 @@ async def stream_file(file_id: str, token: str = None, request: Request = None):
148
  file_path = info_json["result"]["file_path"]
149
  download_upstream_url = f"https://api.telegram.org/file/bot{use_token}/{file_path}"
150
 
151
- # Stream chunks directly with range header support
152
  client = httpx.AsyncClient(timeout=300)
153
  req_headers = {}
154
  if request and "range" in request.headers:
@@ -183,122 +298,4 @@ async def download_file(file_id: str, token: str = None, request: Request = None
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()
191
- total_ram = round(mem.total / (1024 ** 3), 2)
192
- free_ram = round(mem.available / (1024 ** 3), 2)
193
- ram_pct = mem.percent
194
-
195
- disk = shutil.disk_usage("/")
196
- total_disk = round(disk.total / (1024 ** 3), 2)
197
- free_disk = round(disk.free / (1024 ** 3), 2)
198
- cpu_count = os.cpu_count()
199
- cpu_pct = psutil.cpu_percent(interval=0.3)
200
-
201
- return f"""
202
- ### ๐Ÿ“Š Hugging Face Space Live Status:
203
-
204
- | Resource | Allocated / Total | Free / Available | Usage % |
205
- | :--- | :--- | :--- | :--- |
206
- | ๐Ÿง  **RAM (Memory)** | **`{total_ram} GB`** | **`{free_ram} GB`** | `{ram_pct}%` |
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)
224
-
225
- try:
226
- with open(file_path, "rb") as fp:
227
- resp = requests.post(
228
- f"https://api.telegram.org/bot{token}/sendDocument",
229
- data={"chat_id": chat},
230
- files={"document": (file_name, fp)},
231
- timeout=120
232
- )
233
-
234
- if resp.status_code == 200 and resp.json().get("ok"):
235
- res = resp.json()["result"]
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():
260
- start = time.time()
261
- if torch.cuda.is_available():
262
- dev_name = torch.cuda.get_device_name(0)
263
- vram = round(torch.cuda.get_device_properties(0).total_memory / (1024 ** 3), 2)
264
- lat = round(time.time() - start, 3)
265
- return f"โœ… **ZeroGPU Active!** `{dev_name}` ({vram} GB VRAM) allocated in `{lat}s`."
266
- return "โš ๏ธ CUDA unavailable"
267
- 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 Endpoint: `{SELF_URL}` | **24/7 Automated Keep-Alive Active**")
274
-
275
- with gr.Tabs():
276
- with gr.TabItem("๐Ÿ“Š System Status & 24/7 Monitor"):
277
- with gr.Row():
278
- refresh_btn = gr.Button("๐Ÿ”„ Refresh Stats", variant="primary")
279
- gpu_test_btn = gr.Button("๐ŸŽฎ Probe ZeroGPU Quota", variant="secondary")
280
-
281
- stats_display = gr.Markdown(value=get_system_stats)
282
- gpu_display = gr.Markdown(value="*Click 'Probe ZeroGPU Quota' to test dynamic GPU allocation.*")
283
-
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")
292
-
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 into FastAPI
304
- app = gr.mount_gradio_app(api, demo, path="/")
 
5
  import threading
6
  import requests
7
  import httpx
8
+ from fastapi import UploadFile, File, Form, Request, HTTPException
9
+ from fastapi.responses import StreamingResponse, JSONResponse
10
  from fastapi.middleware.cors import CORSMiddleware
11
  import gradio as gr
12
  import psutil
 
30
  # ---------------------------------------------------------------------------
31
  heartbeat_state = {
32
  "total_pings": 0,
33
+ "last_ping_time": "Starting up...",
34
+ "last_ping_status": "Active",
35
  "started_at": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
36
  }
37
 
38
  def self_keep_alive_daemon():
39
+ time.sleep(20) # wait for server to bind port
40
  while True:
41
  try:
42
  target = f"{SELF_URL}/heartbeat"
 
46
  heartbeat_state["last_ping_status"] = f"HTTP {r.status_code} OK"
47
  except Exception as e:
48
  heartbeat_state["last_ping_time"] = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
49
+ heartbeat_state["last_ping_status"] = f"Ping note: {str(e)[:35]}"
50
+ time.sleep(600) # Ping every 10 minutes
51
 
52
  heartbeat_thread = threading.Thread(target=self_keep_alive_daemon, daemon=True)
53
  heartbeat_thread.start()
54
 
55
  # ---------------------------------------------------------------------------
56
+ # Gradio Dashboard & System Inspector
57
+ # ---------------------------------------------------------------------------
58
+ def get_system_stats():
59
+ mem = psutil.virtual_memory()
60
+ total_ram = round(mem.total / (1024 ** 3), 2)
61
+ free_ram = round(mem.available / (1024 ** 3), 2)
62
+ ram_pct = mem.percent
63
+
64
+ disk = shutil.disk_usage("/")
65
+ total_disk = round(disk.total / (1024 ** 3), 2)
66
+ free_disk = round(disk.free / (1024 ** 3), 2)
67
+ cpu_count = os.cpu_count()
68
+ cpu_pct = psutil.cpu_percent(interval=0.3)
69
+
70
+ return f"""
71
+ ### ๐Ÿ“Š Hugging Face Space Live Status:
72
+
73
+ | Resource | Allocated / Total | Free / Available | Usage % |
74
+ | :--- | :--- | :--- | :--- |
75
+ | ๐Ÿง  **RAM (Memory)** | **`{total_ram} GB`** | **`{free_ram} GB`** | `{ram_pct}%` |
76
+ | ๐Ÿ’พ **Disk Storage** | **`{total_disk} GB`** | **`{free_disk} GB`** | `{round((1 - free_disk/total_disk)*100, 1)}%` |
77
+ | โš™๏ธ **CPU Cores** | **`{cpu_count} vCPUs`** | Active | `{cpu_pct}%` |
78
+ | ๐Ÿ”„ **24/7 Keep-Alive** | `{heartbeat_state['total_pings']} Pings` | Status: `{heartbeat_state['last_ping_status']}` | Last: `{heartbeat_state['last_ping_time']}` |
79
+ """
80
+
81
+ def direct_tg_upload_gradio(file_obj, bot_token_input, channel_id_input):
82
+ if not file_obj:
83
+ return "โš ๏ธ Please select a file first."
84
+
85
+ token = bot_token_input.strip() if bot_token_input else DEFAULT_BOT_TOKEN
86
+ chat = channel_id_input.strip() if channel_id_input else DEFAULT_CHANNEL_ID
87
+
88
+ if not token or not chat:
89
+ return "โŒ Error: Both Telegram Bot Token and Channel ID are required."
90
+
91
+ file_path = file_obj.name if hasattr(file_obj, 'name') else str(file_obj)
92
+ file_name = os.path.basename(file_path)
93
+
94
+ try:
95
+ with open(file_path, "rb") as fp:
96
+ resp = requests.post(
97
+ f"https://api.telegram.org/bot{token}/sendDocument",
98
+ data={"chat_id": chat},
99
+ files={"document": (file_name, fp)},
100
+ timeout=120
101
+ )
102
+
103
+ if resp.status_code == 200 and resp.json().get("ok"):
104
+ res = resp.json()["result"]
105
+ doc = res.get("document") or res.get("video") or res.get("audio")
106
+ fid = doc["file_id"] if doc else str(res["message_id"])
107
+
108
+ stream_url = f"{SELF_URL}/stream/{fid}?token={token}"
109
+ download_url = f"{SELF_URL}/download/{fid}?token={token}"
110
+
111
+ return f"""
112
+ โœ… **Upload to Telegram SUCCESSFUL!**
113
+
114
+ - ๐Ÿ“ **File Name:** `{file_name}`
115
+ - ๐Ÿ†” **Telegram File ID:** `{fid}`
116
+ - ๐Ÿ’ฌ **Message ID:** `{res['message_id']}`
117
+ - ๐Ÿš€ **Direct Stream Link:** [Open Stream]({stream_url})
118
+ - โฌ‡๏ธ **Direct Download Link:** [Download File]({download_url})
119
+ """
120
+ else:
121
+ return f"โŒ Upload Failed: {resp.text}"
122
+ except Exception as e:
123
+ return f"โŒ Error: {str(e)}"
124
+
125
+ # ZeroGPU burst probe
126
+ if HAS_SPACES:
127
+ @spaces.GPU(duration=5)
128
+ def test_gpu_quota():
129
+ start = time.time()
130
+ if torch.cuda.is_available():
131
+ dev_name = torch.cuda.get_device_name(0)
132
+ vram = round(torch.cuda.get_device_properties(0).total_memory / (1024 ** 3), 2)
133
+ lat = round(time.time() - start, 3)
134
+ return f"โœ… **ZeroGPU Active!** `{dev_name}` ({vram} GB VRAM) allocated in `{lat}s`."
135
+ return "โš ๏ธ CUDA unavailable"
136
+ else:
137
+ def test_gpu_quota():
138
+ return "โ„น๏ธ ZeroGPU module not present in this runtime."
139
+
140
+ with gr.Blocks(theme=gr.themes.Soft(), title="FluxCloud 24/7 Telegram & System Hub") as demo:
141
+ gr.Markdown("# โšก FluxCloud 24/7 Engine & Telegram Storage Hub")
142
+ gr.Markdown(f"Permanent Host: `{SELF_URL}` | **24/7 Automated Keep-Alive Active**")
143
+
144
+ with gr.Tabs():
145
+ with gr.TabItem("๐Ÿ“Š System Status & 24/7 Monitor"):
146
+ with gr.Row():
147
+ refresh_btn = gr.Button("๐Ÿ”„ Refresh Stats", variant="primary")
148
+ gpu_test_btn = gr.Button("๐ŸŽฎ Probe ZeroGPU Quota", variant="secondary")
149
+
150
+ stats_display = gr.Markdown(value=get_system_stats)
151
+ gpu_display = gr.Markdown(value="*Click 'Probe ZeroGPU Quota' to test dynamic GPU allocation.*")
152
+
153
+ refresh_btn.click(fn=get_system_stats, outputs=stats_display)
154
+ gpu_test_btn.click(fn=test_gpu_quota, outputs=gpu_display)
155
+
156
+ with gr.TabItem("๐Ÿค– Telegram Cloud Storage Tester"):
157
+ gr.Markdown("Upload any file to test direct storage into your Telegram Channel with instant streaming links.")
158
+ with gr.Row():
159
+ token_box = gr.Textbox(label="Telegram Bot Token", value=DEFAULT_BOT_TOKEN, placeholder="Enter Bot Token")
160
+ channel_box = gr.Textbox(label="Channel ID / Chat ID", value=DEFAULT_CHANNEL_ID, placeholder="-100xxxxxxxxxx or @channel")
161
+
162
+ test_file = gr.File(label="Choose File to Upload")
163
+ upload_btn = gr.Button("๐Ÿš€ Upload to Telegram Cloud", variant="primary")
164
+ tg_output = gr.Markdown(label="Upload Result")
165
+
166
+ upload_btn.click(
167
+ fn=direct_tg_upload_gradio,
168
+ inputs=[test_file, token_box, channel_box],
169
+ outputs=tg_output,
170
+ )
171
+
172
+ # ---------------------------------------------------------------------------
173
+ # FastAPI REST Endpoints attached to demo.app
174
  # ---------------------------------------------------------------------------
175
+ api = demo.app
176
 
177
  api.add_middleware(
178
  CORSMiddleware,
 
251
  if not use_token:
252
  raise HTTPException(status_code=400, detail="Bot token is required")
253
 
 
254
  async with httpx.AsyncClient(timeout=20) as client:
255
  info_resp = await client.get(f"https://api.telegram.org/bot{use_token}/getFile?file_id={file_id}")
256
 
 
264
  file_path = info_json["result"]["file_path"]
265
  download_upstream_url = f"https://api.telegram.org/file/bot{use_token}/{file_path}"
266
 
 
267
  client = httpx.AsyncClient(timeout=300)
268
  req_headers = {}
269
  if request and "range" in request.headers:
 
298
  resp.headers["Content-Disposition"] = f'attachment; filename="{file_id}"'
299
  return resp
300
 
301
+ demo.launch()