Update app.py
Browse files
app.py
CHANGED
|
@@ -1,22 +1,57 @@
|
|
| 1 |
import os
|
| 2 |
-
import time
|
| 3 |
import asyncio
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from huggingface_hub import HfApi
|
| 7 |
|
| 8 |
-
# =========================
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
app = Client(
|
| 19 |
-
"
|
| 20 |
api_id=API_ID,
|
| 21 |
api_hash=API_HASH,
|
| 22 |
bot_token=BOT_TOKEN
|
|
@@ -24,106 +59,167 @@ app = Client(
|
|
| 24 |
|
| 25 |
hf = HfApi(token=HF_TOKEN)
|
| 26 |
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
# =========================
|
| 31 |
-
def format_size(bytes_size):
|
| 32 |
-
for unit in ["B", "KB", "MB", "GB"]:
|
| 33 |
-
if bytes_size < 1024:
|
| 34 |
-
return f"{bytes_size:.2f}{unit}"
|
| 35 |
-
bytes_size /= 1024
|
| 36 |
-
return f"{bytes_size:.2f}TB"
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def calc_speed(start_time, current, total):
|
| 40 |
-
elapsed = time.time() - start_time
|
| 41 |
-
if elapsed == 0:
|
| 42 |
-
return "0 B/s"
|
| 43 |
-
speed = current / elapsed
|
| 44 |
-
return f"{format_size(speed)}/s"
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
# =========================
|
| 48 |
-
# UPLOAD FUNCTION
|
| 49 |
-
# =========================
|
| 50 |
-
def upload_to_hf(file_path, filename, status_msg):
|
| 51 |
-
start_time = time.time()
|
| 52 |
-
|
| 53 |
-
def progress(current, total):
|
| 54 |
-
percent = (current / total) * 100 if total else 0
|
| 55 |
-
speed = calc_speed(start_time, current, total)
|
| 56 |
-
|
| 57 |
-
asyncio.run_coroutine_threadsafe(
|
| 58 |
-
status_msg.edit_text(
|
| 59 |
-
f"βοΈ Uploading...\n"
|
| 60 |
-
f"π¦ {filename}\n"
|
| 61 |
-
f"π {percent:.2f}%\n"
|
| 62 |
-
f"π {speed}"
|
| 63 |
-
),
|
| 64 |
-
app.loop
|
| 65 |
-
)
|
| 66 |
-
|
| 67 |
-
hf.upload_file(
|
| 68 |
-
path_or_fileobj=file_path,
|
| 69 |
-
path_in_repo=f"uploads/{filename}",
|
| 70 |
-
repo_id=HF_REPO,
|
| 71 |
-
repo_type="dataset",
|
| 72 |
-
progress_callback=progress
|
| 73 |
-
)
|
| 74 |
-
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
# =========================
|
| 79 |
-
@app.on_message(filters.document | filters.video | filters.audio | filters.photo)
|
| 80 |
-
async def handle_file(client, message: Message):
|
| 81 |
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
|
|
|
| 86 |
|
| 87 |
-
|
| 88 |
-
file_path = await message.download(
|
| 89 |
-
progress=download_progress := lambda cur, total: None
|
| 90 |
-
)
|
| 91 |
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
|
| 95 |
-
await status.edit("β¬οΈ Preparing upload...")
|
| 96 |
|
|
|
|
| 97 |
loop = asyncio.get_event_loop()
|
| 98 |
-
|
| 99 |
await loop.run_in_executor(
|
| 100 |
None,
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
| 105 |
)
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
pass
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
-
# =========================
|
| 118 |
-
# START COMMAND
|
| 119 |
-
# =========================
|
| 120 |
@app.on_message(filters.command("start"))
|
| 121 |
-
async def start(_,
|
| 122 |
-
await
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
)
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import asyncio
|
| 3 |
+
import hashlib
|
| 4 |
+
import shutil
|
| 5 |
+
import logging
|
| 6 |
+
import aiohttp
|
| 7 |
+
|
| 8 |
+
from fastapi import FastAPI
|
| 9 |
+
import uvicorn
|
| 10 |
+
|
| 11 |
+
from pyrogram import Client, filters, idle
|
| 12 |
+
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
| 13 |
from huggingface_hub import HfApi
|
| 14 |
|
| 15 |
+
# ================= LOGGING =================
|
| 16 |
+
|
| 17 |
+
logging.basicConfig(level=logging.INFO)
|
| 18 |
+
log = logging.getLogger("bot")
|
| 19 |
+
|
| 20 |
+
# ================= CONFIG =================
|
| 21 |
+
|
| 22 |
+
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
| 23 |
+
API_ID = int(os.getenv("API_ID"))
|
| 24 |
+
API_HASH = os.getenv("API_HASH")
|
| 25 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 26 |
+
|
| 27 |
+
DATASET_REPO = "Cxops/Bzxv"
|
| 28 |
+
SPACE_URL = "https://cxops-push.hf.space"
|
| 29 |
+
|
| 30 |
+
BASE_DIR = "/data/files"
|
| 31 |
+
os.makedirs(BASE_DIR, exist_ok=True)
|
| 32 |
+
|
| 33 |
+
DISK_LIMIT_GB = 45
|
| 34 |
+
|
| 35 |
+
# ================= FASTAPI (PORT 7860) =================
|
| 36 |
+
|
| 37 |
+
web = FastAPI()
|
| 38 |
+
|
| 39 |
+
@web.get("/")
|
| 40 |
+
def home():
|
| 41 |
+
return {"status": "running", "service": "telegram-bot"}
|
| 42 |
|
| 43 |
+
@web.get("/health")
|
| 44 |
+
def health():
|
| 45 |
+
free = shutil.disk_usage("/data").free
|
| 46 |
+
return {
|
| 47 |
+
"ok": True,
|
| 48 |
+
"free_gb": round(free / (1024**3), 2)
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
# ================= PYROGRAM BOT =================
|
| 52 |
|
| 53 |
app = Client(
|
| 54 |
+
"hf_bot",
|
| 55 |
api_id=API_ID,
|
| 56 |
api_hash=API_HASH,
|
| 57 |
bot_token=BOT_TOKEN
|
|
|
|
| 59 |
|
| 60 |
hf = HfApi(token=HF_TOKEN)
|
| 61 |
|
| 62 |
+
# ================= UTIL =================
|
| 63 |
|
| 64 |
+
def hash_id(text: str):
|
| 65 |
+
return hashlib.sha256(text.encode()).hexdigest()[:16]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
def user_folder(uid, uname):
|
| 68 |
+
return hash_id(f"{uid}:{uname}")
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
def user_path(folder):
|
| 71 |
+
path = os.path.join(BASE_DIR, folder)
|
| 72 |
+
os.makedirs(path, exist_ok=True)
|
| 73 |
+
return path
|
| 74 |
|
| 75 |
+
def disk_ok():
|
| 76 |
+
free = shutil.disk_usage("/data").free
|
| 77 |
+
return free > (DISK_LIMIT_GB * 1024**3)
|
| 78 |
|
| 79 |
+
# ================= KEEPALIVE =================
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
+
async def keepalive():
|
| 82 |
+
while True:
|
| 83 |
+
try:
|
| 84 |
+
async with aiohttp.ClientSession() as s:
|
| 85 |
+
await s.get(SPACE_URL)
|
| 86 |
+
except Exception as e:
|
| 87 |
+
log.warning(f"keepalive error: {e}")
|
| 88 |
+
await asyncio.sleep(300)
|
| 89 |
|
| 90 |
+
# ================= HF UPLOAD =================
|
|
|
|
| 91 |
|
| 92 |
+
async def upload_to_hf(local_file, remote_path):
|
| 93 |
loop = asyncio.get_event_loop()
|
|
|
|
| 94 |
await loop.run_in_executor(
|
| 95 |
None,
|
| 96 |
+
lambda: hf.upload_file(
|
| 97 |
+
path_or_fileobj=local_file,
|
| 98 |
+
path_in_repo=remote_path,
|
| 99 |
+
repo_id=DATASET_REPO,
|
| 100 |
+
repo_type="dataset"
|
| 101 |
+
)
|
| 102 |
)
|
| 103 |
|
| 104 |
+
# ================= QUEUE =================
|
| 105 |
+
|
| 106 |
+
queue = asyncio.Queue()
|
| 107 |
|
| 108 |
+
async def worker():
|
| 109 |
+
while True:
|
| 110 |
+
job = await queue.get()
|
|
|
|
| 111 |
|
| 112 |
+
msg = job["msg"]
|
| 113 |
+
file_id = job["file_id"]
|
| 114 |
+
folder = job["folder"]
|
| 115 |
+
fake = job["fake"]
|
| 116 |
+
|
| 117 |
+
if not disk_ok():
|
| 118 |
+
await msg.reply("β Disk full. Try later.")
|
| 119 |
+
continue
|
| 120 |
+
|
| 121 |
+
status = await msg.reply("β¬ Downloading...")
|
| 122 |
+
|
| 123 |
+
local_file = os.path.join(user_path(folder), fake)
|
| 124 |
+
|
| 125 |
+
path = await app.download_media(file_id, file_name=local_file)
|
| 126 |
+
|
| 127 |
+
await status.edit("β Uploading to HuggingFace...")
|
| 128 |
+
|
| 129 |
+
remote_path = f"{folder}/{fake}"
|
| 130 |
+
await upload_to_hf(path, remote_path)
|
| 131 |
+
|
| 132 |
+
try:
|
| 133 |
+
os.remove(path)
|
| 134 |
+
except:
|
| 135 |
+
pass
|
| 136 |
+
|
| 137 |
+
await status.edit("β
Done")
|
| 138 |
+
|
| 139 |
+
# ================= HANDLERS =================
|
| 140 |
+
|
| 141 |
+
pending = {}
|
| 142 |
|
|
|
|
|
|
|
|
|
|
| 143 |
@app.on_message(filters.command("start"))
|
| 144 |
+
async def start(_, msg):
|
| 145 |
+
await msg.reply("π Bot is live. Send files to store them.")
|
| 146 |
+
|
| 147 |
+
@app.on_message(filters.document | filters.video | filters.audio)
|
| 148 |
+
async def receive(_, msg):
|
| 149 |
+
user = msg.from_user
|
| 150 |
+
if not user:
|
| 151 |
+
return
|
| 152 |
+
|
| 153 |
+
folder = user_folder(user.id, user.username or str(user.id))
|
| 154 |
+
|
| 155 |
+
file_id = (
|
| 156 |
+
msg.document.file_id if msg.document else
|
| 157 |
+
msg.video.file_id if msg.video else
|
| 158 |
+
msg.audio.file_id
|
| 159 |
)
|
| 160 |
|
| 161 |
+
fake = hash_id(file_id)
|
| 162 |
+
|
| 163 |
+
pending[user.id] = {
|
| 164 |
+
"file_id": file_id,
|
| 165 |
+
"folder": folder,
|
| 166 |
+
"fake": fake,
|
| 167 |
+
"msg": msg
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
kb = InlineKeyboardMarkup([
|
| 171 |
+
[
|
| 172 |
+
InlineKeyboardButton("β¬ Upload", callback_data="up"),
|
| 173 |
+
InlineKeyboardButton("β Cancel", callback_data="no")
|
| 174 |
+
]
|
| 175 |
+
])
|
| 176 |
+
|
| 177 |
+
await msg.reply("File received. Upload?", reply_markup=kb)
|
| 178 |
+
|
| 179 |
+
@app.on_callback_query()
|
| 180 |
+
async def cb(_, q):
|
| 181 |
+
uid = q.from_user.id
|
| 182 |
+
|
| 183 |
+
if q.data == "no":
|
| 184 |
+
pending.pop(uid, None)
|
| 185 |
+
return await q.message.edit("Cancelled")
|
| 186 |
+
|
| 187 |
+
if q.data == "up":
|
| 188 |
+
if uid in pending:
|
| 189 |
+
await queue.put(pending[uid])
|
| 190 |
+
pending.pop(uid)
|
| 191 |
+
await q.message.edit("Queued β")
|
| 192 |
+
|
| 193 |
+
# ================= STARTUP =================
|
| 194 |
+
|
| 195 |
+
async def run_web():
|
| 196 |
+
config = uvicorn.Config(
|
| 197 |
+
web,
|
| 198 |
+
host="0.0.0.0",
|
| 199 |
+
port=7860,
|
| 200 |
+
log_level="info"
|
| 201 |
+
)
|
| 202 |
+
server = uvicorn.Server(config)
|
| 203 |
+
await server.serve()
|
| 204 |
+
|
| 205 |
+
async def start_bot():
|
| 206 |
+
log.info("Starting bot...")
|
| 207 |
+
|
| 208 |
+
await app.start()
|
| 209 |
+
|
| 210 |
+
me = await app.get_me()
|
| 211 |
+
log.info(f"Bot running as @{me.username}")
|
| 212 |
+
|
| 213 |
+
asyncio.create_task(worker())
|
| 214 |
+
asyncio.create_task(keepalive())
|
| 215 |
+
|
| 216 |
+
await idle()
|
| 217 |
+
|
| 218 |
+
async def main():
|
| 219 |
+
await asyncio.gather(
|
| 220 |
+
start_bot(),
|
| 221 |
+
run_web()
|
| 222 |
+
)
|
| 223 |
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
asyncio.run(main())
|