Cxops commited on
Commit
806ea3a
·
verified ·
1 Parent(s): 99badfc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -73
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import json
3
  import math
4
  import time
@@ -18,12 +19,7 @@ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
18
  from cryptography.hazmat.backends import default_backend
19
 
20
  from pyrogram import Client, filters
21
- from pyrogram.types import (
22
- Message,
23
- CallbackQuery,
24
- InlineKeyboardMarkup,
25
- InlineKeyboardButton,
26
- )
27
 
28
  from huggingface_hub import HfApi, hf_hub_download, upload_file
29
 
@@ -39,13 +35,16 @@ HF_REPO_TYPE = "dataset"
39
  HF_BRANCH = "main"
40
 
41
  MIN_FREE_DISK = 45 * 1024**3
42
- SPLIT_SIZE = 2 * 1024**3 - 10 * 1024 * 1024
 
 
43
 
44
  logging.basicConfig(level=logging.INFO)
45
- log = logging.getLogger(__name__)
46
 
47
  # ---------------- ENCRYPTION ----------------
48
  SALT = b"hf_bot_salt_2025"
 
49
  kdf = PBKDF2HMAC(
50
  algorithm=hashes.SHA256(),
51
  length=32,
@@ -53,6 +52,7 @@ kdf = PBKDF2HMAC(
53
  iterations=100000,
54
  backend=default_backend(),
55
  )
 
56
  key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
57
  fernet = Fernet(key)
58
 
@@ -60,19 +60,19 @@ def encrypt(x: str) -> str:
60
  return base64.urlsafe_b64encode(fernet.encrypt(x.encode())).decode().rstrip("=")
61
 
62
  def decrypt(x: str) -> str:
63
- pad = "=" * (-len(x) % 4)
64
- return fernet.decrypt(base64.urlsafe_b64decode(x + pad)).decode()
65
 
66
- def user_folder(uid: int) -> str:
67
  return encrypt(str(uid))
68
 
69
  # ---------------- HF ----------------
70
- hf_api = HfApi(token=HF_TOKEN)
71
 
72
- def hf_write_json(path: str, data: dict):
73
- with tempfile.NamedTemporaryFile("w", delete=False) as f:
 
74
  json.dump(data, f)
75
- tmp = f.name
76
 
77
  upload_file(
78
  path_or_fileobj=tmp,
@@ -83,7 +83,7 @@ def hf_write_json(path: str, data: dict):
83
  )
84
  os.remove(tmp)
85
 
86
- def hf_read_json(path: str) -> Optional[dict]:
87
  try:
88
  tmp = hf_hub_download(
89
  repo_id=HF_REPO_ID,
@@ -91,113 +91,141 @@ def hf_read_json(path: str) -> Optional[dict]:
91
  filename=path,
92
  revision=HF_BRANCH,
93
  )
94
- with open(tmp, "r") as f:
95
  return json.load(f)
96
  except Exception:
97
- return None
98
 
99
- def hf_file_size(path: str) -> Optional[int]:
100
  try:
101
- info = hf_api.get_paths_info(
102
- repo_id=HF_REPO_ID,
103
- repo_type=HF_REPO_TYPE,
104
- paths=[path],
105
- )
106
  return info[0].size
107
- except Exception:
108
  return None
109
 
110
- def hf_delete(path: str):
111
  try:
112
- hf_api.delete_file(
113
- path,
114
- repo_id=HF_REPO_ID,
115
- repo_type=HF_REPO_TYPE,
116
- commit_message="delete",
117
- )
118
  except Exception as e:
119
  log.error(e)
120
 
121
  # ---------------- BOT ----------------
122
  app = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
123
 
124
- active: Dict[int, dict] = {}
125
  queue = asyncio.Queue()
126
- pending = {}
 
 
 
 
 
 
 
127
 
128
- # ---------------- HELPERS ----------------
129
  def fmt(n):
130
  if not n:
131
  return "0 B"
132
- u = ["B","KB","MB","GB"]
133
- i = int(math.log(n,1024)) if n > 0 else 0
134
- return f"{n/1024**i:.1f} {u[i]}"
135
 
136
- def bar(p):
137
- return "█"*int(p/10) + "░"*(10-int(p/10))
 
 
 
 
 
 
 
 
138
 
139
- def free_ok(n=0):
140
- return (shutil.disk_usage("/").free - n) > MIN_FREE_DISK
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
  # ---------------- WORKER ----------------
143
  async def worker():
144
  while True:
145
- op = await queue.get()
146
  try:
147
- if op["type"] == "upload":
148
- await upload_job(op)
149
  else:
150
- await download_job(op)
151
  except Exception as e:
152
  log.exception(e)
153
  queue.task_done()
154
 
155
  # ---------------- UPLOAD ----------------
156
- async def upload_job(op):
157
- msg = op["msg"]
158
- file_id = op["file_id"]
159
- name = op["name"]
160
- uid = op["uid"]
161
- cancel = op["cancel"]
162
-
163
- active[msg] = {"chat": op["chat"], "file": name, "cur":0, "tot":0, "cancel": cancel}
 
 
 
 
 
 
 
164
 
165
  while not free_ok():
166
  await asyncio.sleep(5)
167
 
168
  tmp = tempfile.mktemp()
169
-
170
  await app.download_media(file_id, file_name=tmp)
171
 
172
  if cancel.is_set():
173
  return
174
 
175
  path = f"{user_folder(uid)}/{encrypt(name)}"
176
- upload_file(tmp, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE, path_in_repo=path, token=HF_TOKEN)
177
 
178
  os.remove(tmp)
179
- await app.send_message(op["chat"], f"✅ Uploaded {name}")
 
180
 
181
  # ---------------- DOWNLOAD ----------------
182
- async def download_job(op):
183
- chat = op["chat"]
184
- msg = op["msg"]
185
- path = op["path"]
186
- name = op["name"]
187
- size = op["size"]
188
- cancel = op["cancel"]
189
 
190
- url = hf_api.hf_hub_url(HF_REPO_ID, path, repo_type=HF_REPO_TYPE)
191
 
192
  tmp = tempfile.mktemp()
193
 
194
  async with aiohttp.ClientSession() as s:
195
  async with s.get(url) as r:
196
- with open(tmp,"wb") as f:
197
- async for c in r.content.iter_chunked(1024*64):
198
  if cancel.is_set():
199
  return
200
- f.write(c)
201
 
202
  await app.send_document(chat, tmp, caption=name)
203
  os.remove(tmp)
@@ -205,7 +233,7 @@ async def download_job(op):
205
  # ---------------- HANDLERS ----------------
206
  @app.on_message(filters.command("start"))
207
  async def start(_, m):
208
- await m.reply("Send files to upload.")
209
 
210
  @app.on_message(filters.media & filters.private)
211
  async def media(_, m):
@@ -225,9 +253,9 @@ async def media(_, m):
225
  [InlineKeyboardButton("Upload", callback_data=f"up|{m.id}")]
226
  ])
227
 
228
- msg = await m.reply(f"Upload {name}?", reply_markup=btn)
229
 
230
- pending[msg.id] = {
231
  "file_id": fid,
232
  "name": name,
233
  "uid": m.from_user.id,
@@ -237,14 +265,14 @@ async def media(_, m):
237
  @app.on_callback_query(filters.regex("^up\\|"))
238
  async def up(_, q):
239
  mid = int(q.data.split("|")[1])
240
- data = pending.pop(q.message.id, None)
241
  if not data:
242
  return await q.answer("Expired", show_alert=True)
243
 
244
  cancel = asyncio.Event()
245
 
246
  await queue.put({
247
- "type":"upload",
248
  "file_id": data["file_id"],
249
  "name": data["name"],
250
  "uid": data["uid"],
@@ -255,10 +283,39 @@ async def up(_, q):
255
 
256
  await q.message.edit("Uploading started...")
257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
  # ---------------- MAIN ----------------
259
  async def main():
260
  await app.start()
 
261
  asyncio.create_task(worker())
 
 
 
262
  await asyncio.Event().wait()
263
 
264
  if __name__ == "__main__":
 
1
  import os
2
+ import sys
3
  import json
4
  import math
5
  import time
 
19
  from cryptography.hazmat.backends import default_backend
20
 
21
  from pyrogram import Client, filters
22
+ from pyrogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
 
 
 
 
 
23
 
24
  from huggingface_hub import HfApi, hf_hub_download, upload_file
25
 
 
35
  HF_BRANCH = "main"
36
 
37
  MIN_FREE_DISK = 45 * 1024**3
38
+ SPLIT_SIZE = 2 * 1024**3 - 10 * 1024**2
39
+ KEEPALIVE_INTERVAL = 300
40
+ PROGRESS_INTERVAL = 2
41
 
42
  logging.basicConfig(level=logging.INFO)
43
+ log = logging.getLogger("bot")
44
 
45
  # ---------------- ENCRYPTION ----------------
46
  SALT = b"hf_bot_salt_2025"
47
+
48
  kdf = PBKDF2HMAC(
49
  algorithm=hashes.SHA256(),
50
  length=32,
 
52
  iterations=100000,
53
  backend=default_backend(),
54
  )
55
+
56
  key = base64.urlsafe_b64encode(kdf.derive(SECRET_KEY.encode()))
57
  fernet = Fernet(key)
58
 
 
60
  return base64.urlsafe_b64encode(fernet.encrypt(x.encode())).decode().rstrip("=")
61
 
62
  def decrypt(x: str) -> str:
63
+ x += "=" * (-len(x) % 4)
64
+ return fernet.decrypt(base64.urlsafe_b64decode(x)).decode()
65
 
66
+ def user_folder(uid: int):
67
  return encrypt(str(uid))
68
 
69
  # ---------------- HF ----------------
70
+ hf = HfApi(token=HF_TOKEN)
71
 
72
+ def hf_write_json(path, data):
73
+ tmp = tempfile.mktemp()
74
+ with open(tmp, "w") as f:
75
  json.dump(data, f)
 
76
 
77
  upload_file(
78
  path_or_fileobj=tmp,
 
83
  )
84
  os.remove(tmp)
85
 
86
+ def hf_read_json(path):
87
  try:
88
  tmp = hf_hub_download(
89
  repo_id=HF_REPO_ID,
 
91
  filename=path,
92
  revision=HF_BRANCH,
93
  )
94
+ with open(tmp) as f:
95
  return json.load(f)
96
  except Exception:
97
+ return {}
98
 
99
+ def hf_size(path):
100
  try:
101
+ info = hf.get_paths_info(HF_REPO_ID, repo_type=HF_REPO_TYPE, paths=[path])
 
 
 
 
102
  return info[0].size
103
+ except:
104
  return None
105
 
106
+ def hf_delete(path):
107
  try:
108
+ hf.delete_file(path, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE)
 
 
 
 
 
109
  except Exception as e:
110
  log.error(e)
111
 
112
  # ---------------- BOT ----------------
113
  app = Client("bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
114
 
115
+ active_progress: Dict[int, dict] = {}
116
  queue = asyncio.Queue()
117
+ pending_uploads = {}
118
+
119
+ # ---------------- UTILS ----------------
120
+ def free_ok(n=0):
121
+ return (shutil.disk_usage("/").free - n) > MIN_FREE_DISK
122
+
123
+ def bar(p):
124
+ return "█" * int(p / 10) + "░" * (10 - int(p / 10))
125
 
 
126
  def fmt(n):
127
  if not n:
128
  return "0 B"
129
+ u = ["B", "KB", "MB", "GB"]
130
+ i = int(math.log(n, 1024)) if n > 0 else 0
131
+ return f"{n / 1024**i:.1f} {u[i]}"
132
 
133
+ # ---------------- PROGRESS UPDATER ----------------
134
+ async def progress_loop():
135
+ while True:
136
+ await asyncio.sleep(PROGRESS_INTERVAL)
137
+ for msg_id, p in list(active_progress.items()):
138
+ try:
139
+ chat = p["chat"]
140
+ name = p["file"]
141
+ cur = p.get("cur", 0)
142
+ tot = p.get("tot", 0)
143
 
144
+ percent = (cur / tot * 100) if tot else 0
145
+
146
+ text = (
147
+ f"**{p['op']}** `{name}`\n"
148
+ f"{bar(percent)} {percent:.1f}%\n"
149
+ f"{fmt(cur)} / {fmt(tot)}"
150
+ )
151
+
152
+ kb = None
153
+ if p.get("cancel"):
154
+ kb = InlineKeyboardMarkup([
155
+ [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_{msg_id}")]
156
+ ])
157
+
158
+ await app.edit_message_text(chat, msg_id, text, reply_markup=kb)
159
+
160
+ except Exception:
161
+ pass
162
 
163
  # ---------------- WORKER ----------------
164
  async def worker():
165
  while True:
166
+ job = await queue.get()
167
  try:
168
+ if job["type"] == "upload":
169
+ await handle_upload(job)
170
  else:
171
+ await handle_download(job)
172
  except Exception as e:
173
  log.exception(e)
174
  queue.task_done()
175
 
176
  # ---------------- UPLOAD ----------------
177
+ async def handle_upload(job):
178
+ msg = job["msg"]
179
+ file_id = job["file_id"]
180
+ name = job["name"]
181
+ uid = job["uid"]
182
+ cancel = job["cancel"]
183
+
184
+ active_progress[msg] = {
185
+ "chat": job["chat"],
186
+ "file": name,
187
+ "cur": 0,
188
+ "tot": 0,
189
+ "op": "Upload",
190
+ "cancel": cancel
191
+ }
192
 
193
  while not free_ok():
194
  await asyncio.sleep(5)
195
 
196
  tmp = tempfile.mktemp()
 
197
  await app.download_media(file_id, file_name=tmp)
198
 
199
  if cancel.is_set():
200
  return
201
 
202
  path = f"{user_folder(uid)}/{encrypt(name)}"
203
+ upload_file(tmp, HF_REPO_ID, HF_REPO_TYPE, path, token=HF_TOKEN)
204
 
205
  os.remove(tmp)
206
+
207
+ await app.send_message(job["chat"], f"✅ Uploaded `{name}`")
208
 
209
  # ---------------- DOWNLOAD ----------------
210
+ async def handle_download(job):
211
+ chat = job["chat"]
212
+ msg = job["msg"]
213
+ path = job["path"]
214
+ name = job["name"]
215
+ size = job["size"]
216
+ cancel = job["cancel"]
217
 
218
+ url = hf.hf_hub_url(HF_REPO_ID, path, repo_type=HF_REPO_TYPE)
219
 
220
  tmp = tempfile.mktemp()
221
 
222
  async with aiohttp.ClientSession() as s:
223
  async with s.get(url) as r:
224
+ with open(tmp, "wb") as f:
225
+ async for chunk in r.content.iter_chunked(64 * 1024):
226
  if cancel.is_set():
227
  return
228
+ f.write(chunk)
229
 
230
  await app.send_document(chat, tmp, caption=name)
231
  os.remove(tmp)
 
233
  # ---------------- HANDLERS ----------------
234
  @app.on_message(filters.command("start"))
235
  async def start(_, m):
236
+ await m.reply("Send files to upload")
237
 
238
  @app.on_message(filters.media & filters.private)
239
  async def media(_, m):
 
253
  [InlineKeyboardButton("Upload", callback_data=f"up|{m.id}")]
254
  ])
255
 
256
+ msg = await m.reply(f"Upload `{name}`?", reply_markup=btn)
257
 
258
+ pending_uploads[msg.id] = {
259
  "file_id": fid,
260
  "name": name,
261
  "uid": m.from_user.id,
 
265
  @app.on_callback_query(filters.regex("^up\\|"))
266
  async def up(_, q):
267
  mid = int(q.data.split("|")[1])
268
+ data = pending_uploads.pop(q.message.id, None)
269
  if not data:
270
  return await q.answer("Expired", show_alert=True)
271
 
272
  cancel = asyncio.Event()
273
 
274
  await queue.put({
275
+ "type": "upload",
276
  "file_id": data["file_id"],
277
  "name": data["name"],
278
  "uid": data["uid"],
 
283
 
284
  await q.message.edit("Uploading started...")
285
 
286
+ @app.on_callback_query(filters.regex("^cancel_"))
287
+ async def cancel(_, q):
288
+ mid = int(q.data.split("_")[1])
289
+ if mid in active_progress:
290
+ active_progress[mid]["cancel"].set()
291
+ await q.answer("Cancelled")
292
+ else:
293
+ await q.answer("Nothing running")
294
+
295
+ # ---------------- KEEP ALIVE ----------------
296
+ async def keep_alive():
297
+ async def handler(_):
298
+ return web.Response(text="OK")
299
+
300
+ app_web = web.Application()
301
+ app_web.router.add_get("/", handler)
302
+
303
+ runner = web.AppRunner(app_web)
304
+ await runner.setup()
305
+ site = web.TCPSite(runner, "0.0.0.0", 7860)
306
+ await site.start()
307
+
308
+ while True:
309
+ await asyncio.sleep(KEEPALIVE_INTERVAL)
310
+
311
  # ---------------- MAIN ----------------
312
  async def main():
313
  await app.start()
314
+
315
  asyncio.create_task(worker())
316
+ asyncio.create_task(progress_loop())
317
+ asyncio.create_task(keep_alive())
318
+
319
  await asyncio.Event().wait()
320
 
321
  if __name__ == "__main__":