Threatthriver commited on
Commit
6a5fcdf
·
verified ·
1 Parent(s): 57816bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -17
app.py CHANGED
@@ -3,7 +3,9 @@ from huggingface_hub import HfApi
3
  import os
4
  import uuid
5
  from fastapi import FastAPI, UploadFile, File
 
6
  import uvicorn
 
7
 
8
  # --- SYSTEM CONFIGURATION ---
9
  HF_TOKEN = os.getenv("HF_TOKEN")
@@ -12,26 +14,39 @@ HIDDEN_PATH = "data/blobs/0x44"
12
 
13
  # Initialize Connection
14
  api = HfApi(token=HF_TOKEN)
 
 
15
  app = FastAPI()
16
 
 
 
 
 
 
 
 
 
 
17
  # --- HELPER FUNCTION ---
18
- def upload_logic(file_obj, filename_hint="video.mp4"):
19
  """
20
  Core upload logic shared by both Gradio (Web) and FastAPI (Mobile)
21
  """
22
  try:
23
  # 1. Generate Stealth Name
24
  request_id = str(uuid.uuid4())
25
- extension = os.path.splitext(filename_hint)[1] or ".bin"
26
- if extension == ".bin": extension = ".mp4" # Default to mp4 if unknown
27
-
 
 
28
  shard_name = f"sys_core_dump_{request_id}{extension}"
29
 
30
  print(f"⚙️ Allocating Shard: {shard_name}...")
31
 
32
  # 2. Upload to Hidden Folder
33
  api.upload_file(
34
- path_or_fileobj=file_obj,
35
  path_in_repo=f"{HIDDEN_PATH}/{shard_name}",
36
  repo_id=DATASET_ID,
37
  repo_type="dataset",
@@ -49,8 +64,7 @@ def upload_logic(file_obj, filename_hint="video.mp4"):
49
  # --- WEB INTERFACE (GRADIO) ---
50
  def system_shard_allocator(packet_file):
51
  if packet_file is None: return "ERROR: No packet received."
52
-
53
- # Gradio passes a NamedTemporaryFile wrapper, we use its path
54
  url = upload_logic(packet_file.name, packet_file.name)
55
  return url if url else "ALLOCATION_ERROR"
56
 
@@ -61,11 +75,10 @@ with gr.Blocks(title="System Sync Daemon") as system_daemon:
61
  output_log = gr.Textbox(label="Allocation Path")
62
 
63
  btn = gr.Button("Execute Sync")
64
- # Web uses 'predict' endpoint via Gradio Client
65
  btn.click(fn=system_shard_allocator, inputs=input_packet, outputs=output_log, api_name="predict")
66
 
67
  # --- MOBILE INTERFACE (FASTAPI) ---
68
- # This matches the endpoint in your mobile app: /upload_stream
69
  @app.post("/upload_stream")
70
  async def upload_stream(video: UploadFile = File(...)):
71
  """
@@ -73,17 +86,35 @@ async def upload_stream(video: UploadFile = File(...)):
73
  """
74
  print(f"📱 Receiving mobile stream: {video.filename}")
75
 
76
- # Pass the specialized file object from FastAPI directly to HfApi
77
- url = upload_logic(video.file, video.filename)
78
-
79
- if url:
80
- return {"url": url}
81
- else:
82
- return {"error": "Upload failed"}, 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  # Mount Gradio to the root of FastAPI
 
85
  app = gr.mount_gradio_app(app, system_daemon, path="/")
86
 
87
- # If running locally (Space handles this automatically usually, but good for testing)
88
  if __name__ == "__main__":
89
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
3
  import os
4
  import uuid
5
  from fastapi import FastAPI, UploadFile, File
6
+ from fastapi.middleware.cors import CORSMiddleware
7
  import uvicorn
8
+ import shutil
9
 
10
  # --- SYSTEM CONFIGURATION ---
11
  HF_TOKEN = os.getenv("HF_TOKEN")
 
14
 
15
  # Initialize Connection
16
  api = HfApi(token=HF_TOKEN)
17
+
18
+ # Initialize FastAPI
19
  app = FastAPI()
20
 
21
+ # Add CORS to allow mobile app requests
22
+ app.add_middleware(
23
+ CORSMiddleware,
24
+ allow_origins=["*"],
25
+ allow_credentials=True,
26
+ allow_methods=["*"],
27
+ allow_headers=["*"],
28
+ )
29
+
30
  # --- HELPER FUNCTION ---
31
+ def upload_logic(file_path, filename_hint="video.mp4"):
32
  """
33
  Core upload logic shared by both Gradio (Web) and FastAPI (Mobile)
34
  """
35
  try:
36
  # 1. Generate Stealth Name
37
  request_id = str(uuid.uuid4())
38
+ extension = os.path.splitext(filename_hint)[1] or ".mp4"
39
+ # Ensure we don't end up with weird extensions
40
+ if len(extension) > 5 or extension == ".bin":
41
+ extension = ".mp4"
42
+
43
  shard_name = f"sys_core_dump_{request_id}{extension}"
44
 
45
  print(f"⚙️ Allocating Shard: {shard_name}...")
46
 
47
  # 2. Upload to Hidden Folder
48
  api.upload_file(
49
+ path_or_fileobj=file_path,
50
  path_in_repo=f"{HIDDEN_PATH}/{shard_name}",
51
  repo_id=DATASET_ID,
52
  repo_type="dataset",
 
64
  # --- WEB INTERFACE (GRADIO) ---
65
  def system_shard_allocator(packet_file):
66
  if packet_file is None: return "ERROR: No packet received."
67
+ # Gradio handles cleanup, we just use the path
 
68
  url = upload_logic(packet_file.name, packet_file.name)
69
  return url if url else "ALLOCATION_ERROR"
70
 
 
75
  output_log = gr.Textbox(label="Allocation Path")
76
 
77
  btn = gr.Button("Execute Sync")
78
+ # 'predict' API name enabled for website compatibility
79
  btn.click(fn=system_shard_allocator, inputs=input_packet, outputs=output_log, api_name="predict")
80
 
81
  # --- MOBILE INTERFACE (FASTAPI) ---
 
82
  @app.post("/upload_stream")
83
  async def upload_stream(video: UploadFile = File(...)):
84
  """
 
86
  """
87
  print(f"📱 Receiving mobile stream: {video.filename}")
88
 
89
+ try:
90
+ # Create a temporary file to store the upload
91
+ temp_filename = f"temp_{uuid.uuid4()}_{video.filename}"
92
+ with open(temp_filename, "wb") as buffer:
93
+ shutil.copyfileobj(video.file, buffer)
94
+
95
+ # Upload
96
+ url = upload_logic(temp_filename, video.filename)
97
+
98
+ # Cleanup
99
+ if os.path.exists(temp_filename):
100
+ os.remove(temp_filename)
101
+
102
+ if url:
103
+ return {"url": url}
104
+ else:
105
+ return {"error": "Upload failed"}, 500
106
+
107
+ except Exception as e:
108
+ print(f"Error processing mobile upload: {e}")
109
+ return {"error": str(e)}, 500
110
+
111
+ # IMPORTANT: Enable queueing BEFORE mounting
112
+ system_daemon.queue()
113
 
114
  # Mount Gradio to the root of FastAPI
115
+ # This allows both / (Gradio) and /upload_stream (API) to work
116
  app = gr.mount_gradio_app(app, system_daemon, path="/")
117
 
118
+ # Entry point for HF Spaces
119
  if __name__ == "__main__":
120
  uvicorn.run(app, host="0.0.0.0", port=7860)