Update app.py
Browse files
app.py
CHANGED
|
@@ -1,20 +1,32 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import asyncio
|
| 3 |
-
import
|
| 4 |
from pathlib import Path
|
| 5 |
-
from fastapi import FastAPI
|
| 6 |
from fastapi.responses import RedirectResponse
|
| 7 |
from huggingface_hub import HfApi
|
| 8 |
from telethon import TelegramClient, events
|
| 9 |
-
from telethon.
|
| 10 |
-
|
| 11 |
-
# ---
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# Initialize Hugging Face API
|
| 20 |
hf_api = HfApi(token=HF_TOKEN)
|
|
@@ -22,71 +34,104 @@ hf_api = HfApi(token=HF_TOKEN)
|
|
| 22 |
# Initialize FastAPI
|
| 23 |
app = FastAPI(title="My Cloud Bot")
|
| 24 |
|
| 25 |
-
# Initialize Telethon Client (
|
| 26 |
-
client = TelegramClient(
|
| 27 |
|
| 28 |
-
# Helper: Get public CDN URL
|
| 29 |
def get_cdn_url(filename):
|
| 30 |
return f"https://huggingface.co/datasets/{HF_REPO}/resolve/main/{filename}"
|
| 31 |
|
| 32 |
-
# --- Telegram Bot
|
| 33 |
|
| 34 |
@client.on(events.NewMessage(pattern='/start'))
|
| 35 |
async def start_handler(event):
|
| 36 |
-
await event.reply(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
@client.on(events.NewMessage)
|
| 39 |
async def handle_file(event):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
if not event.message.file:
|
| 41 |
return
|
| 42 |
|
| 43 |
-
message = await event.reply("π₯ Downloading
|
|
|
|
| 44 |
|
| 45 |
try:
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
if not file_path:
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
filename = Path(file_path).name
|
| 54 |
|
| 55 |
-
# Update
|
| 56 |
-
await message.edit(f"π€ Uploading {
|
| 57 |
-
|
| 58 |
-
#
|
| 59 |
hf_api.upload_file(
|
| 60 |
path_or_fileobj=file_path,
|
| 61 |
-
path_in_repo=
|
| 62 |
repo_id=HF_REPO,
|
| 63 |
repo_type="dataset",
|
| 64 |
-
commit_message=f"Upload via Telegram: {
|
| 65 |
)
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
# 4. Reply with Link
|
| 71 |
response_text = (
|
| 72 |
-
f"β
*
|
| 73 |
-
f"π *
|
| 74 |
-
f"π¦ *
|
| 75 |
-
f"π *
|
| 76 |
-
f"
|
| 77 |
)
|
| 78 |
|
| 79 |
await message.edit(response_text, parse_mode='markdown')
|
| 80 |
-
|
| 81 |
-
|
|
|
|
| 82 |
os.remove(file_path)
|
|
|
|
| 83 |
|
| 84 |
except Exception as e:
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
os.remove(file_path)
|
| 88 |
|
| 89 |
-
# --- FastAPI Endpoints
|
| 90 |
|
| 91 |
@app.get("/")
|
| 92 |
def home():
|
|
@@ -98,17 +143,21 @@ def health():
|
|
| 98 |
|
| 99 |
@app.get("/cdn/{filename:path}")
|
| 100 |
def cdn_redirect(filename: str):
|
| 101 |
-
|
| 102 |
-
return RedirectResponse(url)
|
| 103 |
|
| 104 |
-
# --- Startup
|
| 105 |
|
| 106 |
@app.on_event("startup")
|
| 107 |
async def startup_event():
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
@app.on_event("shutdown")
|
| 113 |
async def shutdown_event():
|
|
|
|
| 114 |
await client.disconnect()
|
|
|
|
| 1 |
import os
|
| 2 |
+
import sys
|
| 3 |
import asyncio
|
| 4 |
+
import logging
|
| 5 |
from pathlib import Path
|
| 6 |
+
from fastapi import FastAPI
|
| 7 |
from fastapi.responses import RedirectResponse
|
| 8 |
from huggingface_hub import HfApi
|
| 9 |
from telethon import TelegramClient, events
|
| 10 |
+
from telethon.sessions import MemorySession
|
| 11 |
+
|
| 12 |
+
# --- Logging Setup for HF Space ---
|
| 13 |
+
logging.basicConfig(
|
| 14 |
+
level=logging.INFO,
|
| 15 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 16 |
+
handlers=[logging.StreamHandler(sys.stdout)]
|
| 17 |
+
)
|
| 18 |
+
logger = logging.getLogger("MyCloudBot")
|
| 19 |
+
|
| 20 |
+
# --- Configuration ---
|
| 21 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 22 |
+
HF_REPO = os.environ.get("HF_REPO")
|
| 23 |
+
API_ID = int(os.environ.get("TG_API_ID", 0))
|
| 24 |
+
API_HASH = os.environ.get("TG_API_HASH", "")
|
| 25 |
+
BOT_TOKEN = os.environ.get("TG_BOT_TOKEN", "")
|
| 26 |
+
|
| 27 |
+
if not all([HF_TOKEN, HF_REPO, API_ID, API_HASH, BOT_TOKEN]):
|
| 28 |
+
logger.error(" Missing environment variables! Check HF Space Secrets.")
|
| 29 |
+
raise ValueError("Missing required secrets")
|
| 30 |
|
| 31 |
# Initialize Hugging Face API
|
| 32 |
hf_api = HfApi(token=HF_TOKEN)
|
|
|
|
| 34 |
# Initialize FastAPI
|
| 35 |
app = FastAPI(title="My Cloud Bot")
|
| 36 |
|
| 37 |
+
# Initialize Telethon Client with MemorySession (No file persistence needed)
|
| 38 |
+
client = TelegramClient(MemorySession(), API_ID, API_HASH)
|
| 39 |
|
|
|
|
| 40 |
def get_cdn_url(filename):
|
| 41 |
return f"https://huggingface.co/datasets/{HF_REPO}/resolve/main/{filename}"
|
| 42 |
|
| 43 |
+
# --- Telegram Bot Handlers ---
|
| 44 |
|
| 45 |
@client.on(events.NewMessage(pattern='/start'))
|
| 46 |
async def start_handler(event):
|
| 47 |
+
await event.reply(
|
| 48 |
+
"π *Welcome to My Cloud Bot!*\n\n"
|
| 49 |
+
"Send me any file and I will upload it to Hugging Face.\n"
|
| 50 |
+
"You'll get a permanent CDN link instantly.",
|
| 51 |
+
parse_mode='markdown'
|
| 52 |
+
)
|
| 53 |
|
| 54 |
@client.on(events.NewMessage)
|
| 55 |
async def handle_file(event):
|
| 56 |
+
# Ignore commands
|
| 57 |
+
if event.message.text and event.message.text.startswith('/'):
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
if not event.message.file:
|
| 61 |
return
|
| 62 |
|
| 63 |
+
message = await event.reply("π₯ *Downloading from Telegram...*", parse_mode='markdown')
|
| 64 |
+
file_name = event.message.file.name or "unknown_file"
|
| 65 |
|
| 66 |
try:
|
| 67 |
+
logger.info(f"π₯ Starting download: {file_name}")
|
| 68 |
+
|
| 69 |
+
# Download with progress
|
| 70 |
+
def progress(current, total):
|
| 71 |
+
percent = (current / total) * 100
|
| 72 |
+
if int(percent) % 20 == 0: # Log every 20%
|
| 73 |
+
logger.info(f" Download progress: {percent:.1f}%")
|
| 74 |
+
|
| 75 |
+
file_path = await client.download_media(
|
| 76 |
+
event.message.file,
|
| 77 |
+
progress_callback=progress
|
| 78 |
+
)
|
| 79 |
|
| 80 |
if not file_path:
|
| 81 |
+
raise Exception("download_media returned None - File might be too large or restricted")
|
| 82 |
+
|
| 83 |
+
logger.info(f"β
Download complete: {file_path}")
|
|
|
|
| 84 |
|
| 85 |
+
# Update status
|
| 86 |
+
await message.edit(f"π€ *Uploading {file_name} to Cloud...*", parse_mode='markdown')
|
| 87 |
+
|
| 88 |
+
# Upload to HF Dataset
|
| 89 |
hf_api.upload_file(
|
| 90 |
path_or_fileobj=file_path,
|
| 91 |
+
path_in_repo=file_name,
|
| 92 |
repo_id=HF_REPO,
|
| 93 |
repo_type="dataset",
|
| 94 |
+
commit_message=f"Upload via Telegram: {file_name}"
|
| 95 |
)
|
| 96 |
+
|
| 97 |
+
cdn_link = get_cdn_url(file_name)
|
| 98 |
+
file_size_mb = os.path.getsize(file_path) / (1024*1024)
|
| 99 |
+
|
|
|
|
| 100 |
response_text = (
|
| 101 |
+
f"β
*Upload Complete!*\n\n"
|
| 102 |
+
f"π *File:* `{file_name}`\n"
|
| 103 |
+
f"π¦ *Size:* {file_size_mb:.2f} MB\n\n"
|
| 104 |
+
f"π *CDN Link:*\n{cdn_link}\n\n"
|
| 105 |
+
f"_Link is public and permanent._"
|
| 106 |
)
|
| 107 |
|
| 108 |
await message.edit(response_text, parse_mode='markdown')
|
| 109 |
+
logger.info(f"π Link generated: {cdn_link}")
|
| 110 |
+
|
| 111 |
+
# Cleanup
|
| 112 |
os.remove(file_path)
|
| 113 |
+
logger.info(f"π§Ή Cleaned up local file: {file_name}")
|
| 114 |
|
| 115 |
except Exception as e:
|
| 116 |
+
error_type = type(e).__name__
|
| 117 |
+
error_msg = str(e)[:400]
|
| 118 |
+
|
| 119 |
+
logger.error(f"β FAILED [{error_type}]: {error_msg}")
|
| 120 |
+
|
| 121 |
+
safe_error = error_msg.replace("`", "'")
|
| 122 |
+
await message.edit(
|
| 123 |
+
f"β *Operation Failed*\n\n"
|
| 124 |
+
f"*Type:* `{error_type}`\n"
|
| 125 |
+
f"*Details:* `{safe_error}`\n\n"
|
| 126 |
+
f"_Check HF Space Logs for more info._",
|
| 127 |
+
parse_mode='markdown'
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# Cleanup on error
|
| 131 |
+
if 'file_path' in locals() and file_path and os.path.exists(file_path):
|
| 132 |
os.remove(file_path)
|
| 133 |
|
| 134 |
+
# --- FastAPI Endpoints ---
|
| 135 |
|
| 136 |
@app.get("/")
|
| 137 |
def home():
|
|
|
|
| 143 |
|
| 144 |
@app.get("/cdn/{filename:path}")
|
| 145 |
def cdn_redirect(filename: str):
|
| 146 |
+
return RedirectResponse(get_cdn_url(filename))
|
|
|
|
| 147 |
|
| 148 |
+
# --- Startup & Shutdown ---
|
| 149 |
|
| 150 |
@app.on_event("startup")
|
| 151 |
async def startup_event():
|
| 152 |
+
logger.info(" Starting My Cloud Bot...")
|
| 153 |
+
try:
|
| 154 |
+
await client.start(bot_token=BOT_TOKEN)
|
| 155 |
+
logger.info("β
Telegram Bot connected successfully!")
|
| 156 |
+
except Exception as e:
|
| 157 |
+
logger.error(f"β Failed to start Telegram client: {e}")
|
| 158 |
+
raise
|
| 159 |
|
| 160 |
@app.on_event("shutdown")
|
| 161 |
async def shutdown_event():
|
| 162 |
+
logger.info("π Shutting down bot...")
|
| 163 |
await client.disconnect()
|