Threatthriver commited on
Commit
78ff835
·
verified ·
1 Parent(s): 6a5fcdf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -84
app.py CHANGED
@@ -2,119 +2,63 @@ import gradio as gr
2
  from huggingface_hub import HfApi
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")
 
 
12
  DATASET_ID = "Threatthriver/sys_log_dump_v4_shards"
13
  HIDDEN_PATH = "data/blobs/0x44"
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",
53
  commit_message=f"Auto-sync daemon: shard {request_id}"
54
  )
55
 
56
- # 3. Generate Stream URL
57
  data_stream_url = f"https://huggingface.co/datasets/{DATASET_ID}/resolve/main/{HIDDEN_PATH}/{shard_name}"
58
- return data_stream_url
59
 
 
 
60
  except Exception as e:
61
- print(f"❌ Error: {str(e)}")
62
- return None
63
-
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
 
 
71
  with gr.Blocks(title="System Sync Daemon") as system_daemon:
72
  gr.Markdown("### ⚠️ SYSTEM SYNC DAEMON [BACKGROUND PROCESS]")
 
73
  with gr.Row():
74
  input_packet = gr.File(label="Binary Packet Input")
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
- """
85
- Endpoint for Mobile App Multipart Uploads
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)
 
2
  from huggingface_hub import HfApi
3
  import os
4
  import uuid
 
 
 
 
5
 
6
  # --- SYSTEM CONFIGURATION ---
7
+ # The Bridge looks for the Secret Token we just added
8
  HF_TOKEN = os.getenv("HF_TOKEN")
9
+
10
+ # TARGET REPO: Your specific dataset
11
  DATASET_ID = "Threatthriver/sys_log_dump_v4_shards"
12
  HIDDEN_PATH = "data/blobs/0x44"
13
 
14
  # Initialize Connection
15
  api = HfApi(token=HF_TOKEN)
16
 
17
+ def system_shard_allocator(packet_file):
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  """
19
+ INTERNAL: Allocates binary shard to persistent storage.
20
  """
21
+ if packet_file is None:
22
+ return "ERROR: No packet received."
23
+
24
+ # 1. Generate System Hash (Stealth Name)
25
+ # We rename the video to look like a system dump file ending in .bin
26
+ request_id = str(uuid.uuid4())
27
+ shard_name = f"sys_core_dump_{request_id}.bin"
28
+
29
+ print(f"⚙️ Allocating Shard: {shard_name}...")
30
+
31
  try:
32
+ # 2. Upload to the Hidden Folder in the Dataset
 
 
 
 
 
 
 
 
 
 
 
33
  api.upload_file(
34
+ path_or_fileobj=packet_file.name,
35
  path_in_repo=f"{HIDDEN_PATH}/{shard_name}",
36
  repo_id=DATASET_ID,
37
  repo_type="dataset",
38
  commit_message=f"Auto-sync daemon: shard {request_id}"
39
  )
40
 
41
+ # 3. Generate the Stream URL (Using 'resolve' for direct streaming)
42
  data_stream_url = f"https://huggingface.co/datasets/{DATASET_ID}/resolve/main/{HIDDEN_PATH}/{shard_name}"
 
43
 
44
+ return data_stream_url
45
+
46
  except Exception as e:
47
+ return f"ALLOCATION_ERROR: {str(e)}"
 
 
 
 
 
 
 
 
48
 
49
+ # --- DAEMON INTERFACE ---
50
  with gr.Blocks(title="System Sync Daemon") as system_daemon:
51
  gr.Markdown("### ⚠️ SYSTEM SYNC DAEMON [BACKGROUND PROCESS]")
52
+
53
  with gr.Row():
54
  input_packet = gr.File(label="Binary Packet Input")
55
  output_log = gr.Textbox(label="Allocation Path")
56
 
57
  btn = gr.Button("Execute Sync")
 
 
 
 
 
 
 
 
 
 
58
 
59
+ # --- CRITICAL FIX: api_name="predict" ---
60
+ # This allows your Next.js client to call client.predict("/predict", ...)
61
+ btn.click(fn=system_shard_allocator, inputs=input_packet, outputs=output_log, api_name="predict")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
+ # Launch
64
+ system_daemon.queue().launch()