000x commited on
Commit
e2edfd5
Β·
verified Β·
1 Parent(s): 5515645

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -50
app.py CHANGED
@@ -1,20 +1,32 @@
1
  import os
 
2
  import asyncio
3
- import tempfile
4
  from pathlib import Path
5
- from fastapi import FastAPI, HTTPException
6
  from fastapi.responses import RedirectResponse
7
  from huggingface_hub import HfApi
8
  from telethon import TelegramClient, events
9
- from telethon.tl.types import DocumentAttributeVideo, DocumentAttributeAudio
10
-
11
- # --- Configuration from Environment Variables ---
12
- HF_TOKEN = os.environ["HF_TOKEN"]
13
- HF_REPO = os.environ["HF_REPO"] # Example: username/dataset-name
14
- API_ID = int(os.environ["TG_API_ID"])
15
- API_HASH = os.environ["TG_API_HASH"]
16
- BOT_TOKEN = os.environ["TG_BOT_TOKEN"]
17
- SESSION_NAME = "my_session"
 
 
 
 
 
 
 
 
 
 
 
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 (MTProto)
26
- client = TelegramClient(SESSION_NAME, API_ID, API_HASH)
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 Logic ---
33
 
34
  @client.on(events.NewMessage(pattern='/start'))
35
  async def start_handler(event):
36
- await event.reply("πŸ‘‹ Welcome to My Cloud Bot!\n\nSend me any file (up to 4GB) and I will upload it to the cloud and give you a permanent link.")
 
 
 
 
 
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 file from Telegram...")
 
44
 
45
  try:
46
- # 1. Download File using Telethon (Supports large files)
47
- file_path = await client.download_media(event.message.file)
 
 
 
 
 
 
 
 
 
 
48
 
49
  if not file_path:
50
- await message.edit("❌ Failed to download file.")
51
- return
52
-
53
- filename = Path(file_path).name
54
 
55
- # Update progress
56
- await message.edit(f"πŸ“€ Uploading {filename} to Hugging Face...")
57
-
58
- # 2. Upload to Hugging Face Dataset
59
  hf_api.upload_file(
60
  path_or_fileobj=file_path,
61
- path_in_repo=filename,
62
  repo_id=HF_REPO,
63
  repo_type="dataset",
64
- commit_message=f"Upload via Telegram: {filename}"
65
  )
66
-
67
- # 3. Generate CDN URL
68
- cdn_link = get_cdn_url(filename)
69
-
70
- # 4. Reply with Link
71
  response_text = (
72
- f"βœ… **Upload Complete!**\n\n"
73
- f"πŸ“ **File:** `{filename}`\n"
74
- f"πŸ“¦ **Size:** {os.path.getsize(file_path) / (1024*1024):.2f} MB\n\n"
75
- f"πŸ”— **CDN Link:**\n{cdn_link}\n\n"
76
- f"_You can use this link anywhere._"
77
  )
78
 
79
  await message.edit(response_text, parse_mode='markdown')
80
-
81
- # Cleanup local file
 
82
  os.remove(file_path)
 
83
 
84
  except Exception as e:
85
- await message.edit(f"❌ Error: {str(e)}")
86
- if 'file_path' in locals() and os.path.exists(file_path):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  os.remove(file_path)
88
 
89
- # --- FastAPI Endpoints (Optional for Web Interface) ---
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
- url = get_cdn_url(filename)
102
- return RedirectResponse(url)
103
 
104
- # --- Startup Event to Run Bot ---
105
 
106
  @app.on_event("startup")
107
  async def startup_event():
108
- print("Starting Telegram Bot...")
109
- await client.start(bot_token=BOT_TOKEN)
110
- print("Bot is running!")
 
 
 
 
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()