yangtb24 commited on
Commit
b92bb8f
·
verified ·
1 Parent(s): 953aa23

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -22
app.py CHANGED
@@ -1,9 +1,6 @@
1
- from flask import Flask, render_template_string, jsonify, Response # Import Response
2
  import requests
3
- import threading
4
- import time
5
- from sseclient import SSEClient
6
- import os # Import the 'os' module
7
 
8
  app = Flask(__name__)
9
 
@@ -423,7 +420,7 @@ USERNAME = os.environ.get("USERNAME", "yangtb24") # Default to "yangtb24" if no
423
  def fetch_instances(username):
424
  try:
425
  response = requests.get(f"https://huggingface.co/api/spaces?author={username}")
426
- response.raise_for_status() # Raise an exception for bad status codes
427
  user_instances = response.json()
428
  return [{"id": instance["id"].split('/')[1], "owner": username} for instance in user_instances]
429
  except requests.exceptions.RequestException as e:
@@ -432,7 +429,6 @@ def fetch_instances(username):
432
 
433
  @app.route('/')
434
  def index():
435
- # Pass the username to the template
436
  return render_template_string(htmlTemplate, username=USERNAME)
437
 
438
  @app.route('/instances')
@@ -440,32 +436,43 @@ def get_instances():
440
  instances = fetch_instances(USERNAME)
441
  return jsonify(instances)
442
 
443
-
444
  @app.route('/metrics/<username>/<instance_id>')
445
  def stream_metrics(username, instance_id):
446
  url = f"https://api.hf.space/v1/{username}/{instance_id}/live-metrics/sse"
447
 
448
  def generate():
449
- session = requests.Session() # Create a session object
450
  try:
451
- # Add a timeout (e.g., 10 seconds)
452
- response = session.get(url, stream=True, headers={"Accept": "text/event-stream"}, timeout=10)
453
- response.raise_for_status() # Important: raise HTTP errors
454
- client = SSEClient(response)
455
- for event in client.events():
456
- if event.event == 'metric':
457
- yield f"event: {event.event}\\ndata: {event.data}\\n\\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
458
  except requests.exceptions.RequestException as e:
459
  print(f"Request Exception: {e}")
460
- yield f"event: error\ndata: Connection error: {e}\\n\\n" # Include error details
461
  except Exception as e:
462
  print(f"An error occurred: {e}")
463
- yield f"event: error\ndata: An error occurred: {e}\\n\\n" # Include error details
464
- finally:
465
- session.close() # Close the session
466
 
467
  return Response(generate(), mimetype='text/event-stream')
468
 
469
-
470
  if __name__ == '__main__':
471
- app.run(debug=True, host='0.0.0.0', port=7860) #Huggingface use 7860 port
 
1
+ from flask import Flask, render_template_string, jsonify, Response
2
  import requests
3
+ import os
 
 
 
4
 
5
  app = Flask(__name__)
6
 
 
420
  def fetch_instances(username):
421
  try:
422
  response = requests.get(f"https://huggingface.co/api/spaces?author={username}")
423
+ response.raise_for_status()
424
  user_instances = response.json()
425
  return [{"id": instance["id"].split('/')[1], "owner": username} for instance in user_instances]
426
  except requests.exceptions.RequestException as e:
 
429
 
430
  @app.route('/')
431
  def index():
 
432
  return render_template_string(htmlTemplate, username=USERNAME)
433
 
434
  @app.route('/instances')
 
436
  instances = fetch_instances(USERNAME)
437
  return jsonify(instances)
438
 
 
439
  @app.route('/metrics/<username>/<instance_id>')
440
  def stream_metrics(username, instance_id):
441
  url = f"https://api.hf.space/v1/{username}/{instance_id}/live-metrics/sse"
442
 
443
  def generate():
 
444
  try:
445
+ # Use a reasonable timeout
446
+ response = requests.get(url, stream=True, headers={"Accept": "text/event-stream"}, timeout=15)
447
+ response.raise_for_status()
448
+
449
+ buffer = ""
450
+ for chunk in response.iter_content(chunk_size=1024, decode_unicode=True):
451
+ if chunk:
452
+ buffer += chunk
453
+ while "\n\n" in buffer:
454
+ event_data, buffer = buffer.split("\n\n", 1)
455
+ # Basic SSE parsing (event: ...\ndata: ...)
456
+ lines = event_data.split("\n")
457
+ event_type = "message" # Default event type
458
+ data_lines = []
459
+ for line in lines:
460
+ if line.startswith("event:"):
461
+ event_type = line.split(":", 1)[1].strip()
462
+ elif line.startswith("data:"):
463
+ data_lines.append(line.split(":", 1)[1].strip())
464
+
465
+ if event_type == "metric": # Only send metric event
466
+ yield f"event: {event_type}\ndata: {''.join(data_lines)}\n\n"
467
+
468
  except requests.exceptions.RequestException as e:
469
  print(f"Request Exception: {e}")
470
+ yield f"event: error\ndata: Connection error: {e}\\n\\n"
471
  except Exception as e:
472
  print(f"An error occurred: {e}")
473
+ yield f"event: error\ndata: An error occurred: {e}\\n\\n"
 
 
474
 
475
  return Response(generate(), mimetype='text/event-stream')
476
 
 
477
  if __name__ == '__main__':
478
+ app.run(debug=True, host='0.0.0.0', port=7860)