Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,161 +1,198 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
| 2 |
-
from
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
)
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
continue
|
| 95 |
-
|
| 96 |
-
derivatives = photo.get("derivatives", {})
|
| 97 |
-
best = max(
|
| 98 |
-
(d for k, d in derivatives.items() if k.lower() != "posterframe"),
|
| 99 |
-
key=lambda d: int(d.get("fileSize") or 0),
|
| 100 |
-
default=None
|
| 101 |
-
)
|
| 102 |
-
if not best:
|
| 103 |
continue
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
| 108 |
continue
|
| 109 |
-
video_url = f"https://{info['url_location']}{info['url_path']}"
|
| 110 |
-
|
| 111 |
-
poster = None
|
| 112 |
-
pf = derivatives.get("PosterFrame")
|
| 113 |
-
if pf:
|
| 114 |
-
pf_info = asset_map.get(pf.get("checksum"))
|
| 115 |
-
if pf_info:
|
| 116 |
-
poster = f"https://{pf_info['url_location']}{pf_info['url_path']}"
|
| 117 |
-
|
| 118 |
-
videos.append({
|
| 119 |
-
"caption": photo.get("caption", ""),
|
| 120 |
-
"url": video_url,
|
| 121 |
-
"poster": poster or ""
|
| 122 |
-
})
|
| 123 |
-
|
| 124 |
-
return {"videos": videos}
|
| 125 |
-
|
| 126 |
-
except Exception as e:
|
| 127 |
-
logging.exception("Error in get_album")
|
| 128 |
-
return {"error": str(e)}
|
| 129 |
-
|
| 130 |
-
@app.get("/album/{token}/raw")
|
| 131 |
-
async def get_album_raw(token: str):
|
| 132 |
-
try:
|
| 133 |
-
base_url = await get_base_url(token)
|
| 134 |
-
base_url = await get_redirected_base_url(base_url, token)
|
| 135 |
-
metadata = await get_metadata(base_url)
|
| 136 |
-
guids = [photo["photoGuid"] for photo in metadata]
|
| 137 |
-
asset_map = await get_asset_urls(base_url, guids)
|
| 138 |
-
return {"metadata": metadata, "asset_urls": asset_map}
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Header
|
| 2 |
+
from pydantic import BaseModel, Field
|
| 3 |
+
from typing import Optional, Dict, Any, List
|
| 4 |
+
from uuid import uuid4
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
+
import asyncio
|
| 7 |
+
|
| 8 |
+
app = FastAPI(title="Create3 Robot Command Bridge", version="1.0.0")
|
| 9 |
+
|
| 10 |
+
# ====== Simple shared secret auth (optional but recommended) ======
|
| 11 |
+
API_TOKEN = "change-me-please" # set this to your own token
|
| 12 |
+
|
| 13 |
+
def check_token(auth_header: Optional[str]):
|
| 14 |
+
if not API_TOKEN:
|
| 15 |
+
return
|
| 16 |
+
if not auth_header or not auth_header.startswith("Bearer "):
|
| 17 |
+
raise HTTPException(status_code=401, detail="Missing bearer token")
|
| 18 |
+
token = auth_header.split(" ", 1)[1].strip()
|
| 19 |
+
if token != API_TOKEN:
|
| 20 |
+
raise HTTPException(status_code=403, detail="Invalid token")
|
| 21 |
+
|
| 22 |
+
# ====== In-memory command store ======
|
| 23 |
+
# For HF Space demo/testing this is OK.
|
| 24 |
+
# If you restart the app, queue clears.
|
| 25 |
+
commands: Dict[str, Dict[str, Any]] = {}
|
| 26 |
+
queue: List[str] = []
|
| 27 |
+
queue_lock = asyncio.Lock()
|
| 28 |
+
|
| 29 |
+
# ====== Models ======
|
| 30 |
+
class CommandCreate(BaseModel):
|
| 31 |
+
command: str = Field(..., description="Robot command name")
|
| 32 |
+
args: Dict[str, Any] = Field(default_factory=dict, description="Command arguments")
|
| 33 |
+
source: Optional[str] = Field(default="ai", description="Who sent the command")
|
| 34 |
+
priority: int = Field(default=0, description="Higher = earlier in queue")
|
| 35 |
+
ttl_seconds: Optional[int] = Field(default=120, description="Optional expiration")
|
| 36 |
+
|
| 37 |
+
class CommandStatusUpdate(BaseModel):
|
| 38 |
+
status: str = Field(..., description="queued | running | done | failed | expired")
|
| 39 |
+
result: Optional[Dict[str, Any]] = None
|
| 40 |
+
error: Optional[str] = None
|
| 41 |
+
robot_id: Optional[str] = None
|
| 42 |
+
|
| 43 |
+
# ====== Helpers ======
|
| 44 |
+
def now_iso() -> str:
|
| 45 |
+
return datetime.now(timezone.utc).isoformat()
|
| 46 |
+
|
| 47 |
+
def command_expired(cmd: Dict[str, Any]) -> bool:
|
| 48 |
+
ttl = cmd.get("ttl_seconds")
|
| 49 |
+
if not ttl:
|
| 50 |
+
return False
|
| 51 |
+
created = datetime.fromisoformat(cmd["created_at"])
|
| 52 |
+
age = (datetime.now(timezone.utc) - created).total_seconds()
|
| 53 |
+
return age > ttl
|
| 54 |
+
|
| 55 |
+
# ====== API ======
|
| 56 |
+
|
| 57 |
+
@app.get("/")
|
| 58 |
+
async def root():
|
| 59 |
+
return {"ok": True, "service": "create3-command-bridge"}
|
| 60 |
+
|
| 61 |
+
@app.post("/commands")
|
| 62 |
+
async def create_command(cmd: CommandCreate, authorization: Optional[str] = Header(default=None)):
|
| 63 |
+
check_token(authorization)
|
| 64 |
+
|
| 65 |
+
cmd_id = str(uuid4())
|
| 66 |
+
record = {
|
| 67 |
+
"id": cmd_id,
|
| 68 |
+
"command": cmd.command,
|
| 69 |
+
"args": cmd.args,
|
| 70 |
+
"source": cmd.source,
|
| 71 |
+
"priority": cmd.priority,
|
| 72 |
+
"ttl_seconds": cmd.ttl_seconds,
|
| 73 |
+
"status": "queued",
|
| 74 |
+
"result": None,
|
| 75 |
+
"error": None,
|
| 76 |
+
"created_at": now_iso(),
|
| 77 |
+
"updated_at": now_iso(),
|
| 78 |
+
"claimed_by": None,
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
async with queue_lock:
|
| 82 |
+
commands[cmd_id] = record
|
| 83 |
+
|
| 84 |
+
# Insert by priority (higher first)
|
| 85 |
+
inserted = False
|
| 86 |
+
for i, queued_id in enumerate(queue):
|
| 87 |
+
if record["priority"] > commands[queued_id]["priority"]:
|
| 88 |
+
queue.insert(i, cmd_id)
|
| 89 |
+
inserted = True
|
| 90 |
+
break
|
| 91 |
+
if not inserted:
|
| 92 |
+
queue.append(cmd_id)
|
| 93 |
+
|
| 94 |
+
return {"ok": True, "command_id": cmd_id, "status": "queued"}
|
| 95 |
+
|
| 96 |
+
@app.get("/commands")
|
| 97 |
+
async def list_commands(limit: int = 20, authorization: Optional[str] = Header(default=None)):
|
| 98 |
+
check_token(authorization)
|
| 99 |
+
# latest updated first
|
| 100 |
+
items = sorted(commands.values(), key=lambda x: x["updated_at"], reverse=True)[:limit]
|
| 101 |
+
return {"ok": True, "items": items}
|
| 102 |
+
|
| 103 |
+
@app.get("/commands/{command_id}")
|
| 104 |
+
async def get_command(command_id: str, authorization: Optional[str] = Header(default=None)):
|
| 105 |
+
check_token(authorization)
|
| 106 |
+
if command_id not in commands:
|
| 107 |
+
raise HTTPException(status_code=404, detail="Command not found")
|
| 108 |
+
return {"ok": True, "item": commands[command_id]}
|
| 109 |
+
|
| 110 |
+
@app.post("/commands/next")
|
| 111 |
+
async def claim_next_command(
|
| 112 |
+
robot_id: str,
|
| 113 |
+
authorization: Optional[str] = Header(default=None),
|
| 114 |
+
):
|
| 115 |
+
"""
|
| 116 |
+
Client polls this endpoint to claim the next command.
|
| 117 |
+
Returns one command and marks it running.
|
| 118 |
+
"""
|
| 119 |
+
check_token(authorization)
|
| 120 |
+
|
| 121 |
+
async with queue_lock:
|
| 122 |
+
# Clean expired queued commands while scanning
|
| 123 |
+
while queue:
|
| 124 |
+
cmd_id = queue.pop(0)
|
| 125 |
+
cmd = commands.get(cmd_id)
|
| 126 |
+
if not cmd:
|
| 127 |
continue
|
| 128 |
+
if cmd["status"] != "queued":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
continue
|
| 130 |
|
| 131 |
+
if command_expired(cmd):
|
| 132 |
+
cmd["status"] = "expired"
|
| 133 |
+
cmd["error"] = "TTL expired before execution"
|
| 134 |
+
cmd["updated_at"] = now_iso()
|
| 135 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
+
cmd["status"] = "running"
|
| 138 |
+
cmd["claimed_by"] = robot_id
|
| 139 |
+
cmd["updated_at"] = now_iso()
|
| 140 |
+
return {"ok": True, "item": cmd}
|
| 141 |
+
|
| 142 |
+
return {"ok": True, "item": None}
|
| 143 |
+
|
| 144 |
+
@app.post("/commands/{command_id}/status")
|
| 145 |
+
async def update_command_status(
|
| 146 |
+
command_id: str,
|
| 147 |
+
update: CommandStatusUpdate,
|
| 148 |
+
authorization: Optional[str] = Header(default=None),
|
| 149 |
+
):
|
| 150 |
+
check_token(authorization)
|
| 151 |
+
|
| 152 |
+
cmd = commands.get(command_id)
|
| 153 |
+
if not cmd:
|
| 154 |
+
raise HTTPException(status_code=404, detail="Command not found")
|
| 155 |
+
|
| 156 |
+
# Basic state update
|
| 157 |
+
cmd["status"] = update.status
|
| 158 |
+
cmd["result"] = update.result
|
| 159 |
+
cmd["error"] = update.error
|
| 160 |
+
if update.robot_id:
|
| 161 |
+
cmd["claimed_by"] = update.robot_id
|
| 162 |
+
cmd["updated_at"] = now_iso()
|
| 163 |
+
|
| 164 |
+
return {"ok": True}
|
| 165 |
+
|
| 166 |
+
@app.post("/commands/{command_id}/cancel")
|
| 167 |
+
async def cancel_command(command_id: str, authorization: Optional[str] = Header(default=None)):
|
| 168 |
+
check_token(authorization)
|
| 169 |
+
|
| 170 |
+
cmd = commands.get(command_id)
|
| 171 |
+
if not cmd:
|
| 172 |
+
raise HTTPException(status_code=404, detail="Command not found")
|
| 173 |
+
|
| 174 |
+
if cmd["status"] in ("done", "failed", "expired"):
|
| 175 |
+
return {"ok": True, "status": cmd["status"], "message": "Already finished"}
|
| 176 |
+
|
| 177 |
+
cmd["status"] = "failed"
|
| 178 |
+
cmd["error"] = "Cancelled by operator"
|
| 179 |
+
cmd["updated_at"] = now_iso()
|
| 180 |
+
|
| 181 |
+
# Remove from queue if still queued
|
| 182 |
+
async with queue_lock:
|
| 183 |
+
if command_id in queue:
|
| 184 |
+
queue.remove(command_id)
|
| 185 |
+
|
| 186 |
+
return {"ok": True, "status": "failed"}
|
| 187 |
+
|
| 188 |
+
@app.get("/health")
|
| 189 |
+
async def health():
|
| 190 |
+
queued = sum(1 for c in commands.values() if c["status"] == "queued")
|
| 191 |
+
running = sum(1 for c in commands.values() if c["status"] == "running")
|
| 192 |
+
return {
|
| 193 |
+
"ok": True,
|
| 194 |
+
"queued": queued,
|
| 195 |
+
"running": running,
|
| 196 |
+
"total": len(commands),
|
| 197 |
+
"time": now_iso(),
|
| 198 |
+
}
|