Fred808 commited on
Commit
d295fbe
Β·
verified Β·
1 Parent(s): 6e594aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -67
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 fastapi import FastAPI, Form, HTTPException
9
- from fastapi.responses import HTMLResponse, FileResponse
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
- # === FastAPI App ===
137
- app = FastAPI(title="Hugging Face Uploader", description="Upload files from Telegram to Hugging Face datasets")
 
 
 
 
 
 
 
 
 
 
 
138
 
139
- @app.get("/", response_class=HTMLResponse)
140
- async def index():
141
- """Serve the main HTML page"""
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
- @app.get("/style.css")
149
- async def get_css():
150
- """Serve the CSS file"""
151
- return FileResponse("style.css", media_type="text/css")
152
 
153
- @app.get("/script.js")
154
- async def get_js():
155
- """Serve the JavaScript file"""
156
- return FileResponse("script.js", media_type="application/javascript")
157
 
158
- @app.post("/upload")
159
- async def upload(filenames: str = Form(...)):
160
- """Handle file upload requests"""
161
  try:
162
- if not filenames.strip():
163
- raise HTTPException(status_code=400, detail="❌ Error: No filenames provided")
 
164
 
165
  # Check if credentials are configured
166
  if not client:
167
- raise HTTPException(status_code=500, detail="❌ Error: Application not configured. Please set up your environment variables with API credentials.")
168
 
169
- # Process filenames using the async function
170
- results = await process_filenames(filenames)
171
- return {"results": results}
172
 
173
  except Exception as e:
174
  logging.error(f"Error in upload route: {e}")
175
- raise HTTPException(status_code=500, detail=f"❌ Error: {str(e)}")
176
 
177
- @app.get("/health")
178
- async def health():
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
- "files": {
189
- "index_html_exists": os.path.exists("index.html"),
190
- "style_css_exists": os.path.exists("style.css"),
191
- "script_js_exists": os.path.exists("script.js"),
192
- "session_file_exists": os.path.exists("my_session.session")
193
  }
194
  }
195
- return status
196
 
197
- @app.get("/config")
198
- async def config():
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
- return config_status
 
208
 
209
- @app.get("/debug")
210
- async def debug():
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
- "html_exists": os.path.exists('index.html'),
218
- "css_exists": os.path.exists('style.css'),
219
- "js_exists": os.path.exists('script.js'),
220
- "session_file_exists": os.path.exists('my_session.session'),
221
- "downloads_folder_exists": os.path.exists('downloads'),
222
- "log_file_exists": os.path.exists('upload.log')
223
  }
224
 
225
- return debug_info
226
 
227
- @app.get("/session-info")
228
- async def session_info():
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 with FastAPI...")
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"\nFile structure:")
252
- print(f" index.html exists: {os.path.exists('index.html')}")
253
- print(f" style.css exists: {os.path.exists('style.css')}")
254
- print(f" script.js exists: {os.path.exists('script.js')}")
 
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 deployment.")
258
- print("\nTo configure, set environment variables in your deployment environment.")
259
  print("Visit http://localhost:7860 to use the application.")
260
 
261
  # Use port 7860 for Hugging Face Spaces compatibility
262
- uvicorn.run(app, host="0.0.0.0", port=7860)
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