amri12310 commited on
Commit
b4d2f75
·
verified ·
1 Parent(s): 4ff3562

Update engine.py

Browse files
Files changed (1) hide show
  1. engine.py +49 -83
engine.py CHANGED
@@ -884,7 +884,7 @@ def internal_kill(u_id):
884
  return "Node Aborted", 200
885
 
886
  # ==========================================
887
- # TURBO LEAD-PIPE PROXY (200MB SHOCK ABSORBER + TV SAFE)
888
  # ==========================================
889
  @app.route('/stream/<u_id>', methods=['GET', 'HEAD'])
890
  @app.route('/stream/<u_id>/<filename>', methods=['GET', 'HEAD'])
@@ -898,10 +898,11 @@ def stream_vault(u_id, filename=None):
898
  total_size, num_chunks, c_size_mb = meta.get('size', 0), meta.get('chunks', 0), meta.get('chunk_size_mb', 500)
899
  chunk_size_bytes = c_size_mb * 1024 * 1024
900
 
 
901
  if request.method == 'HEAD':
902
- # ⚡ FIX 1: application/octet-stream forces TV hardware to sniff the file safely
903
- return Response("", status=200, headers={"Content-Length": str(total_size), "Content-Type": "application/octet-stream", "Accept-Ranges": "bytes"})
904
 
 
905
  range_header = request.headers.get('Range', None)
906
  req_start = 0
907
  req_end = total_size - 1
@@ -918,17 +919,13 @@ def stream_vault(u_id, filename=None):
918
  def generate_turbo_new():
919
  start_chunk_idx = req_start // chunk_size_bytes
920
  first_offset = req_start % chunk_size_bytes
921
-
922
- # ⚡ FIX 2: 200MB Shock Absorber allows seamless .bin file stitching!
923
  data_queue = queue.Queue(maxsize=400)
924
- stop_event = threading.Event()
925
 
926
  def turbo_worker():
927
  try:
928
  for i in range(start_chunk_idx, num_chunks):
929
- if stop_event.is_set(): break
930
  current_offset = first_offset if i == start_chunk_idx else 0
931
- while not stop_event.is_set():
932
  chunk_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{u_id}/{i}.bin"
933
  h = auth.copy()
934
  if current_offset > 0: h["Range"] = f"bytes={current_offset}-"
@@ -937,63 +934,47 @@ def stream_vault(u_id, filename=None):
937
  r.raise_for_status()
938
  expected_len = int(r.headers.get('Content-Length', 0))
939
  bytes_this_req = 0
940
-
941
- # ⚡ FIX 3: Restored to 1MB chunks to fill the 200MB buffer efficiently
942
  for data in r.iter_content(chunk_size=1024*1024):
943
- if stop_event.is_set(): break
944
  if data:
945
- # ⚡ ANTI-DEADLOCK: Try to queue, but check Kill Switch every 0.5s
946
- while not stop_event.is_set():
947
- try:
948
- data_queue.put(data, timeout=0.5)
949
- bytes_this_req += len(data)
950
- current_offset += len(data)
951
- break # Success, move to the next chunk
952
- except queue.Full:
953
- pass # Queue is full, loop around and check stop_event again
954
-
955
- if expected_len > 0 and bytes_this_req < expected_len and not stop_event.is_set():
956
- print(f"⚠️ [NETWORK] HF dropped early. Resuming...", flush=True)
957
  continue
958
  else: break
959
  except Exception as e:
960
- if stop_event.is_set(): break
961
  time.sleep(1)
962
- except Exception as e: pass
963
  finally: data_queue.put(None)
964
 
965
  threading.Thread(target=turbo_worker, daemon=True).start()
966
 
967
  bytes_sent = 0
968
- try:
969
- while bytes_sent < bytes_to_send:
970
- chunk_data = data_queue.get()
971
- if chunk_data is None: break
972
- if bytes_sent + len(chunk_data) > bytes_to_send:
973
- yield chunk_data[:bytes_to_send - bytes_sent]
974
- break
975
- yield chunk_data
976
- bytes_sent += len(chunk_data)
977
- except GeneratorExit:
978
- print("🛑 [PROXY] Client disconnected. Killing worker thread.", flush=True)
979
- stop_event.set()
980
- finally:
981
- stop_event.set()
982
-
983
- # ⚡ FIX 1: application/octet-stream
984
- headers = {"Content-Length": str(bytes_to_send), "Content-Type": "application/octet-stream", "Accept-Ranges": "bytes", "Connection": "keep-alive"}
985
  if range_header: headers["Content-Range"] = f"bytes {req_start}-{req_end}/{total_size}"
986
 
 
987
  if request.args.get('dl', '0') == '1':
988
  headers["Content-Disposition"] = f'attachment; filename="{u_id}.mkv"'
989
 
 
990
  r = Response(stream_with_context(generate_turbo_new()), status=206 if range_header else 200, headers=headers)
991
  r.direct_passthrough = True
992
  return r
993
 
994
  except Exception as e: print(f"Meta A error: {e}", flush=True)
995
 
996
- # ⚡ ROUTE B: OLD Sharded format (Same Upgrades Applied)
997
  all_chunks, total_size = [], 0
998
  for p in [1, 2, 3]:
999
  try:
@@ -1008,10 +989,11 @@ def stream_vault(u_id, filename=None):
1008
 
1009
  all_chunks.sort(key=lambda x: x['start'])
1010
 
 
1011
  if request.method == 'HEAD':
1012
- # ⚡ FIX 1: application/octet-stream
1013
- return Response("", status=200, headers={"Content-Length": str(total_size), "Content-Type": "application/octet-stream", "Accept-Ranges": "bytes"})
1014
 
 
1015
  range_header = request.headers.get('Range', None)
1016
  req_start = 0
1017
  req_end = total_size - 1
@@ -1026,17 +1008,13 @@ def stream_vault(u_id, filename=None):
1026
  bytes_to_send = (req_end - req_start) + 1
1027
 
1028
  def generate_turbo_old():
1029
- # ⚡ FIX 2: 200MB Shock Absorber
1030
  data_queue = queue.Queue(maxsize=400)
1031
- stop_event = threading.Event()
1032
-
1033
  def turbo_worker_old():
1034
  current_start = req_start
1035
  try:
1036
  for chunk in all_chunks:
1037
- if stop_event.is_set(): break
1038
  if chunk['end'] <= current_start: continue
1039
- while current_start < chunk['end'] and not stop_event.is_set():
1040
  url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{u_id}/{chunk['name']}"
1041
  h = auth.copy()
1042
  if current_start > chunk['start']: h["Range"] = f"bytes={current_start - chunk['start']}-"
@@ -1045,56 +1023,44 @@ def stream_vault(u_id, filename=None):
1045
  if r.status_code not in [200, 206]: break
1046
  expected_len = int(r.headers.get('Content-Length', 0))
1047
  bytes_this_req = 0
1048
- # ⚡ FIX 3: 1MB Chunks
1049
  for data in r.iter_content(chunk_size=1024*1024):
1050
- if stop_event.is_set(): break
1051
- if data:
1052
- # ⚡ ANTI-DEADLOCK: Try to queue, but check Kill Switch every 0.5s
1053
- while not stop_event.is_set():
1054
- try:
1055
- data_queue.put(data, timeout=0.5)
1056
- bytes_this_req += len(data)
1057
- current_offset += len(data)
1058
- break # Success, move to the next chunk
1059
- except queue.Full:
1060
- pass # Queue is full, loop around and check stop_event again
1061
- if expected_len > 0 and bytes_this_req < expected_len and not stop_event.is_set():
1062
  continue
1063
  else: break
1064
- except:
1065
- if stop_event.is_set(): break
1066
- time.sleep(1)
1067
- except Exception as e: pass
1068
  finally: data_queue.put(None)
1069
 
1070
  threading.Thread(target=turbo_worker_old, daemon=True).start()
1071
 
1072
  bytes_sent = 0
1073
- try:
1074
- while bytes_sent < bytes_to_send:
1075
- chunk_data = data_queue.get()
1076
- if chunk_data is None: break
1077
- if bytes_sent + len(chunk_data) > bytes_to_send:
1078
- yield chunk_data[:bytes_to_send - bytes_sent]
1079
- break
1080
- yield chunk_data
1081
- bytes_sent += len(chunk_data)
1082
- except GeneratorExit:
1083
- stop_event.set()
1084
- finally:
1085
- stop_event.set()
1086
-
1087
- # ⚡ FIX 1: application/octet-stream
1088
- headers = {"Content-Length": str(bytes_to_send), "Content-Type": "application/octet-stream", "Accept-Ranges": "bytes", "Connection": "keep-alive"}
1089
  if range_header: headers["Content-Range"] = f"bytes {req_start}-{req_end}/{total_size}"
1090
 
 
1091
  if request.args.get('dl', '0') == '1':
1092
  headers["Content-Disposition"] = f'attachment; filename="{u_id}.mkv"'
1093
 
 
1094
  r = Response(stream_with_context(generate_turbo_old()), status=206 if range_header else 200, headers=headers)
1095
  r.direct_passthrough = True
1096
  return r
1097
 
 
1098
  @app.route('/delete_active/<u_id>', methods=['POST'])
1099
  def delete_active(u_id):
1100
  check_auth()
 
884
  return "Node Aborted", 200
885
 
886
  # ==========================================
887
+ # TURBO LEAD-PIPE PROXY (WITH ⚡ DOWNLOAD SUPPORT)
888
  # ==========================================
889
  @app.route('/stream/<u_id>', methods=['GET', 'HEAD'])
890
  @app.route('/stream/<u_id>/<filename>', methods=['GET', 'HEAD'])
 
898
  total_size, num_chunks, c_size_mb = meta.get('size', 0), meta.get('chunks', 0), meta.get('chunk_size_mb', 500)
899
  chunk_size_bytes = c_size_mb * 1024 * 1024
900
 
901
+ # ⚡ LIGHTNING FAST HEAD RESPONSE FOR EXOPLAYER RESUME
902
  if request.method == 'HEAD':
903
+ return Response("", status=200, headers={"Content-Length": str(total_size), "Content-Type": "video/x-matroska", "Accept-Ranges": "bytes"})
 
904
 
905
+ # ⚡ FIXED RANGE PARSING FOR EXOPLAYER RESUME
906
  range_header = request.headers.get('Range', None)
907
  req_start = 0
908
  req_end = total_size - 1
 
919
  def generate_turbo_new():
920
  start_chunk_idx = req_start // chunk_size_bytes
921
  first_offset = req_start % chunk_size_bytes
 
 
922
  data_queue = queue.Queue(maxsize=400)
 
923
 
924
  def turbo_worker():
925
  try:
926
  for i in range(start_chunk_idx, num_chunks):
 
927
  current_offset = first_offset if i == start_chunk_idx else 0
928
+ while True:
929
  chunk_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{u_id}/{i}.bin"
930
  h = auth.copy()
931
  if current_offset > 0: h["Range"] = f"bytes={current_offset}-"
 
934
  r.raise_for_status()
935
  expected_len = int(r.headers.get('Content-Length', 0))
936
  bytes_this_req = 0
 
 
937
  for data in r.iter_content(chunk_size=1024*1024):
 
938
  if data:
939
+ data_queue.put(data)
940
+ bytes_this_req += len(data)
941
+ current_offset += len(data)
942
+ if expected_len > 0 and bytes_this_req < expected_len:
943
+ print(f"⚠️ [NETWORK] HF dropped chunk {i} early. Resuming at {current_offset}...", flush=True)
 
 
 
 
 
 
 
944
  continue
945
  else: break
946
  except Exception as e:
 
947
  time.sleep(1)
948
+ except Exception as e: print(f"Turbo Worker Error: {e}", flush=True)
949
  finally: data_queue.put(None)
950
 
951
  threading.Thread(target=turbo_worker, daemon=True).start()
952
 
953
  bytes_sent = 0
954
+ while bytes_sent < bytes_to_send:
955
+ chunk_data = data_queue.get()
956
+ if chunk_data is None: break
957
+ if bytes_sent + len(chunk_data) > bytes_to_send:
958
+ yield chunk_data[:bytes_to_send - bytes_sent]
959
+ break
960
+ yield chunk_data
961
+ bytes_sent += len(chunk_data)
962
+
963
+ headers = {"Content-Length": str(bytes_to_send), "Content-Type": "video/x-matroska", "Accept-Ranges": "bytes", "Connection": "keep-alive"}
 
 
 
 
 
 
 
964
  if range_header: headers["Content-Range"] = f"bytes {req_start}-{req_end}/{total_size}"
965
 
966
+ # ⚡ ADDED: FORCE BROWSER TO DOWNLOAD FILE IF ?dl=1
967
  if request.args.get('dl', '0') == '1':
968
  headers["Content-Disposition"] = f'attachment; filename="{u_id}.mkv"'
969
 
970
+ # ⚡ DIRECT PASSTHROUGH: Forces TV to recognize it as a standard movie, not a Live Stream!
971
  r = Response(stream_with_context(generate_turbo_new()), status=206 if range_header else 200, headers=headers)
972
  r.direct_passthrough = True
973
  return r
974
 
975
  except Exception as e: print(f"Meta A error: {e}", flush=True)
976
 
977
+ # ⚡ ROUTE B: OLD Sharded format
978
  all_chunks, total_size = [], 0
979
  for p in [1, 2, 3]:
980
  try:
 
989
 
990
  all_chunks.sort(key=lambda x: x['start'])
991
 
992
+ # ⚡ LIGHTNING FAST HEAD RESPONSE FOR EXOPLAYER RESUME
993
  if request.method == 'HEAD':
994
+ return Response("", status=200, headers={"Content-Length": str(total_size), "Content-Type": "video/x-matroska", "Accept-Ranges": "bytes"})
 
995
 
996
+ # ⚡ FIXED RANGE PARSING FOR EXOPLAYER RESUME
997
  range_header = request.headers.get('Range', None)
998
  req_start = 0
999
  req_end = total_size - 1
 
1008
  bytes_to_send = (req_end - req_start) + 1
1009
 
1010
  def generate_turbo_old():
 
1011
  data_queue = queue.Queue(maxsize=400)
 
 
1012
  def turbo_worker_old():
1013
  current_start = req_start
1014
  try:
1015
  for chunk in all_chunks:
 
1016
  if chunk['end'] <= current_start: continue
1017
+ while current_start < chunk['end']:
1018
  url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{u_id}/{chunk['name']}"
1019
  h = auth.copy()
1020
  if current_start > chunk['start']: h["Range"] = f"bytes={current_start - chunk['start']}-"
 
1023
  if r.status_code not in [200, 206]: break
1024
  expected_len = int(r.headers.get('Content-Length', 0))
1025
  bytes_this_req = 0
 
1026
  for data in r.iter_content(chunk_size=1024*1024):
1027
+ if data:
1028
+ data_queue.put(data)
1029
+ current_start += len(data)
1030
+ bytes_this_req += len(data)
1031
+ if expected_len > 0 and bytes_this_req < expected_len:
1032
+ print(f"⚠️ [NETWORK] Old chunk truncated. Resuming...", flush=True)
 
 
 
 
 
 
1033
  continue
1034
  else: break
1035
+ except: time.sleep(1)
1036
+ except Exception as e: print(f"Legacy Worker Error: {e}", flush=True)
 
 
1037
  finally: data_queue.put(None)
1038
 
1039
  threading.Thread(target=turbo_worker_old, daemon=True).start()
1040
 
1041
  bytes_sent = 0
1042
+ while bytes_sent < bytes_to_send:
1043
+ chunk_data = data_queue.get()
1044
+ if chunk_data is None: break
1045
+ if bytes_sent + len(chunk_data) > bytes_to_send:
1046
+ yield chunk_data[:bytes_to_send - bytes_sent]
1047
+ break
1048
+ yield chunk_data
1049
+ bytes_sent += len(chunk_data)
1050
+
1051
+ headers = {"Content-Length": str(bytes_to_send), "Content-Type": "video/x-matroska", "Accept-Ranges": "bytes", "Connection": "keep-alive"}
 
 
 
 
 
 
1052
  if range_header: headers["Content-Range"] = f"bytes {req_start}-{req_end}/{total_size}"
1053
 
1054
+ # ⚡ ADDED: FORCE BROWSER TO DOWNLOAD FILE IF ?dl=1
1055
  if request.args.get('dl', '0') == '1':
1056
  headers["Content-Disposition"] = f'attachment; filename="{u_id}.mkv"'
1057
 
1058
+ # ⚡ DIRECT PASSTHROUGH: Forces TV to recognize it as a standard movie, not a Live Stream!
1059
  r = Response(stream_with_context(generate_turbo_old()), status=206 if range_header else 200, headers=headers)
1060
  r.direct_passthrough = True
1061
  return r
1062
 
1063
+
1064
  @app.route('/delete_active/<u_id>', methods=['POST'])
1065
  def delete_active(u_id):
1066
  check_auth()