Spaces:
Running
on
Zero
Running
on
Zero
xiaoyuxi
commited on
Commit
·
af98c4c
1
Parent(s):
26829ea
backend
Browse files
app.py
CHANGED
|
@@ -4,34 +4,208 @@ import json
|
|
| 4 |
import numpy as np
|
| 5 |
import cv2
|
| 6 |
import base64
|
|
|
|
|
|
|
| 7 |
from typing import List, Tuple
|
| 8 |
|
| 9 |
# Backend Space URL - replace with your actual backend space URL
|
| 10 |
BACKEND_SPACE_URL = "Yuxihenry/SpatialTrackerV2_Backend" # Replace with actual backend space URL
|
| 11 |
hf_token = os.getenv("HF_TOKEN") # Replace with your actual Hugging Face token
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
# Flag to track if backend is available
|
| 14 |
BACKEND_AVAILABLE = False
|
| 15 |
backend_client = None
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
def initialize_backend():
|
| 18 |
"""Initialize backend connection using gradio_client"""
|
| 19 |
global backend_client, BACKEND_AVAILABLE
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
try:
|
| 21 |
-
print(f"Attempting
|
| 22 |
|
| 23 |
# Use gradio_client for proper API access
|
| 24 |
from gradio_client import Client
|
| 25 |
-
backend_client = Client(f"https://huggingface.co/spaces/{BACKEND_SPACE_URL}", hf_token=hf_token)
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
print(f"🔧 Backend client: {backend_client}")
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
BACKEND_AVAILABLE = True
|
| 31 |
return True
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
except Exception as e:
|
| 34 |
print(f"❌ Backend connection failed: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
print("⚠️ Running in standalone mode (some features may be limited)")
|
| 36 |
BACKEND_AVAILABLE = False
|
| 37 |
return False
|
|
@@ -195,6 +369,21 @@ def select_point(original_img: str, sel_pix: list, point_type: str, evt: gr.Sele
|
|
| 195 |
pass
|
| 196 |
except Exception as e:
|
| 197 |
print(f"Backend API call failed: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
# Fallback to local processing
|
| 199 |
pass
|
| 200 |
|
|
@@ -341,6 +530,21 @@ def launch_viz(grid_size, vo_points, fps, original_image_state):
|
|
| 341 |
print(f"❌ Backend API call failed: {e}")
|
| 342 |
print(f"🔧 Error type: {type(e)}")
|
| 343 |
print(f"🔧 Error details: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
# Fallback to local processing
|
| 345 |
pass
|
| 346 |
|
|
@@ -663,9 +867,16 @@ with gr.Blocks(
|
|
| 663 |
|
| 664 |
""")
|
| 665 |
|
| 666 |
-
# Status indicator
|
| 667 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 668 |
gr.Markdown(f"**Status:** {status_text}")
|
|
|
|
| 669 |
|
| 670 |
# GitHub Star Reminder - Added back!
|
| 671 |
gr.HTML("""
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
import cv2
|
| 6 |
import base64
|
| 7 |
+
import requests
|
| 8 |
+
import time
|
| 9 |
from typing import List, Tuple
|
| 10 |
|
| 11 |
# Backend Space URL - replace with your actual backend space URL
|
| 12 |
BACKEND_SPACE_URL = "Yuxihenry/SpatialTrackerV2_Backend" # Replace with actual backend space URL
|
| 13 |
hf_token = os.getenv("HF_TOKEN") # Replace with your actual Hugging Face token
|
| 14 |
|
| 15 |
+
# Debug information
|
| 16 |
+
print(f"🔧 Environment Debug Info:")
|
| 17 |
+
print(f" - Backend URL: {BACKEND_SPACE_URL}")
|
| 18 |
+
print(f" - HF Token available: {'Yes' if hf_token else 'No'}")
|
| 19 |
+
print(f" - HF Token length: {len(hf_token) if hf_token else 0}")
|
| 20 |
+
|
| 21 |
# Flag to track if backend is available
|
| 22 |
BACKEND_AVAILABLE = False
|
| 23 |
backend_client = None
|
| 24 |
|
| 25 |
+
def check_user_permissions():
|
| 26 |
+
"""Check if user has necessary permissions"""
|
| 27 |
+
print("🔐 Checking user permissions...")
|
| 28 |
+
|
| 29 |
+
if not hf_token:
|
| 30 |
+
print("❌ No HF Token found")
|
| 31 |
+
print("🔧 To get a token:")
|
| 32 |
+
print(" 1. Go to https://huggingface.co/settings/tokens")
|
| 33 |
+
print(" 2. Create a new token with 'read' permissions")
|
| 34 |
+
print(" 3. Set it as environment variable: export HF_TOKEN='your_token'")
|
| 35 |
+
return False
|
| 36 |
+
|
| 37 |
+
# Try to access user info
|
| 38 |
+
try:
|
| 39 |
+
headers = {'Authorization': f'Bearer {hf_token}'}
|
| 40 |
+
response = requests.get('https://huggingface.co/api/whoami', headers=headers, timeout=5)
|
| 41 |
+
|
| 42 |
+
if response.status_code == 200:
|
| 43 |
+
user_info = response.json()
|
| 44 |
+
username = user_info.get('name', 'Unknown')
|
| 45 |
+
print(f"✅ Authenticated as: {username}")
|
| 46 |
+
|
| 47 |
+
# Check if user has access to the specific space
|
| 48 |
+
space_url = f"https://huggingface.co/api/spaces/{BACKEND_SPACE_URL}"
|
| 49 |
+
space_response = requests.get(space_url, headers=headers, timeout=5)
|
| 50 |
+
|
| 51 |
+
if space_response.status_code == 200:
|
| 52 |
+
print("✅ You have access to the backend Space")
|
| 53 |
+
return True
|
| 54 |
+
elif space_response.status_code == 401:
|
| 55 |
+
print("❌ You don't have access to the backend Space")
|
| 56 |
+
print("🔧 Solutions:")
|
| 57 |
+
print(" 1. Contact the Space owner to add you as collaborator")
|
| 58 |
+
print(" 2. Ask the owner to make the Space public")
|
| 59 |
+
return False
|
| 60 |
+
elif space_response.status_code == 404:
|
| 61 |
+
print("❌ Backend Space not found")
|
| 62 |
+
print("🔧 Please check if the Space URL is correct")
|
| 63 |
+
return False
|
| 64 |
+
else:
|
| 65 |
+
print(f"⚠️ Unexpected response checking Space access: {space_response.status_code}")
|
| 66 |
+
return False
|
| 67 |
+
|
| 68 |
+
else:
|
| 69 |
+
print(f"❌ Token validation failed: {response.status_code}")
|
| 70 |
+
print("🔧 Your token might be invalid or expired")
|
| 71 |
+
return False
|
| 72 |
+
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print(f"❌ Error checking permissions: {e}")
|
| 75 |
+
return False
|
| 76 |
+
|
| 77 |
+
def check_backend_space_status():
|
| 78 |
+
"""Check if backend space is running via HTTP request"""
|
| 79 |
+
try:
|
| 80 |
+
backend_url = f"https://huggingface.co/spaces/{BACKEND_SPACE_URL}"
|
| 81 |
+
print(f"🔍 Checking backend space status: {backend_url}")
|
| 82 |
+
|
| 83 |
+
# Prepare headers with authentication if token is available
|
| 84 |
+
headers = {}
|
| 85 |
+
if hf_token:
|
| 86 |
+
headers['Authorization'] = f'Bearer {hf_token}'
|
| 87 |
+
print(f"🔐 Using HF Token for authentication")
|
| 88 |
+
|
| 89 |
+
# Try to access the space page
|
| 90 |
+
response = requests.get(backend_url, headers=headers, timeout=10)
|
| 91 |
+
|
| 92 |
+
if response.status_code == 200:
|
| 93 |
+
print("✅ Backend space page is accessible")
|
| 94 |
+
|
| 95 |
+
# Check if space is running (look for common indicators)
|
| 96 |
+
page_content = response.text.lower()
|
| 97 |
+
if "runtime error" in page_content:
|
| 98 |
+
print("❌ Backend space has runtime error")
|
| 99 |
+
return False
|
| 100 |
+
elif "building" in page_content:
|
| 101 |
+
print("🔄 Backend space is building...")
|
| 102 |
+
return False
|
| 103 |
+
elif "sleeping" in page_content:
|
| 104 |
+
print("😴 Backend space is sleeping")
|
| 105 |
+
return False
|
| 106 |
+
else:
|
| 107 |
+
print("✅ Backend space appears to be running")
|
| 108 |
+
return True
|
| 109 |
+
|
| 110 |
+
elif response.status_code == 401:
|
| 111 |
+
print("❌ Authentication failed (HTTP 401)")
|
| 112 |
+
print("🔧 This means:")
|
| 113 |
+
print(" - The backend Space is private")
|
| 114 |
+
print(" - Your HF Token doesn't have access to this Space")
|
| 115 |
+
print(" - You need to be added as a collaborator to the Space")
|
| 116 |
+
print(" - Or the Space owner needs to make it public")
|
| 117 |
+
return False
|
| 118 |
+
|
| 119 |
+
elif response.status_code == 404:
|
| 120 |
+
print("❌ Backend space not found (HTTP 404)")
|
| 121 |
+
print("🔧 Please check if the Space URL is correct:")
|
| 122 |
+
print(f" Current URL: {BACKEND_SPACE_URL}")
|
| 123 |
+
return False
|
| 124 |
+
|
| 125 |
+
else:
|
| 126 |
+
print(f"❌ Backend space not accessible (HTTP {response.status_code})")
|
| 127 |
+
print(f"🔧 Response: {response.text[:200]}...")
|
| 128 |
+
return False
|
| 129 |
+
|
| 130 |
+
except requests.RequestException as e:
|
| 131 |
+
print(f"❌ Failed to check backend space status: {e}")
|
| 132 |
+
return False
|
| 133 |
+
except Exception as e:
|
| 134 |
+
print(f"❌ Unexpected error checking backend: {e}")
|
| 135 |
+
return False
|
| 136 |
+
|
| 137 |
def initialize_backend():
|
| 138 |
"""Initialize backend connection using gradio_client"""
|
| 139 |
global backend_client, BACKEND_AVAILABLE
|
| 140 |
+
|
| 141 |
+
# First check user permissions
|
| 142 |
+
print("🔍 Step 1: Checking user permissions...")
|
| 143 |
+
has_permissions = check_user_permissions()
|
| 144 |
+
|
| 145 |
+
if not has_permissions:
|
| 146 |
+
print("⚠️ Permission check failed, but continuing with connection attempt...")
|
| 147 |
+
|
| 148 |
+
# Then check if the backend space is actually running
|
| 149 |
+
print("🔍 Step 2: Verifying backend space status...")
|
| 150 |
+
space_running = check_backend_space_status()
|
| 151 |
+
|
| 152 |
+
if not space_running:
|
| 153 |
+
print("⚠️ Backend space is not running or accessible")
|
| 154 |
+
print("🔧 Possible solutions:")
|
| 155 |
+
print(" 1. If HTTP 401: Contact the Space owner to add you as collaborator")
|
| 156 |
+
print(" 2. If HTTP 404: Verify the Space URL is correct")
|
| 157 |
+
print(" 3. If sleeping: Wait for the space to wake up")
|
| 158 |
+
print(" 4. Try accessing the Space directly in browser first")
|
| 159 |
+
print(f" 5. Space URL: https://huggingface.co/spaces/{BACKEND_SPACE_URL}")
|
| 160 |
+
|
| 161 |
+
# For now, let's continue and try the gradio_client anyway
|
| 162 |
+
# Sometimes the web page check fails but the API still works
|
| 163 |
+
print("🔄 Continuing with gradio_client attempt despite web check failure...")
|
| 164 |
+
# Don't return False here, let's try the gradio_client connection
|
| 165 |
+
pass
|
| 166 |
+
|
| 167 |
try:
|
| 168 |
+
print(f"🔍 Step 3: Attempting gradio_client connection to: {BACKEND_SPACE_URL}")
|
| 169 |
|
| 170 |
# Use gradio_client for proper API access
|
| 171 |
from gradio_client import Client
|
|
|
|
| 172 |
|
| 173 |
+
# Try to connect with timeout and better error handling
|
| 174 |
+
print("🔄 Creating gradio client connection...")
|
| 175 |
+
backend_client = Client(f"{BACKEND_SPACE_URL}", hf_token=hf_token, download_files=False)
|
| 176 |
+
|
| 177 |
+
print(f"✅ Backend API loaded successfully!")
|
| 178 |
print(f"🔧 Backend client: {backend_client}")
|
| 179 |
|
| 180 |
+
# Skip the problematic API config check and directly mark as available
|
| 181 |
+
# Since the client was created successfully and Space is public
|
| 182 |
+
print("🔧 Skipping API config check due to known issues")
|
| 183 |
+
print("🔧 Marking backend as available for direct API calls")
|
| 184 |
BACKEND_AVAILABLE = True
|
| 185 |
return True
|
| 186 |
+
|
| 187 |
+
except ImportError as import_error:
|
| 188 |
+
print(f"❌ gradio_client import failed: {import_error}")
|
| 189 |
+
print("📦 Please install gradio_client: pip install gradio_client")
|
| 190 |
+
BACKEND_AVAILABLE = False
|
| 191 |
+
return False
|
| 192 |
+
|
| 193 |
except Exception as e:
|
| 194 |
print(f"❌ Backend connection failed: {e}")
|
| 195 |
+
print(f"🔧 Error type: {type(e).__name__}")
|
| 196 |
+
print(f"🔧 Error details: {str(e)}")
|
| 197 |
+
|
| 198 |
+
# Check if it's a specific configuration issue
|
| 199 |
+
if "Could not fetch config" in str(e):
|
| 200 |
+
print("🔧 This might be due to:")
|
| 201 |
+
print(" - Backend Space is not running or deployed")
|
| 202 |
+
print(" - Backend Space is private and requires authentication")
|
| 203 |
+
print(" - Network connectivity issues")
|
| 204 |
+
print(" - Backend Space URL is incorrect")
|
| 205 |
+
|
| 206 |
+
elif "timeout" in str(e).lower():
|
| 207 |
+
print("🔧 Connection timeout - backend might be slow to respond")
|
| 208 |
+
|
| 209 |
print("⚠️ Running in standalone mode (some features may be limited)")
|
| 210 |
BACKEND_AVAILABLE = False
|
| 211 |
return False
|
|
|
|
| 369 |
pass
|
| 370 |
except Exception as e:
|
| 371 |
print(f"Backend API call failed: {e}")
|
| 372 |
+
|
| 373 |
+
# Check for specific gradio_client errors
|
| 374 |
+
if "AppError" in str(type(e)):
|
| 375 |
+
print("🔧 Backend Space has internal errors (AppError)")
|
| 376 |
+
print("🔧 The backend Space code has bugs or configuration issues")
|
| 377 |
+
print("🔧 Contact the Space owner to fix the backend implementation")
|
| 378 |
+
elif "Could not fetch config" in str(e):
|
| 379 |
+
print("🔧 Config fetch failed - possible Gradio version mismatch")
|
| 380 |
+
print("🔧 Frontend and backend may be using incompatible Gradio versions")
|
| 381 |
+
elif "timeout" in str(e).lower():
|
| 382 |
+
print("🔧 Backend request timed out - Space might be overloaded")
|
| 383 |
+
else:
|
| 384 |
+
print(f"🔧 Unexpected error type: {type(e).__name__}")
|
| 385 |
+
|
| 386 |
+
print("🔄 Showing error message instead of visualization...")
|
| 387 |
# Fallback to local processing
|
| 388 |
pass
|
| 389 |
|
|
|
|
| 530 |
print(f"❌ Backend API call failed: {e}")
|
| 531 |
print(f"🔧 Error type: {type(e)}")
|
| 532 |
print(f"🔧 Error details: {str(e)}")
|
| 533 |
+
|
| 534 |
+
# Check for specific gradio_client errors
|
| 535 |
+
if "AppError" in str(type(e)):
|
| 536 |
+
print("🔧 Backend Space has internal errors (AppError)")
|
| 537 |
+
print("🔧 The backend Space code has bugs or configuration issues")
|
| 538 |
+
print("🔧 Contact the Space owner to fix the backend implementation")
|
| 539 |
+
elif "Could not fetch config" in str(e):
|
| 540 |
+
print("🔧 Config fetch failed - possible Gradio version mismatch")
|
| 541 |
+
print("🔧 Frontend and backend may be using incompatible Gradio versions")
|
| 542 |
+
elif "timeout" in str(e).lower():
|
| 543 |
+
print("🔧 Backend request timed out - Space might be overloaded")
|
| 544 |
+
else:
|
| 545 |
+
print(f"🔧 Unexpected error type: {type(e).__name__}")
|
| 546 |
+
|
| 547 |
+
print("🔄 Showing error message instead of visualization...")
|
| 548 |
# Fallback to local processing
|
| 549 |
pass
|
| 550 |
|
|
|
|
| 867 |
|
| 868 |
""")
|
| 869 |
|
| 870 |
+
# Status indicator with more detailed information
|
| 871 |
+
if BACKEND_AVAILABLE:
|
| 872 |
+
status_text = "🟢 Backend Connected"
|
| 873 |
+
status_details = f"Connected to: {BACKEND_SPACE_URL}"
|
| 874 |
+
else:
|
| 875 |
+
status_text = "🟡 Running in Standalone Mode"
|
| 876 |
+
status_details = f"Backend unavailable: {BACKEND_SPACE_URL}"
|
| 877 |
+
|
| 878 |
gr.Markdown(f"**Status:** {status_text}")
|
| 879 |
+
gr.Markdown(f"<small style='color: #666;'>{status_details}</small>", elem_id="status-details")
|
| 880 |
|
| 881 |
# GitHub Star Reminder - Added back!
|
| 882 |
gr.HTML("""
|