Update app.py
Browse files
app.py
CHANGED
|
@@ -5,10 +5,8 @@ from telethon import TelegramClient
|
|
| 5 |
from telethon.errors import SessionPasswordNeededError, PhoneCodeInvalidError, AuthKeyError
|
| 6 |
from huggingface_hub import upload_file
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
from fastapi.staticfiles import StaticFiles
|
| 11 |
-
import uvicorn
|
| 12 |
|
| 13 |
# === Load secrets from .env ===
|
| 14 |
load_dotenv()
|
|
@@ -132,51 +130,54 @@ async def process_filenames(name_input):
|
|
| 132 |
logging.error(f"Error in process_filenames: {e}")
|
| 133 |
return f"β Error: {str(e)}"
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
try:
|
| 143 |
-
with open("index.html", "r", encoding="utf-8") as f:
|
| 144 |
-
return HTMLResponse(content=f.read())
|
| 145 |
-
except FileNotFoundError:
|
| 146 |
-
raise HTTPException(status_code=404, detail="index.html not found")
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
return FileResponse("style.css", media_type="text/css")
|
| 152 |
|
| 153 |
-
@app.
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
return FileResponse("script.js", media_type="application/javascript")
|
| 157 |
|
| 158 |
-
@app.
|
| 159 |
-
|
| 160 |
-
"""Handle file upload requests"""
|
| 161 |
try:
|
| 162 |
-
|
| 163 |
-
|
|
|
|
| 164 |
|
| 165 |
# Check if credentials are configured
|
| 166 |
if not client:
|
| 167 |
-
|
| 168 |
|
| 169 |
-
#
|
| 170 |
-
results =
|
| 171 |
-
return
|
| 172 |
|
| 173 |
except Exception as e:
|
| 174 |
logging.error(f"Error in upload route: {e}")
|
| 175 |
-
|
| 176 |
|
| 177 |
-
@app.
|
| 178 |
-
|
| 179 |
-
"""Health check endpoint"""
|
| 180 |
status = {
|
| 181 |
"status": "healthy",
|
| 182 |
"message": "Hugging Face Uploader is running",
|
|
@@ -185,17 +186,16 @@ async def health():
|
|
| 185 |
"huggingface": bool(HF_TOKEN and REPO_ID),
|
| 186 |
"channel": bool(CHANNEL)
|
| 187 |
},
|
| 188 |
-
"
|
| 189 |
-
"
|
| 190 |
-
"
|
| 191 |
-
"
|
| 192 |
-
"session_file_exists": os.path.exists("my_session.session")
|
| 193 |
}
|
| 194 |
}
|
| 195 |
-
return status
|
| 196 |
|
| 197 |
-
@app.
|
| 198 |
-
|
| 199 |
"""Show configuration status"""
|
| 200 |
config_status = {
|
| 201 |
"API_ID": "β
Set" if API_ID else "β Missing",
|
|
@@ -204,60 +204,65 @@ async def config():
|
|
| 204 |
"CHANNEL_USERNAME": "β
Set" if CHANNEL else "β Missing",
|
| 205 |
"DATASET_REPO": "β
Set" if REPO_ID else "β Missing"
|
| 206 |
}
|
| 207 |
-
|
|
|
|
| 208 |
|
| 209 |
-
@app.
|
| 210 |
-
|
| 211 |
"""Debug endpoint to check file structure"""
|
| 212 |
import glob
|
| 213 |
|
| 214 |
debug_info = {
|
| 215 |
"current_directory": os.getcwd(),
|
|
|
|
|
|
|
|
|
|
| 216 |
"files_in_current_dir": os.listdir('.'),
|
| 217 |
-
"
|
| 218 |
-
"
|
| 219 |
-
"
|
| 220 |
-
"
|
| 221 |
-
"
|
| 222 |
-
"log_file_exists": os.path.exists('upload.log')
|
| 223 |
}
|
| 224 |
|
| 225 |
-
return debug_info
|
| 226 |
|
| 227 |
-
@app.
|
| 228 |
-
|
| 229 |
"""Check Telegram session status"""
|
| 230 |
if not client:
|
| 231 |
-
return {"error": "Client not initialized"}
|
| 232 |
|
| 233 |
try:
|
|
|
|
| 234 |
session_status = {
|
| 235 |
"session_file_exists": os.path.exists('my_session.session'),
|
| 236 |
"client_initialized": bool(client),
|
| 237 |
"session_file_size": os.path.getsize('my_session.session') if os.path.exists('my_session.session') else 0
|
| 238 |
}
|
| 239 |
-
return session_status
|
| 240 |
except Exception as e:
|
| 241 |
-
return {"error": str(e)}
|
| 242 |
|
| 243 |
if __name__ == '__main__':
|
| 244 |
-
print("Starting Hugging Face Uploader
|
| 245 |
print("Configuration status:")
|
| 246 |
print(f" API_ID: {'β
Set' if API_ID else 'β Missing'}")
|
| 247 |
print(f" API_HASH: {'β
Set' if API_HASH else 'β Missing'}")
|
| 248 |
print(f" HF_TOKEN: {'β
Set' if HF_TOKEN else 'β Missing'}")
|
| 249 |
print(f" CHANNEL_USERNAME: {'β
Set' if CHANNEL else 'β Missing'}")
|
| 250 |
print(f" DATASET_REPO: {'β
Set' if REPO_ID else 'β Missing'}")
|
| 251 |
-
print(f"\
|
| 252 |
-
print(f"
|
| 253 |
-
print(f"
|
| 254 |
-
print(f"
|
|
|
|
| 255 |
print(f" Session file exists: {os.path.exists('my_session.session')}")
|
| 256 |
print("\nβ οΈ IMPORTANT: This application requires a pre-authenticated Telegram session.")
|
| 257 |
-
print(" You must create the session file locally first, then upload it to your
|
| 258 |
-
print("\nTo configure, set environment variables in your
|
| 259 |
print("Visit http://localhost:7860 to use the application.")
|
| 260 |
|
| 261 |
# Use port 7860 for Hugging Face Spaces compatibility
|
| 262 |
-
|
| 263 |
|
|
|
|
| 5 |
from telethon.errors import SessionPasswordNeededError, PhoneCodeInvalidError, AuthKeyError
|
| 6 |
from huggingface_hub import upload_file
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
+
from flask import Flask, request, render_template, jsonify
|
| 9 |
+
import threading
|
|
|
|
|
|
|
| 10 |
|
| 11 |
# === Load secrets from .env ===
|
| 12 |
load_dotenv()
|
|
|
|
| 130 |
logging.error(f"Error in process_filenames: {e}")
|
| 131 |
return f"β Error: {str(e)}"
|
| 132 |
|
| 133 |
+
def run_async_in_thread(coro):
|
| 134 |
+
"""Run async function in a separate thread with its own event loop"""
|
| 135 |
+
def run_in_thread():
|
| 136 |
+
loop = asyncio.new_event_loop()
|
| 137 |
+
asyncio.set_event_loop(loop)
|
| 138 |
+
try:
|
| 139 |
+
return loop.run_until_complete(coro)
|
| 140 |
+
finally:
|
| 141 |
+
loop.close()
|
| 142 |
+
|
| 143 |
+
import concurrent.futures
|
| 144 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 145 |
+
future = executor.submit(run_in_thread)
|
| 146 |
+
return future.result()
|
| 147 |
|
| 148 |
+
# === Flask App with explicit template and static folder paths ===
|
| 149 |
+
# Get the directory where this script is located
|
| 150 |
+
basedir = os.path.abspath(os.path.dirname(__file__))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
+
app = Flask(__name__,
|
| 153 |
+
template_folder=os.path.join(basedir, 'templates'),
|
| 154 |
+
static_folder=os.path.join(basedir, 'static'))
|
|
|
|
| 155 |
|
| 156 |
+
@app.route('/')
|
| 157 |
+
def index():
|
| 158 |
+
return render_template('index.html')
|
|
|
|
| 159 |
|
| 160 |
+
@app.route('/upload', methods=['POST'])
|
| 161 |
+
def upload():
|
|
|
|
| 162 |
try:
|
| 163 |
+
filenames_input = request.form.get('filenames', '').strip()
|
| 164 |
+
if not filenames_input:
|
| 165 |
+
return "β Error: No filenames provided", 400
|
| 166 |
|
| 167 |
# Check if credentials are configured
|
| 168 |
if not client:
|
| 169 |
+
return "β Error: Application not configured. Please set up your environment variables with API credentials.", 500
|
| 170 |
|
| 171 |
+
# Run the async function in a separate thread
|
| 172 |
+
results = run_async_in_thread(process_filenames(filenames_input))
|
| 173 |
+
return results
|
| 174 |
|
| 175 |
except Exception as e:
|
| 176 |
logging.error(f"Error in upload route: {e}")
|
| 177 |
+
return f"β Error: {str(e)}", 500
|
| 178 |
|
| 179 |
+
@app.route('/health')
|
| 180 |
+
def health():
|
|
|
|
| 181 |
status = {
|
| 182 |
"status": "healthy",
|
| 183 |
"message": "Hugging Face Uploader is running",
|
|
|
|
| 186 |
"huggingface": bool(HF_TOKEN and REPO_ID),
|
| 187 |
"channel": bool(CHANNEL)
|
| 188 |
},
|
| 189 |
+
"paths": {
|
| 190 |
+
"basedir": basedir,
|
| 191 |
+
"template_folder": app.template_folder,
|
| 192 |
+
"static_folder": app.static_folder
|
|
|
|
| 193 |
}
|
| 194 |
}
|
| 195 |
+
return jsonify(status)
|
| 196 |
|
| 197 |
+
@app.route('/config')
|
| 198 |
+
def config():
|
| 199 |
"""Show configuration status"""
|
| 200 |
config_status = {
|
| 201 |
"API_ID": "β
Set" if API_ID else "β Missing",
|
|
|
|
| 204 |
"CHANNEL_USERNAME": "β
Set" if CHANNEL else "β Missing",
|
| 205 |
"DATASET_REPO": "β
Set" if REPO_ID else "β Missing"
|
| 206 |
}
|
| 207 |
+
|
| 208 |
+
return jsonify(config_status)
|
| 209 |
|
| 210 |
+
@app.route('/debug')
|
| 211 |
+
def debug():
|
| 212 |
"""Debug endpoint to check file structure"""
|
| 213 |
import glob
|
| 214 |
|
| 215 |
debug_info = {
|
| 216 |
"current_directory": os.getcwd(),
|
| 217 |
+
"script_directory": basedir,
|
| 218 |
+
"template_folder": app.template_folder,
|
| 219 |
+
"static_folder": app.static_folder,
|
| 220 |
"files_in_current_dir": os.listdir('.'),
|
| 221 |
+
"templates_exists": os.path.exists('templates'),
|
| 222 |
+
"static_exists": os.path.exists('static'),
|
| 223 |
+
"templates_files": glob.glob('templates/*') if os.path.exists('templates') else [],
|
| 224 |
+
"static_files": glob.glob('static/**/*', recursive=True) if os.path.exists('static') else [],
|
| 225 |
+
"session_file_exists": os.path.exists('my_session.session')
|
|
|
|
| 226 |
}
|
| 227 |
|
| 228 |
+
return jsonify(debug_info)
|
| 229 |
|
| 230 |
+
@app.route('/session-info')
|
| 231 |
+
def session_info():
|
| 232 |
"""Check Telegram session status"""
|
| 233 |
if not client:
|
| 234 |
+
return jsonify({"error": "Client not initialized"})
|
| 235 |
|
| 236 |
try:
|
| 237 |
+
# This is a synchronous check
|
| 238 |
session_status = {
|
| 239 |
"session_file_exists": os.path.exists('my_session.session'),
|
| 240 |
"client_initialized": bool(client),
|
| 241 |
"session_file_size": os.path.getsize('my_session.session') if os.path.exists('my_session.session') else 0
|
| 242 |
}
|
| 243 |
+
return jsonify(session_status)
|
| 244 |
except Exception as e:
|
| 245 |
+
return jsonify({"error": str(e)})
|
| 246 |
|
| 247 |
if __name__ == '__main__':
|
| 248 |
+
print("Starting Hugging Face Uploader...")
|
| 249 |
print("Configuration status:")
|
| 250 |
print(f" API_ID: {'β
Set' if API_ID else 'β Missing'}")
|
| 251 |
print(f" API_HASH: {'β
Set' if API_HASH else 'β Missing'}")
|
| 252 |
print(f" HF_TOKEN: {'β
Set' if HF_TOKEN else 'β Missing'}")
|
| 253 |
print(f" CHANNEL_USERNAME: {'β
Set' if CHANNEL else 'β Missing'}")
|
| 254 |
print(f" DATASET_REPO: {'β
Set' if REPO_ID else 'β Missing'}")
|
| 255 |
+
print(f"\nPaths:")
|
| 256 |
+
print(f" Base directory: {basedir}")
|
| 257 |
+
print(f" Template folder: {app.template_folder}")
|
| 258 |
+
print(f" Static folder: {app.static_folder}")
|
| 259 |
+
print(f"\nSession info:")
|
| 260 |
print(f" Session file exists: {os.path.exists('my_session.session')}")
|
| 261 |
print("\nβ οΈ IMPORTANT: This application requires a pre-authenticated Telegram session.")
|
| 262 |
+
print(" You must create the session file locally first, then upload it to your Space.")
|
| 263 |
+
print("\nTo configure, set environment variables in your Space settings.")
|
| 264 |
print("Visit http://localhost:7860 to use the application.")
|
| 265 |
|
| 266 |
# Use port 7860 for Hugging Face Spaces compatibility
|
| 267 |
+
app.run(host='0.0.0.0', port=7860, debug=False)
|
| 268 |
|