Spaces:
Running
on
Zero
Running
on
Zero
xiaoyuxi
commited on
Commit
·
2a1f271
1
Parent(s):
7e0fb4c
vggt_da
Browse files- app.py +153 -229
- app_backup.py +1268 -0
app.py
CHANGED
|
@@ -684,11 +684,12 @@ def clear_all():
|
|
| 684 |
gr.update(value=3))
|
| 685 |
|
| 686 |
def clear_all_with_download():
|
| 687 |
-
"""Clear all buffers including download
|
| 688 |
return (None, None, [],
|
| 689 |
gr.update(value=50),
|
| 690 |
gr.update(value=756),
|
| 691 |
gr.update(value=3),
|
|
|
|
| 692 |
None) # HTML download component
|
| 693 |
|
| 694 |
def update_tracker_model(model_name):
|
|
@@ -964,174 +965,84 @@ with gr.Blocks(
|
|
| 964 |
|
| 965 |
Welcome to SpatialTracker V2! This interface allows you to track any pixels in 3D using our model.
|
| 966 |
|
| 967 |
-
|
|
|
|
|
|
|
| 968 |
1. Upload a video file or select from examples below
|
| 969 |
-
2.
|
| 970 |
-
3. Adjust tracking parameters
|
| 971 |
-
4. Click "
|
| 972 |
|
| 973 |
""")
|
| 974 |
|
| 975 |
-
# Status indicator
|
| 976 |
-
if BACKEND_AVAILABLE
|
| 977 |
-
|
| 978 |
-
status_details = f"Connected to: {BACKEND_SPACE_URL}"
|
| 979 |
-
else:
|
| 980 |
-
status_text = "🟡 Running in Standalone Mode"
|
| 981 |
-
status_details = f"Backend unavailable: {BACKEND_SPACE_URL}"
|
| 982 |
-
|
| 983 |
-
gr.Markdown(f"**Status:** {status_text}")
|
| 984 |
-
gr.Markdown(f"<small style='color: #666;'>{status_details}</small>", elem_id="status-details")
|
| 985 |
-
|
| 986 |
-
# Example videos section - moved to top
|
| 987 |
-
with gr.Group(elem_classes=["example-videos"]):
|
| 988 |
-
gr.Markdown("### 📂 Example Videos")
|
| 989 |
-
gr.Markdown("Try these example videos to get started quickly:")
|
| 990 |
-
|
| 991 |
-
# Custom horizontal scrolling video gallery
|
| 992 |
-
gr.HTML("""
|
| 993 |
-
<div style='background-color: #f8f9ff; border-radius: 8px; padding: 10px; margin: 10px 0; border-left: 4px solid #667eea;'>
|
| 994 |
-
<p style='margin: 0; font-size: 13px; color: #666; display: flex; align-items: center; gap: 8px;'>
|
| 995 |
-
<span style='font-size: 16px;'>💡</span>
|
| 996 |
-
<strong>Tip:</strong> Scroll horizontally below to see all example videos
|
| 997 |
-
</p>
|
| 998 |
-
</div>
|
| 999 |
-
""")
|
| 1000 |
-
|
| 1001 |
-
# Define video_input here so it can be referenced in examples
|
| 1002 |
-
video_input = gr.Video(
|
| 1003 |
-
label="Upload Video or Select Example",
|
| 1004 |
-
format="mp4",
|
| 1005 |
-
height=300
|
| 1006 |
-
)
|
| 1007 |
-
|
| 1008 |
-
# Create a horizontal scrolling container for the examples
|
| 1009 |
-
with gr.Group(elem_classes=["horizontal-examples"]):
|
| 1010 |
-
gr.Examples(
|
| 1011 |
-
examples=[
|
| 1012 |
-
["examples/kiss.mp4"],
|
| 1013 |
-
["examples/backpack.mp4"],
|
| 1014 |
-
["examples/pillow.mp4"],
|
| 1015 |
-
["examples/handwave.mp4"],
|
| 1016 |
-
["examples/hockey.mp4"],
|
| 1017 |
-
["examples/drifting.mp4"],
|
| 1018 |
-
["examples/ken_block_0.mp4"],
|
| 1019 |
-
["examples/kitchen.mp4"],
|
| 1020 |
-
["examples/basketball.mp4"],
|
| 1021 |
-
["examples/ego_kc1.mp4"],
|
| 1022 |
-
["examples/vertical_place.mp4"],
|
| 1023 |
-
["examples/ego_teaser.mp4"],
|
| 1024 |
-
["examples/robot_unitree.mp4"],
|
| 1025 |
-
["examples/robot_3.mp4"],
|
| 1026 |
-
["examples/teleop2.mp4"],
|
| 1027 |
-
["examples/pusht.mp4"],
|
| 1028 |
-
["examples/cinema_0.mp4"],
|
| 1029 |
-
["examples/cinema_1.mp4"],
|
| 1030 |
-
],
|
| 1031 |
-
inputs=video_input,
|
| 1032 |
-
label="🎬 Click on any example to load it",
|
| 1033 |
-
examples_per_page=16
|
| 1034 |
-
)
|
| 1035 |
|
|
|
|
| 1036 |
with gr.Row():
|
| 1037 |
with gr.Column(scale=1):
|
| 1038 |
-
#
|
| 1039 |
with gr.Group():
|
| 1040 |
-
gr.Markdown("###
|
| 1041 |
-
gr.Markdown("Click on the object you want to track in the frame below:")
|
| 1042 |
|
| 1043 |
-
|
| 1044 |
-
label="
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
)
|
| 1048 |
|
| 1049 |
-
|
| 1050 |
-
|
| 1051 |
-
|
| 1052 |
-
|
| 1053 |
-
|
| 1054 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1055 |
)
|
| 1056 |
-
|
| 1057 |
-
with gr.Row():
|
| 1058 |
-
reset_points_btn = gr.Button("🔄 Reset Points", variant="secondary")
|
| 1059 |
-
clear_all_btn = gr.Button("🗑️ Clear All", variant="stop")
|
| 1060 |
|
| 1061 |
with gr.Column(scale=1):
|
| 1062 |
-
#
|
| 1063 |
-
with gr.Group():
|
| 1064 |
-
gr.Markdown("### 🎬 Tracking Results")
|
| 1065 |
-
tracking_result_video = gr.Video(
|
| 1066 |
-
label="Tracking Result Video",
|
| 1067 |
-
interactive=False,
|
| 1068 |
-
height=300
|
| 1069 |
-
)
|
| 1070 |
-
|
| 1071 |
-
# HTML文件下载组件
|
| 1072 |
-
html_download = gr.File(
|
| 1073 |
-
label="📥 Download 3D Visualization HTML",
|
| 1074 |
-
interactive=False,
|
| 1075 |
-
visible=True
|
| 1076 |
-
)
|
| 1077 |
-
|
| 1078 |
-
# Advanced settings section - changed to open=True
|
| 1079 |
-
with gr.Accordion("⚙️ Advanced Settings", open=True):
|
| 1080 |
-
gr.Markdown("Adjust these parameters to optimize tracking performance:")
|
| 1081 |
-
with gr.Row():
|
| 1082 |
-
grid_size = gr.Slider(
|
| 1083 |
-
minimum=10,
|
| 1084 |
-
maximum=100,
|
| 1085 |
-
step=10,
|
| 1086 |
-
value=50,
|
| 1087 |
-
label="Grid Size",
|
| 1088 |
-
info="Size of the tracking grid (larger = more detailed)"
|
| 1089 |
-
)
|
| 1090 |
-
vo_points = gr.Slider(
|
| 1091 |
-
minimum=100,
|
| 1092 |
-
maximum=2000,
|
| 1093 |
-
step=50,
|
| 1094 |
-
value=756,
|
| 1095 |
-
label="VO Points",
|
| 1096 |
-
info="Number of visual odometry points (more = better accuracy)"
|
| 1097 |
-
)
|
| 1098 |
-
fps = gr.Slider(
|
| 1099 |
-
minimum=1,
|
| 1100 |
-
maximum=30,
|
| 1101 |
-
step=1,
|
| 1102 |
-
value=3,
|
| 1103 |
-
label="FPS",
|
| 1104 |
-
info="Frames per second for processing (higher = smoother but slower)"
|
| 1105 |
-
)
|
| 1106 |
-
|
| 1107 |
-
# Launch button
|
| 1108 |
-
with gr.Row():
|
| 1109 |
-
launch_btn = gr.Button("🚀 Start Tracking Now!", variant="primary", size="lg")
|
| 1110 |
-
|
| 1111 |
-
# 3D Visualization - Make it larger and more prominent
|
| 1112 |
-
with gr.Row():
|
| 1113 |
-
with gr.Column():
|
| 1114 |
with gr.Group():
|
| 1115 |
gr.Markdown("### 🌐 3D Trajectory Visualization")
|
| 1116 |
-
gr.Markdown("Interactive 3D visualization of 3D point tracking and camera motion:")
|
| 1117 |
viz_html = gr.HTML(
|
| 1118 |
label="3D Trajectory Visualization",
|
| 1119 |
value="""
|
| 1120 |
-
<div style='border: 3px solid #667eea; border-radius:
|
| 1121 |
background: linear-gradient(135deg, #f8f9ff 0%, #e6f3ff 100%);
|
| 1122 |
-
text-align: center; min-height:
|
| 1123 |
flex-direction: column; justify-content: center; align-items: center;
|
| 1124 |
-
box-shadow: 0
|
| 1125 |
-
<div style='font-size:
|
| 1126 |
-
<
|
| 1127 |
3D Trajectory Visualization
|
| 1128 |
-
</
|
| 1129 |
-
<p style='color: #666; font-size:
|
| 1130 |
-
|
| 1131 |
</p>
|
| 1132 |
-
<div style='background: rgba(102, 126, 234, 0.1); border-radius:
|
| 1133 |
-
padding: 12px
|
| 1134 |
-
<span style='color: #667eea; font-weight:
|
| 1135 |
⚡ Powered by SpatialTracker V2
|
| 1136 |
</span>
|
| 1137 |
</div>
|
|
@@ -1139,7 +1050,100 @@ with gr.Blocks(
|
|
| 1139 |
""",
|
| 1140 |
elem_id="viz_container"
|
| 1141 |
)
|
| 1142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1143 |
# Hidden state variables
|
| 1144 |
original_image_state = gr.State(None)
|
| 1145 |
selected_points = gr.State([])
|
|
@@ -1165,95 +1169,15 @@ with gr.Blocks(
|
|
| 1165 |
|
| 1166 |
clear_all_btn.click(
|
| 1167 |
fn=clear_all_with_download,
|
| 1168 |
-
outputs=[video_input, interactive_frame, selected_points, grid_size, vo_points, fps, html_download]
|
| 1169 |
)
|
| 1170 |
|
| 1171 |
launch_btn.click(
|
| 1172 |
fn=launch_viz,
|
| 1173 |
inputs=[grid_size, vo_points, fps, original_image_state],
|
| 1174 |
-
outputs=[viz_html,
|
| 1175 |
)
|
| 1176 |
|
| 1177 |
-
# GitHub Star Reminder - Added back!
|
| 1178 |
-
gr.HTML("""
|
| 1179 |
-
<div style='background: linear-gradient(135deg, #e8eaff 0%, #f0f2ff 100%);
|
| 1180 |
-
border-radius: 10px;
|
| 1181 |
-
padding: 15px;
|
| 1182 |
-
margin: 15px 0;
|
| 1183 |
-
box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
|
| 1184 |
-
border: 1px solid rgba(102, 126, 234, 0.15);'>
|
| 1185 |
-
<div style='text-align: center; color: #4a5568;'>
|
| 1186 |
-
<h3 style='margin: 0 0 10px 0; font-size: 18px; text-shadow: none; color: #2d3748;'>
|
| 1187 |
-
⭐ Love SpatialTracker? Give us a Star! ⭐
|
| 1188 |
-
</h3>
|
| 1189 |
-
<p style='margin: 0 0 12px 0; font-size: 14px; opacity: 0.8; color: #4a5568;'>
|
| 1190 |
-
Help us grow by starring our repository on GitHub! 🚀
|
| 1191 |
-
</p>
|
| 1192 |
-
<div style='display: flex; justify-content: center;'>
|
| 1193 |
-
<a href="https://github.com/henry123-boy/SpaTrackerV2"
|
| 1194 |
-
target="_blank"
|
| 1195 |
-
style='display: inline-flex;
|
| 1196 |
-
align-items: center;
|
| 1197 |
-
gap: 6px;
|
| 1198 |
-
background: rgba(102, 126, 234, 0.1);
|
| 1199 |
-
color: #4a5568;
|
| 1200 |
-
padding: 8px 16px;
|
| 1201 |
-
border-radius: 20px;
|
| 1202 |
-
text-decoration: none;
|
| 1203 |
-
font-weight: bold;
|
| 1204 |
-
font-size: 14px;
|
| 1205 |
-
backdrop-filter: blur(5px);
|
| 1206 |
-
border: 1px solid rgba(102, 126, 234, 0.2);
|
| 1207 |
-
transition: all 0.3s ease;'
|
| 1208 |
-
onmouseover="this.style.background='rgba(102, 126, 234, 0.15)'; this.style.transform='translateY(-1px)'"
|
| 1209 |
-
onmouseout="this.style.background='rgba(102, 126, 234, 0.1)'; this.style.transform='translateY(0)'">
|
| 1210 |
-
<span style='font-size: 16px;'>⭐</span>
|
| 1211 |
-
Star on GitHub
|
| 1212 |
-
</a>
|
| 1213 |
-
</div>
|
| 1214 |
-
</div>
|
| 1215 |
-
</div>
|
| 1216 |
-
""")
|
| 1217 |
-
|
| 1218 |
-
# Acknowledgment section for TAPIR3D - moved to the end
|
| 1219 |
-
gr.HTML("""
|
| 1220 |
-
<div style='background: linear-gradient(135deg, #fff8e1 0%, #fffbf0 100%);
|
| 1221 |
-
border-radius: 8px;
|
| 1222 |
-
padding: 12px;
|
| 1223 |
-
margin: 15px 0;
|
| 1224 |
-
box-shadow: 0 1px 4px rgba(255, 193, 7, 0.1);
|
| 1225 |
-
border: 1px solid rgba(255, 193, 7, 0.2);'>
|
| 1226 |
-
<div style='text-align: center; color: #5d4037;'>
|
| 1227 |
-
<h5 style='margin: 0 0 6px 0; font-size: 14px; color: #5d4037;'>
|
| 1228 |
-
Acknowledgments
|
| 1229 |
-
</h5>
|
| 1230 |
-
<p style='margin: 0; font-size: 12px; opacity: 0.9; color: #5d4037; line-height: 1.3;'>
|
| 1231 |
-
Our 3D visualizer is adapted from <strong>TAPIP3D</strong>. We thank the authors for their excellent work!
|
| 1232 |
-
</p>
|
| 1233 |
-
<div style='margin-top: 6px;'>
|
| 1234 |
-
<a href="https://github.com/zbw001/TAPIP3D"
|
| 1235 |
-
target="_blank"
|
| 1236 |
-
style='display: inline-flex;
|
| 1237 |
-
align-items: center;
|
| 1238 |
-
gap: 3px;
|
| 1239 |
-
background: rgba(255, 193, 7, 0.15);
|
| 1240 |
-
color: #5d4037;
|
| 1241 |
-
padding: 3px 10px;
|
| 1242 |
-
border-radius: 12px;
|
| 1243 |
-
text-decoration: none;
|
| 1244 |
-
font-weight: 500;
|
| 1245 |
-
font-size: 11px;
|
| 1246 |
-
border: 1px solid rgba(255, 193, 7, 0.3);
|
| 1247 |
-
transition: all 0.3s ease;'
|
| 1248 |
-
onmouseover="this.style.background='rgba(255, 193, 7, 0.2)'"
|
| 1249 |
-
onmouseout="this.style.background='rgba(255, 193, 7, 0.15)'">
|
| 1250 |
-
📚 TAPIP3D Repository
|
| 1251 |
-
</a>
|
| 1252 |
-
</div>
|
| 1253 |
-
</div>
|
| 1254 |
-
</div>
|
| 1255 |
-
""")
|
| 1256 |
-
|
| 1257 |
# Launch the interface
|
| 1258 |
if __name__ == "__main__":
|
| 1259 |
print("🌟 Launching SpatialTracker V2 Frontend...")
|
|
|
|
| 684 |
gr.update(value=3))
|
| 685 |
|
| 686 |
def clear_all_with_download():
|
| 687 |
+
"""Clear all buffers including both download components"""
|
| 688 |
return (None, None, [],
|
| 689 |
gr.update(value=50),
|
| 690 |
gr.update(value=756),
|
| 691 |
gr.update(value=3),
|
| 692 |
+
None, # tracking_video_download
|
| 693 |
None) # HTML download component
|
| 694 |
|
| 695 |
def update_tracker_model(model_name):
|
|
|
|
| 965 |
|
| 966 |
Welcome to SpatialTracker V2! This interface allows you to track any pixels in 3D using our model.
|
| 967 |
|
| 968 |
+
**⚡ Quick Start:** Upload video → Click "Start Tracking Now!"
|
| 969 |
+
|
| 970 |
+
**🔬 Advanced Usage with SAM:**
|
| 971 |
1. Upload a video file or select from examples below
|
| 972 |
+
2. Expand "Manual Point Selection" to click on specific objects for SAM-guided tracking
|
| 973 |
+
3. Adjust tracking parameters for optimal performance
|
| 974 |
+
4. Click "Start Tracking Now!" to begin 3D tracking with SAM guidance
|
| 975 |
|
| 976 |
""")
|
| 977 |
|
| 978 |
+
# Status indicator - more compact
|
| 979 |
+
status_info = "🟢 Backend Connected" if BACKEND_AVAILABLE else "🟡 Standalone Mode"
|
| 980 |
+
gr.Markdown(f"**Status:** {status_info} | Backend: {BACKEND_SPACE_URL}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 981 |
|
| 982 |
+
# Main content area - video upload left, 3D visualization right
|
| 983 |
with gr.Row():
|
| 984 |
with gr.Column(scale=1):
|
| 985 |
+
# Video upload section
|
| 986 |
with gr.Group():
|
| 987 |
+
gr.Markdown("### 📂 Select Video")
|
|
|
|
| 988 |
|
| 989 |
+
video_input = gr.Video(
|
| 990 |
+
label="Upload Video or Select Example",
|
| 991 |
+
format="mp4",
|
| 992 |
+
height=250 # Matched height with 3D viz
|
| 993 |
)
|
| 994 |
|
| 995 |
+
# Compact horizontal examples
|
| 996 |
+
gr.Markdown("**Examples:** (scroll horizontally)")
|
| 997 |
+
with gr.Group(elem_classes=["horizontal-examples"]):
|
| 998 |
+
gr.Examples(
|
| 999 |
+
examples=[
|
| 1000 |
+
["examples/kiss.mp4"],
|
| 1001 |
+
["examples/backpack.mp4"],
|
| 1002 |
+
["examples/pillow.mp4"],
|
| 1003 |
+
["examples/handwave.mp4"],
|
| 1004 |
+
["examples/hockey.mp4"],
|
| 1005 |
+
["examples/drifting.mp4"],
|
| 1006 |
+
["examples/ken_block_0.mp4"],
|
| 1007 |
+
["examples/kitchen.mp4"],
|
| 1008 |
+
["examples/basketball.mp4"],
|
| 1009 |
+
["examples/ego_kc1.mp4"],
|
| 1010 |
+
["examples/vertical_place.mp4"],
|
| 1011 |
+
["examples/ego_teaser.mp4"],
|
| 1012 |
+
["examples/robot_unitree.mp4"],
|
| 1013 |
+
["examples/robot_3.mp4"],
|
| 1014 |
+
["examples/teleop2.mp4"],
|
| 1015 |
+
["examples/pusht.mp4"],
|
| 1016 |
+
["examples/cinema_0.mp4"],
|
| 1017 |
+
["examples/cinema_1.mp4"],
|
| 1018 |
+
],
|
| 1019 |
+
inputs=video_input,
|
| 1020 |
+
label="",
|
| 1021 |
+
examples_per_page=18
|
| 1022 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1023 |
|
| 1024 |
with gr.Column(scale=1):
|
| 1025 |
+
# 3D Visualization - moved to top right for immediate visibility
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1026 |
with gr.Group():
|
| 1027 |
gr.Markdown("### 🌐 3D Trajectory Visualization")
|
|
|
|
| 1028 |
viz_html = gr.HTML(
|
| 1029 |
label="3D Trajectory Visualization",
|
| 1030 |
value="""
|
| 1031 |
+
<div style='border: 3px solid #667eea; border-radius: 10px; padding: 20px;
|
| 1032 |
background: linear-gradient(135deg, #f8f9ff 0%, #e6f3ff 100%);
|
| 1033 |
+
text-align: center; min-height: 250px; display: flex;
|
| 1034 |
flex-direction: column; justify-content: center; align-items: center;
|
| 1035 |
+
box-shadow: 0 4px 16px rgba(102, 126, 234, 0.15);'>
|
| 1036 |
+
<div style='font-size: 32px; margin-bottom: 10px;'>🌐</div>
|
| 1037 |
+
<h3 style='color: #667eea; margin-bottom: 8px; font-size: 18px; font-weight: 600;'>
|
| 1038 |
3D Trajectory Visualization
|
| 1039 |
+
</h3>
|
| 1040 |
+
<p style='color: #666; font-size: 13px; line-height: 1.4; max-width: 400px; margin-bottom: 15px;'>
|
| 1041 |
+
Track any pixels in 3D space with camera motion
|
| 1042 |
</p>
|
| 1043 |
+
<div style='background: rgba(102, 126, 234, 0.1); border-radius: 15px;
|
| 1044 |
+
padding: 6px 12px; border: 1px solid rgba(102, 126, 234, 0.2);'>
|
| 1045 |
+
<span style='color: #667eea; font-weight: 500; font-size: 11px;'>
|
| 1046 |
⚡ Powered by SpatialTracker V2
|
| 1047 |
</span>
|
| 1048 |
</div>
|
|
|
|
| 1050 |
""",
|
| 1051 |
elem_id="viz_container"
|
| 1052 |
)
|
| 1053 |
+
|
| 1054 |
+
# Start button section - below video area
|
| 1055 |
+
with gr.Row():
|
| 1056 |
+
with gr.Column(scale=3):
|
| 1057 |
+
launch_btn = gr.Button("🚀 Start Tracking Now!", variant="primary", size="lg")
|
| 1058 |
+
with gr.Column(scale=1):
|
| 1059 |
+
clear_all_btn = gr.Button("🗑️ Clear All", variant="secondary", size="sm")
|
| 1060 |
+
|
| 1061 |
+
# Tracking parameters section
|
| 1062 |
+
with gr.Row():
|
| 1063 |
+
gr.Markdown("### ⚙️ Tracking Parameters")
|
| 1064 |
+
with gr.Row():
|
| 1065 |
+
grid_size = gr.Slider(
|
| 1066 |
+
minimum=10, maximum=100, step=10, value=50,
|
| 1067 |
+
label="Grid Size", info="Tracking detail level"
|
| 1068 |
+
)
|
| 1069 |
+
vo_points = gr.Slider(
|
| 1070 |
+
minimum=100, maximum=2000, step=50, value=756,
|
| 1071 |
+
label="VO Points", info="Motion accuracy"
|
| 1072 |
+
)
|
| 1073 |
+
fps = gr.Slider(
|
| 1074 |
+
minimum=1, maximum=30, step=1, value=3,
|
| 1075 |
+
label="FPS", info="Processing speed"
|
| 1076 |
+
)
|
| 1077 |
+
|
| 1078 |
+
# Advanced Point Selection with SAM - Collapsed by default
|
| 1079 |
+
with gr.Accordion("🎯 Advanced: Manual Point Selection with SAM", open=False):
|
| 1080 |
+
gr.Markdown("""
|
| 1081 |
+
**Use SAM (Segment Anything Model) for precise object selection:**
|
| 1082 |
+
- Click on target objects in the image for SAM-guided segmentation
|
| 1083 |
+
- Positive points: include these areas | Negative points: exclude these areas
|
| 1084 |
+
- Get more accurate 3D tracking results with SAM's powerful segmentation
|
| 1085 |
+
""")
|
| 1086 |
+
|
| 1087 |
+
with gr.Row():
|
| 1088 |
+
with gr.Column():
|
| 1089 |
+
interactive_frame = gr.Image(
|
| 1090 |
+
label="Click to select tracking points with SAM guidance",
|
| 1091 |
+
type="numpy",
|
| 1092 |
+
interactive=True,
|
| 1093 |
+
height=300
|
| 1094 |
+
)
|
| 1095 |
+
|
| 1096 |
+
with gr.Row():
|
| 1097 |
+
point_type = gr.Radio(
|
| 1098 |
+
choices=["positive_point", "negative_point"],
|
| 1099 |
+
value="positive_point",
|
| 1100 |
+
label="Point Type",
|
| 1101 |
+
info="Positive: track these areas | Negative: avoid these areas"
|
| 1102 |
+
)
|
| 1103 |
+
|
| 1104 |
+
with gr.Row():
|
| 1105 |
+
reset_points_btn = gr.Button("🔄 Reset Points", variant="secondary", size="sm")
|
| 1106 |
+
|
| 1107 |
+
# Downloads section - both as download buttons
|
| 1108 |
+
with gr.Row():
|
| 1109 |
+
gr.Markdown("### 📥 Downloads")
|
| 1110 |
+
with gr.Row():
|
| 1111 |
+
with gr.Column(scale=1):
|
| 1112 |
+
tracking_video_download = gr.File(
|
| 1113 |
+
label="📹 Download 2D Tracking Video",
|
| 1114 |
+
interactive=False,
|
| 1115 |
+
visible=True
|
| 1116 |
+
)
|
| 1117 |
+
with gr.Column(scale=1):
|
| 1118 |
+
html_download = gr.File(
|
| 1119 |
+
label="📄 Download 3D Visualization HTML",
|
| 1120 |
+
interactive=False,
|
| 1121 |
+
visible=True
|
| 1122 |
+
)
|
| 1123 |
+
|
| 1124 |
+
# Compact footer
|
| 1125 |
+
gr.HTML("""
|
| 1126 |
+
<div style='background: linear-gradient(135deg, #e8eaff 0%, #f0f2ff 100%);
|
| 1127 |
+
border-radius: 8px; padding: 12px; margin: 10px 0;
|
| 1128 |
+
box-shadow: 0 1px 4px rgba(102, 126, 234, 0.1);
|
| 1129 |
+
border: 1px solid rgba(102, 126, 234, 0.15);'>
|
| 1130 |
+
<div style='display: flex; justify-content: space-between; align-items: center; color: #4a5568;'>
|
| 1131 |
+
<div style='display: flex; align-items: center; gap: 15px;'>
|
| 1132 |
+
<a href="https://github.com/henry123-boy/SpaTrackerV2" target="_blank"
|
| 1133 |
+
style='display: flex; align-items: center; gap: 5px; text-decoration: none; color: #4a5568; font-weight: 500;'>
|
| 1134 |
+
⭐ Star on GitHub
|
| 1135 |
+
</a>
|
| 1136 |
+
<span style='color: #ccc;'>|</span>
|
| 1137 |
+
<a href="https://github.com/zbw001/TAPIP3D" target="_blank"
|
| 1138 |
+
style='display: flex; align-items: center; gap: 5px; text-decoration: none; color: #4a5568; font-size: 12px;'>
|
| 1139 |
+
📚 TAPIP3D Acknowledgments
|
| 1140 |
+
</a>
|
| 1141 |
+
</div>
|
| 1142 |
+
<span style='font-size: 11px; color: #666;'>Powered by SpatialTracker V2</span>
|
| 1143 |
+
</div>
|
| 1144 |
+
</div>
|
| 1145 |
+
""")
|
| 1146 |
+
|
| 1147 |
# Hidden state variables
|
| 1148 |
original_image_state = gr.State(None)
|
| 1149 |
selected_points = gr.State([])
|
|
|
|
| 1169 |
|
| 1170 |
clear_all_btn.click(
|
| 1171 |
fn=clear_all_with_download,
|
| 1172 |
+
outputs=[video_input, interactive_frame, selected_points, grid_size, vo_points, fps, tracking_video_download, html_download]
|
| 1173 |
)
|
| 1174 |
|
| 1175 |
launch_btn.click(
|
| 1176 |
fn=launch_viz,
|
| 1177 |
inputs=[grid_size, vo_points, fps, original_image_state],
|
| 1178 |
+
outputs=[viz_html, tracking_video_download, html_download]
|
| 1179 |
)
|
| 1180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 6 |
+
import base64
|
| 7 |
+
import requests
|
| 8 |
+
import time
|
| 9 |
+
from typing import List, Tuple
|
| 10 |
+
from gradio_client.utils import handle_file
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
# Backend Space URL - replace with your actual backend space URL
|
| 14 |
+
BACKEND_SPACE_URL = "Yuxihenry/SpatialTrackerV2_Backend" # Replace with actual backend space URL
|
| 15 |
+
hf_token = os.getenv("HF_TOKEN") # Replace with your actual Hugging Face token
|
| 16 |
+
|
| 17 |
+
# Debug information
|
| 18 |
+
print(f"🔧 Environment Debug Info:")
|
| 19 |
+
print(f" - Backend URL: {BACKEND_SPACE_URL}")
|
| 20 |
+
print(f" - HF Token available: {'Yes' if hf_token else 'No'}")
|
| 21 |
+
print(f" - HF Token length: {len(hf_token) if hf_token else 0}")
|
| 22 |
+
|
| 23 |
+
# Flag to track if backend is available
|
| 24 |
+
BACKEND_AVAILABLE = False
|
| 25 |
+
backend_client = None
|
| 26 |
+
|
| 27 |
+
def check_user_permissions():
|
| 28 |
+
"""Check if user has necessary permissions"""
|
| 29 |
+
print("🔐 Checking user permissions...")
|
| 30 |
+
|
| 31 |
+
if not hf_token:
|
| 32 |
+
print("❌ No HF Token found")
|
| 33 |
+
print("🔧 To get a token:")
|
| 34 |
+
print(" 1. Go to https://huggingface.co/settings/tokens")
|
| 35 |
+
print(" 2. Create a new token with 'read' permissions")
|
| 36 |
+
print(" 3. Set it as environment variable: export HF_TOKEN='your_token'")
|
| 37 |
+
return False
|
| 38 |
+
|
| 39 |
+
# Try to access user info
|
| 40 |
+
try:
|
| 41 |
+
headers = {'Authorization': f'Bearer {hf_token}'}
|
| 42 |
+
response = requests.get('https://huggingface.co/api/whoami', headers=headers, timeout=5)
|
| 43 |
+
|
| 44 |
+
if response.status_code == 200:
|
| 45 |
+
user_info = response.json()
|
| 46 |
+
username = user_info.get('name', 'Unknown')
|
| 47 |
+
print(f"✅ Authenticated as: {username}")
|
| 48 |
+
|
| 49 |
+
# Check if user has access to the specific space
|
| 50 |
+
space_url = f"https://huggingface.co/api/spaces/{BACKEND_SPACE_URL}"
|
| 51 |
+
space_response = requests.get(space_url, headers=headers, timeout=5)
|
| 52 |
+
|
| 53 |
+
if space_response.status_code == 200:
|
| 54 |
+
print("✅ You have access to the backend Space")
|
| 55 |
+
return True
|
| 56 |
+
elif space_response.status_code == 401:
|
| 57 |
+
print("❌ You don't have access to the backend Space")
|
| 58 |
+
print("🔧 Solutions:")
|
| 59 |
+
print(" 1. Contact the Space owner to add you as collaborator")
|
| 60 |
+
print(" 2. Ask the owner to make the Space public")
|
| 61 |
+
return False
|
| 62 |
+
elif space_response.status_code == 404:
|
| 63 |
+
print("❌ Backend Space not found")
|
| 64 |
+
print("🔧 Please check if the Space URL is correct")
|
| 65 |
+
return False
|
| 66 |
+
else:
|
| 67 |
+
print(f"⚠️ Unexpected response checking Space access: {space_response.status_code}")
|
| 68 |
+
return False
|
| 69 |
+
|
| 70 |
+
else:
|
| 71 |
+
print(f"❌ Token validation failed: {response.status_code}")
|
| 72 |
+
print("🔧 Your token might be invalid or expired")
|
| 73 |
+
return False
|
| 74 |
+
|
| 75 |
+
except Exception as e:
|
| 76 |
+
print(f"❌ Error checking permissions: {e}")
|
| 77 |
+
return False
|
| 78 |
+
|
| 79 |
+
def check_backend_space_status():
|
| 80 |
+
"""Check if backend space is running via HTTP request"""
|
| 81 |
+
try:
|
| 82 |
+
backend_url = f"https://huggingface.co/spaces/{BACKEND_SPACE_URL}"
|
| 83 |
+
print(f"🔍 Checking backend space status: {backend_url}")
|
| 84 |
+
|
| 85 |
+
# Prepare headers with authentication if token is available
|
| 86 |
+
headers = {}
|
| 87 |
+
if hf_token:
|
| 88 |
+
headers['Authorization'] = f'Bearer {hf_token}'
|
| 89 |
+
print(f"🔐 Using HF Token for authentication")
|
| 90 |
+
|
| 91 |
+
# Try to access the space page
|
| 92 |
+
response = requests.get(backend_url, headers=headers, timeout=10)
|
| 93 |
+
|
| 94 |
+
if response.status_code == 200:
|
| 95 |
+
print("✅ Backend space page is accessible")
|
| 96 |
+
|
| 97 |
+
# Check if space is running (look for common indicators)
|
| 98 |
+
page_content = response.text.lower()
|
| 99 |
+
if "runtime error" in page_content:
|
| 100 |
+
print("❌ Backend space has runtime error")
|
| 101 |
+
return False
|
| 102 |
+
elif "building" in page_content:
|
| 103 |
+
print("🔄 Backend space is building...")
|
| 104 |
+
return False
|
| 105 |
+
elif "sleeping" in page_content:
|
| 106 |
+
print("😴 Backend space is sleeping")
|
| 107 |
+
return False
|
| 108 |
+
else:
|
| 109 |
+
print("✅ Backend space appears to be running")
|
| 110 |
+
return True
|
| 111 |
+
|
| 112 |
+
elif response.status_code == 401:
|
| 113 |
+
print("❌ Authentication failed (HTTP 401)")
|
| 114 |
+
print("🔧 This means:")
|
| 115 |
+
print(" - The backend Space is private")
|
| 116 |
+
print(" - Your HF Token doesn't have access to this Space")
|
| 117 |
+
print(" - You need to be added as a collaborator to the Space")
|
| 118 |
+
print(" - Or the Space owner needs to make it public")
|
| 119 |
+
return False
|
| 120 |
+
|
| 121 |
+
elif response.status_code == 404:
|
| 122 |
+
print("❌ Backend space not found (HTTP 404)")
|
| 123 |
+
print("🔧 Please check if the Space URL is correct:")
|
| 124 |
+
print(f" Current URL: {BACKEND_SPACE_URL}")
|
| 125 |
+
return False
|
| 126 |
+
|
| 127 |
+
else:
|
| 128 |
+
print(f"❌ Backend space not accessible (HTTP {response.status_code})")
|
| 129 |
+
print(f"🔧 Response: {response.text[:200]}...")
|
| 130 |
+
return False
|
| 131 |
+
|
| 132 |
+
except requests.RequestException as e:
|
| 133 |
+
print(f"❌ Failed to check backend space status: {e}")
|
| 134 |
+
return False
|
| 135 |
+
except Exception as e:
|
| 136 |
+
print(f"❌ Unexpected error checking backend: {e}")
|
| 137 |
+
return False
|
| 138 |
+
|
| 139 |
+
def initialize_backend():
|
| 140 |
+
"""Initialize backend connection using gradio_client"""
|
| 141 |
+
global backend_client, BACKEND_AVAILABLE
|
| 142 |
+
|
| 143 |
+
try:
|
| 144 |
+
from gradio_client import Client
|
| 145 |
+
|
| 146 |
+
# Connect to HF Space
|
| 147 |
+
if hf_token:
|
| 148 |
+
backend_client = Client(BACKEND_SPACE_URL, hf_token=hf_token)
|
| 149 |
+
else:
|
| 150 |
+
backend_client = Client(BACKEND_SPACE_URL)
|
| 151 |
+
|
| 152 |
+
# Test the connection
|
| 153 |
+
backend_client.view_api()
|
| 154 |
+
BACKEND_AVAILABLE = True
|
| 155 |
+
return True
|
| 156 |
+
|
| 157 |
+
except Exception as e:
|
| 158 |
+
print(f"❌ Backend connection failed: {e}")
|
| 159 |
+
BACKEND_AVAILABLE = False
|
| 160 |
+
return False
|
| 161 |
+
|
| 162 |
+
def numpy_to_base64(arr):
|
| 163 |
+
"""Convert numpy array to base64 string"""
|
| 164 |
+
return base64.b64encode(arr.tobytes()).decode('utf-8')
|
| 165 |
+
|
| 166 |
+
def base64_to_numpy(b64_str, shape, dtype):
|
| 167 |
+
"""Convert base64 string back to numpy array"""
|
| 168 |
+
return np.frombuffer(base64.b64decode(b64_str), dtype=dtype).reshape(shape)
|
| 169 |
+
|
| 170 |
+
def base64_to_image(b64_str):
|
| 171 |
+
"""Convert base64 string to numpy image array"""
|
| 172 |
+
if not b64_str:
|
| 173 |
+
return None
|
| 174 |
+
try:
|
| 175 |
+
# Decode base64 to bytes
|
| 176 |
+
img_bytes = base64.b64decode(b64_str)
|
| 177 |
+
# Convert bytes to numpy array
|
| 178 |
+
nparr = np.frombuffer(img_bytes, np.uint8)
|
| 179 |
+
# Decode image
|
| 180 |
+
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
| 181 |
+
# Convert BGR to RGB
|
| 182 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 183 |
+
return img
|
| 184 |
+
except Exception as e:
|
| 185 |
+
print(f"Error converting base64 to image: {e}")
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
def get_video_name(video_path):
|
| 189 |
+
"""Extract video name without extension"""
|
| 190 |
+
return os.path.splitext(os.path.basename(video_path))[0]
|
| 191 |
+
|
| 192 |
+
def extract_first_frame(video_path):
|
| 193 |
+
"""Extract first frame from video file"""
|
| 194 |
+
try:
|
| 195 |
+
cap = cv2.VideoCapture(video_path)
|
| 196 |
+
ret, frame = cap.read()
|
| 197 |
+
cap.release()
|
| 198 |
+
|
| 199 |
+
if ret:
|
| 200 |
+
# Convert BGR to RGB
|
| 201 |
+
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 202 |
+
return frame_rgb
|
| 203 |
+
else:
|
| 204 |
+
return None
|
| 205 |
+
except Exception as e:
|
| 206 |
+
print(f"Error extracting first frame: {e}")
|
| 207 |
+
return None
|
| 208 |
+
|
| 209 |
+
def handle_video_upload(video):
|
| 210 |
+
"""Handle video upload and extract first frame"""
|
| 211 |
+
if video is None:
|
| 212 |
+
return (None, None, [],
|
| 213 |
+
gr.update(value=50),
|
| 214 |
+
gr.update(value=756),
|
| 215 |
+
gr.update(value=3))
|
| 216 |
+
|
| 217 |
+
try:
|
| 218 |
+
if BACKEND_AVAILABLE and backend_client:
|
| 219 |
+
# Try to use backend API
|
| 220 |
+
try:
|
| 221 |
+
print("🔧 Calling backend API for video upload...")
|
| 222 |
+
|
| 223 |
+
# Call the unified API with upload_video function type - fix: use handle_file wrapper
|
| 224 |
+
result = backend_client.predict(
|
| 225 |
+
"upload_video", # function_type
|
| 226 |
+
handle_file(video), # video file - wrapped with handle_file
|
| 227 |
+
"", # original_image_state (not used for upload)
|
| 228 |
+
[], # selected_points (not used for upload)
|
| 229 |
+
"positive_point", # point_type (not used for upload)
|
| 230 |
+
0, # point_x (not used for upload)
|
| 231 |
+
0, # point_y (not used for upload)
|
| 232 |
+
50, # grid_size (not used for upload)
|
| 233 |
+
756, # vo_points (not used for upload)
|
| 234 |
+
3, # fps (not used for upload)
|
| 235 |
+
api_name="/unified_api"
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
print(f"✅ Backend video upload API call successful!")
|
| 239 |
+
print(f"🔧 Result type: {type(result)}")
|
| 240 |
+
print(f"🔧 Result: {result}")
|
| 241 |
+
|
| 242 |
+
# Parse the result - expect a dict with success status
|
| 243 |
+
if isinstance(result, dict) and result.get("success"):
|
| 244 |
+
# Extract data from backend response
|
| 245 |
+
original_image_state = result.get("original_image_state", "")
|
| 246 |
+
display_image = result.get("display_image", None)
|
| 247 |
+
selected_points = result.get("selected_points", [])
|
| 248 |
+
|
| 249 |
+
# Fix: Convert display_image from list back to numpy array if needed
|
| 250 |
+
if isinstance(display_image, list):
|
| 251 |
+
display_image = np.array(display_image, dtype=np.uint8)
|
| 252 |
+
print(f"🔧 Converted display_image from list to numpy array: {display_image.shape}")
|
| 253 |
+
|
| 254 |
+
# Get video settings based on video name
|
| 255 |
+
video_name = get_video_name(video)
|
| 256 |
+
print(f"🎬 Video path: '{video}' -> Video name: '{video_name}'")
|
| 257 |
+
grid_size_val, vo_points_val, fps_val = get_video_settings(video_name)
|
| 258 |
+
print(f"🎬 Video settings for '{video_name}': grid_size={grid_size_val}, vo_points={vo_points_val}, fps={fps_val}")
|
| 259 |
+
|
| 260 |
+
return (original_image_state, display_image, selected_points,
|
| 261 |
+
gr.update(value=grid_size_val),
|
| 262 |
+
gr.update(value=vo_points_val),
|
| 263 |
+
gr.update(value=fps_val))
|
| 264 |
+
else:
|
| 265 |
+
print("Backend processing failed, using local fallback")
|
| 266 |
+
# Fallback to local processing
|
| 267 |
+
pass
|
| 268 |
+
except Exception as e:
|
| 269 |
+
print(f"Backend API call failed: {e}")
|
| 270 |
+
# Fallback to local processing
|
| 271 |
+
pass
|
| 272 |
+
|
| 273 |
+
# Fallback: local processing
|
| 274 |
+
print("Using local video processing...")
|
| 275 |
+
display_image = extract_first_frame(video)
|
| 276 |
+
|
| 277 |
+
if display_image is not None:
|
| 278 |
+
# Create a state format compatible with backend
|
| 279 |
+
import tempfile
|
| 280 |
+
import shutil
|
| 281 |
+
|
| 282 |
+
# Create a temporary directory for this session
|
| 283 |
+
session_id = str(int(time.time() * 1000)) # Use timestamp as session ID
|
| 284 |
+
temp_dir = os.path.join("temp_frontend", f"session_{session_id}")
|
| 285 |
+
os.makedirs(temp_dir, exist_ok=True)
|
| 286 |
+
|
| 287 |
+
# Copy video to temp directory with standardized name
|
| 288 |
+
video_name = get_video_name(video)
|
| 289 |
+
temp_video_path = os.path.join(temp_dir, f"{video_name}.mp4")
|
| 290 |
+
shutil.copy(video, temp_video_path)
|
| 291 |
+
|
| 292 |
+
# Create state format compatible with backend
|
| 293 |
+
frame_data = {
|
| 294 |
+
'data': numpy_to_base64(display_image),
|
| 295 |
+
'shape': display_image.shape,
|
| 296 |
+
'dtype': str(display_image.dtype),
|
| 297 |
+
'temp_dir': temp_dir,
|
| 298 |
+
'video_name': video_name,
|
| 299 |
+
'video_path': temp_video_path # Keep for backward compatibility
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
original_image_state = json.dumps(frame_data)
|
| 303 |
+
else:
|
| 304 |
+
# Fallback to simple state if frame extraction fails
|
| 305 |
+
original_image_state = json.dumps({
|
| 306 |
+
"video_path": video,
|
| 307 |
+
"frame": "local_processing_failed"
|
| 308 |
+
})
|
| 309 |
+
|
| 310 |
+
# Get video settings
|
| 311 |
+
video_name = get_video_name(video)
|
| 312 |
+
print(f"🎬 Local fallback - Video path: '{video}' -> Video name: '{video_name}'")
|
| 313 |
+
grid_size_val, vo_points_val, fps_val = get_video_settings(video_name)
|
| 314 |
+
print(f"🎬 Local fallback - Video settings for '{video_name}': grid_size={grid_size_val}, vo_points={vo_points_val}, fps={fps_val}")
|
| 315 |
+
|
| 316 |
+
return (original_image_state, display_image, [],
|
| 317 |
+
gr.update(value=grid_size_val),
|
| 318 |
+
gr.update(value=vo_points_val),
|
| 319 |
+
gr.update(value=fps_val))
|
| 320 |
+
|
| 321 |
+
except Exception as e:
|
| 322 |
+
print(f"Error in handle_video_upload: {e}")
|
| 323 |
+
return (None, None, [],
|
| 324 |
+
gr.update(value=50),
|
| 325 |
+
gr.update(value=756),
|
| 326 |
+
gr.update(value=3))
|
| 327 |
+
|
| 328 |
+
def select_point(original_img: str, sel_pix: list, point_type: str, evt: gr.SelectData):
|
| 329 |
+
"""Handle point selection for SAM"""
|
| 330 |
+
if original_img is None:
|
| 331 |
+
return None, []
|
| 332 |
+
|
| 333 |
+
try:
|
| 334 |
+
if BACKEND_AVAILABLE and backend_client:
|
| 335 |
+
# Try to use backend API
|
| 336 |
+
try:
|
| 337 |
+
print(f"🔧 Calling backend select point API: x={evt.index[0]}, y={evt.index[1]}, type={point_type}")
|
| 338 |
+
|
| 339 |
+
# Call the unified API with select_point function type
|
| 340 |
+
result = backend_client.predict(
|
| 341 |
+
"select_point", # function_type
|
| 342 |
+
None, # video file (not used for select_point)
|
| 343 |
+
original_img, # original_image_state
|
| 344 |
+
sel_pix, # selected_points
|
| 345 |
+
point_type, # point_type
|
| 346 |
+
evt.index[0], # point_x
|
| 347 |
+
evt.index[1], # point_y
|
| 348 |
+
50, # grid_size (not used for select_point)
|
| 349 |
+
756, # vo_points (not used for select_point)
|
| 350 |
+
3, # fps (not used for select_point)
|
| 351 |
+
api_name="/unified_api"
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
print(f"✅ Backend select point API call successful!")
|
| 355 |
+
print(f"🔧 Result type: {type(result)}")
|
| 356 |
+
print(f"🔧 Result: {result}")
|
| 357 |
+
|
| 358 |
+
# Parse the result - expect a dict with success status
|
| 359 |
+
if isinstance(result, dict) and result.get("success"):
|
| 360 |
+
display_image = result.get("display_image", None)
|
| 361 |
+
new_sel_pix = result.get("selected_points", sel_pix)
|
| 362 |
+
|
| 363 |
+
# Fix: Convert display_image from list back to numpy array if needed
|
| 364 |
+
if isinstance(display_image, list):
|
| 365 |
+
display_image = np.array(display_image, dtype=np.uint8)
|
| 366 |
+
print(f"🔧 Converted display_image from list to numpy array: {display_image.shape}")
|
| 367 |
+
|
| 368 |
+
return display_image, new_sel_pix
|
| 369 |
+
else:
|
| 370 |
+
print("Backend processing failed, using local fallback")
|
| 371 |
+
# Fallback to local processing
|
| 372 |
+
pass
|
| 373 |
+
except Exception as e:
|
| 374 |
+
print(f"Backend API call failed: {e}")
|
| 375 |
+
|
| 376 |
+
# Check for specific gradio_client errors
|
| 377 |
+
if "AppError" in str(type(e)):
|
| 378 |
+
print("🔧 Backend Space has internal errors (AppError)")
|
| 379 |
+
print("🔧 The backend Space code has bugs or configuration issues")
|
| 380 |
+
print("🔧 Contact the Space owner to fix the backend implementation")
|
| 381 |
+
elif "Could not fetch config" in str(e):
|
| 382 |
+
print("🔧 Config fetch failed - possible Gradio version mismatch")
|
| 383 |
+
print("🔧 Frontend and backend may be using incompatible Gradio versions")
|
| 384 |
+
elif "timeout" in str(e).lower():
|
| 385 |
+
print("🔧 Backend request timed out - Space might be overloaded")
|
| 386 |
+
else:
|
| 387 |
+
print(f"🔧 Unexpected error type: {type(e).__name__}")
|
| 388 |
+
|
| 389 |
+
print("🔄 Showing error message instead of visualization...")
|
| 390 |
+
# Fallback to local processing
|
| 391 |
+
pass
|
| 392 |
+
|
| 393 |
+
# Fallback: local processing with improved visualization
|
| 394 |
+
print("Using local point selection with enhanced visualization...")
|
| 395 |
+
|
| 396 |
+
# Parse original image state
|
| 397 |
+
try:
|
| 398 |
+
state_data = json.loads(original_img)
|
| 399 |
+
video_path = state_data.get("video_path")
|
| 400 |
+
except:
|
| 401 |
+
video_path = None
|
| 402 |
+
|
| 403 |
+
if video_path:
|
| 404 |
+
# Re-extract frame and add point with mask visualization
|
| 405 |
+
display_image = extract_first_frame(video_path)
|
| 406 |
+
if display_image is not None:
|
| 407 |
+
# Add point to the image with enhanced visualization
|
| 408 |
+
x, y = evt.index[0], evt.index[1]
|
| 409 |
+
color = (0, 255, 0) if point_type == 'positive_point' else (255, 0, 0)
|
| 410 |
+
|
| 411 |
+
# Draw a larger, more visible point
|
| 412 |
+
cv2.circle(display_image, (x, y), 8, color, -1)
|
| 413 |
+
cv2.circle(display_image, (x, y), 12, (255, 255, 255), 2)
|
| 414 |
+
|
| 415 |
+
# Add point to selected points list - fix logic to match local version
|
| 416 |
+
new_sel_pix = sel_pix.copy() if sel_pix else []
|
| 417 |
+
new_sel_pix.append([x, y, point_type])
|
| 418 |
+
|
| 419 |
+
return display_image, new_sel_pix
|
| 420 |
+
|
| 421 |
+
return None, []
|
| 422 |
+
|
| 423 |
+
except Exception as e:
|
| 424 |
+
print(f"Error in select_point: {e}")
|
| 425 |
+
return None, []
|
| 426 |
+
|
| 427 |
+
def reset_points(original_img: str, sel_pix):
|
| 428 |
+
"""Reset points and restore original image"""
|
| 429 |
+
if original_img is None:
|
| 430 |
+
return None, []
|
| 431 |
+
|
| 432 |
+
try:
|
| 433 |
+
if BACKEND_AVAILABLE and backend_client:
|
| 434 |
+
# Try to use backend API
|
| 435 |
+
try:
|
| 436 |
+
print("🔧 Calling backend reset points API...")
|
| 437 |
+
|
| 438 |
+
# Call the unified API with reset_points function type
|
| 439 |
+
result = backend_client.predict(
|
| 440 |
+
"reset_points", # function_type
|
| 441 |
+
None, # video file (not used for reset_points)
|
| 442 |
+
original_img, # original_image_state
|
| 443 |
+
sel_pix, # selected_points
|
| 444 |
+
"positive_point", # point_type (not used for reset_points)
|
| 445 |
+
0, # point_x (not used for reset_points)
|
| 446 |
+
0, # point_y (not used for reset_points)
|
| 447 |
+
50, # grid_size (not used for reset_points)
|
| 448 |
+
756, # vo_points (not used for reset_points)
|
| 449 |
+
3, # fps (not used for reset_points)
|
| 450 |
+
api_name="/unified_api"
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
print(f"✅ Backend reset points API call successful!")
|
| 454 |
+
print(f"🔧 Result: {result}")
|
| 455 |
+
|
| 456 |
+
# Parse the result
|
| 457 |
+
if isinstance(result, dict) and result.get("success"):
|
| 458 |
+
display_image = result.get("display_image", None)
|
| 459 |
+
new_sel_pix = result.get("selected_points", [])
|
| 460 |
+
|
| 461 |
+
# Fix: Convert display_image from list back to numpy array if needed
|
| 462 |
+
if isinstance(display_image, list):
|
| 463 |
+
display_image = np.array(display_image, dtype=np.uint8)
|
| 464 |
+
print(f"🔧 Converted display_image from list to numpy array: {display_image.shape}")
|
| 465 |
+
|
| 466 |
+
return display_image, new_sel_pix
|
| 467 |
+
else:
|
| 468 |
+
print("Backend processing failed, using local fallback")
|
| 469 |
+
# Fallback to local processing
|
| 470 |
+
pass
|
| 471 |
+
except Exception as e:
|
| 472 |
+
print(f"Backend API call failed: {e}")
|
| 473 |
+
# Fallback to local processing
|
| 474 |
+
pass
|
| 475 |
+
|
| 476 |
+
# Fallback: local processing
|
| 477 |
+
print("Using local reset points...")
|
| 478 |
+
|
| 479 |
+
# Parse original image state
|
| 480 |
+
try:
|
| 481 |
+
state_data = json.loads(original_img)
|
| 482 |
+
video_path = state_data.get("video_path")
|
| 483 |
+
except:
|
| 484 |
+
video_path = None
|
| 485 |
+
|
| 486 |
+
if video_path:
|
| 487 |
+
# Re-extract original frame
|
| 488 |
+
display_image = extract_first_frame(video_path)
|
| 489 |
+
return display_image, []
|
| 490 |
+
|
| 491 |
+
return None, []
|
| 492 |
+
|
| 493 |
+
except Exception as e:
|
| 494 |
+
print(f"Error in reset_points: {e}")
|
| 495 |
+
return None, []
|
| 496 |
+
|
| 497 |
+
gr.set_static_paths(paths=[Path.cwd().absolute()/"_viz"])
|
| 498 |
+
|
| 499 |
+
def launch_viz(grid_size, vo_points, fps, original_image_state):
|
| 500 |
+
"""Launch visualization with user-specific temp directory"""
|
| 501 |
+
if original_image_state is None:
|
| 502 |
+
return None, None, None
|
| 503 |
+
|
| 504 |
+
try:
|
| 505 |
+
if BACKEND_AVAILABLE and backend_client:
|
| 506 |
+
# Try to use backend API
|
| 507 |
+
try:
|
| 508 |
+
print(f"🔧 Calling backend API with parameters: grid_size={grid_size}, vo_points={vo_points}, fps={fps}")
|
| 509 |
+
print(f"🔧 Original image state type: {type(original_image_state)}")
|
| 510 |
+
print(f"🔧 Original image state preview: {str(original_image_state)[:100]}...")
|
| 511 |
+
|
| 512 |
+
# Validate and potentially fix the original_image_state format
|
| 513 |
+
state_to_send = original_image_state
|
| 514 |
+
|
| 515 |
+
# Check if this is a local processing state that needs to be converted
|
| 516 |
+
try:
|
| 517 |
+
if isinstance(original_image_state, str):
|
| 518 |
+
parsed_state = json.loads(original_image_state)
|
| 519 |
+
if "video_path" in parsed_state and "frame" in parsed_state:
|
| 520 |
+
# This is a local processing state, we need to handle differently
|
| 521 |
+
print("🔧 Detected local processing state, cannot use backend for tracking")
|
| 522 |
+
print("🔧 Backend requires proper video upload state from backend API")
|
| 523 |
+
# Fall through to local processing
|
| 524 |
+
raise ValueError("Local state cannot be processed by backend")
|
| 525 |
+
except json.JSONDecodeError:
|
| 526 |
+
print("🔧 Invalid JSON state, cannot send to backend")
|
| 527 |
+
raise ValueError("Invalid state format")
|
| 528 |
+
|
| 529 |
+
# Call the unified API with run_tracker function type
|
| 530 |
+
result = backend_client.predict(
|
| 531 |
+
"run_tracker", # function_type
|
| 532 |
+
None, # video file (not used for run_tracker)
|
| 533 |
+
state_to_send, # original_image_state
|
| 534 |
+
[], # selected_points (not used for run_tracker)
|
| 535 |
+
"positive_point", # point_type (not used for run_tracker)
|
| 536 |
+
0, # point_x (not used for run_tracker)
|
| 537 |
+
0, # point_y (not used for run_tracker)
|
| 538 |
+
grid_size, # grid_size
|
| 539 |
+
vo_points, # vo_points
|
| 540 |
+
fps, # fps
|
| 541 |
+
api_name="/unified_api"
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
print(f"✅ Backend API call successful!")
|
| 545 |
+
print(f"🔧 Result type: {type(result)}")
|
| 546 |
+
print(f"🔧 Result: {result}")
|
| 547 |
+
|
| 548 |
+
# Parse the result
|
| 549 |
+
if isinstance(result, dict) and result.get("success"):
|
| 550 |
+
viz_html = result.get("viz_html", "")
|
| 551 |
+
track_video_path = result.get("track_video_path", "")
|
| 552 |
+
track_video_content = result.get("track_video_content", None)
|
| 553 |
+
track_video_filename = result.get("track_video_filename", "tracked_video.mp4")
|
| 554 |
+
|
| 555 |
+
# Save HTML to _viz directory (like local version)
|
| 556 |
+
viz_dir = './_viz'
|
| 557 |
+
os.makedirs(viz_dir, exist_ok=True)
|
| 558 |
+
random_path = f'./_viz/_{time.time()}.html'
|
| 559 |
+
|
| 560 |
+
with open(random_path, 'w', encoding='utf-8') as f:
|
| 561 |
+
f.write(viz_html)
|
| 562 |
+
|
| 563 |
+
# Create iframe HTML to display the saved file
|
| 564 |
+
# Create iframe HTML
|
| 565 |
+
iframe_html = f"""
|
| 566 |
+
<div style='border: 3px solid #667eea; border-radius: 10px; overflow: hidden; box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);'>
|
| 567 |
+
<iframe id="viz_iframe" src="/gradio_api/file={random_path}" width="100%" height="950px" style="border:none;"></iframe>
|
| 568 |
+
</div>
|
| 569 |
+
"""
|
| 570 |
+
print(f"💾 HTML saved to: {random_path}")
|
| 571 |
+
print(f"📊 HTML content preview: {viz_html[:200]}...")
|
| 572 |
+
|
| 573 |
+
# If we have base64 encoded video content, save it as a temporary file
|
| 574 |
+
local_video_path = None
|
| 575 |
+
if track_video_content:
|
| 576 |
+
try:
|
| 577 |
+
# Create a temporary file for the video
|
| 578 |
+
temp_video_dir = "temp_frontend_videos"
|
| 579 |
+
os.makedirs(temp_video_dir, exist_ok=True)
|
| 580 |
+
|
| 581 |
+
# Generate unique filename to avoid conflicts
|
| 582 |
+
timestamp = str(int(time.time() * 1000))
|
| 583 |
+
local_video_path = os.path.join(temp_video_dir, f"{timestamp}_{track_video_filename}")
|
| 584 |
+
|
| 585 |
+
# Decode base64 and save as video file
|
| 586 |
+
video_bytes = base64.b64decode(track_video_content)
|
| 587 |
+
with open(local_video_path, 'wb') as f:
|
| 588 |
+
f.write(video_bytes)
|
| 589 |
+
|
| 590 |
+
print(f"✅ Successfully saved tracking video to: {local_video_path}")
|
| 591 |
+
print(f"🔧 Video file size: {len(video_bytes)} bytes")
|
| 592 |
+
|
| 593 |
+
except Exception as e:
|
| 594 |
+
print(f"❌ Failed to process tracking video: {e}")
|
| 595 |
+
local_video_path = None
|
| 596 |
+
else:
|
| 597 |
+
print("⚠️ No tracking video content received from backend")
|
| 598 |
+
|
| 599 |
+
# 返回iframe HTML、视频路径和HTML文件路径(用于下载)
|
| 600 |
+
return iframe_html, local_video_path, random_path
|
| 601 |
+
else:
|
| 602 |
+
error_msg = result.get("error", "Unknown error") if isinstance(result, dict) else "Backend processing failed"
|
| 603 |
+
print(f"❌ Backend processing failed: {error_msg}")
|
| 604 |
+
# Fall through to error message
|
| 605 |
+
pass
|
| 606 |
+
except Exception as e:
|
| 607 |
+
print(f"❌ Backend API call failed: {e}")
|
| 608 |
+
print(f"🔧 Error type: {type(e)}")
|
| 609 |
+
print(f"🔧 Error details: {str(e)}")
|
| 610 |
+
|
| 611 |
+
# Check for specific gradio_client errors
|
| 612 |
+
if "AppError" in str(type(e)):
|
| 613 |
+
print("🔧 Backend Space has internal errors (AppError)")
|
| 614 |
+
print("🔧 The backend Space code has bugs or configuration issues")
|
| 615 |
+
print("🔧 Contact the Space owner to fix the backend implementation")
|
| 616 |
+
elif "Could not fetch config" in str(e):
|
| 617 |
+
print("🔧 Config fetch failed - possible Gradio version mismatch")
|
| 618 |
+
print("🔧 Frontend and backend may be using incompatible Gradio versions")
|
| 619 |
+
elif "timeout" in str(e).lower():
|
| 620 |
+
print("🔧 Backend request timed out - Space might be overloaded")
|
| 621 |
+
elif "Expecting value" in str(e):
|
| 622 |
+
print("🔧 JSON parsing error in backend - state format mismatch")
|
| 623 |
+
print("🔧 This happens when using local processing state with backend API")
|
| 624 |
+
print("🔧 Please upload video again to use backend processing")
|
| 625 |
+
else:
|
| 626 |
+
print(f"🔧 Unexpected error type: {type(e).__name__}")
|
| 627 |
+
|
| 628 |
+
print("🔄 Showing error message instead of visualization...")
|
| 629 |
+
# Fall through to error message
|
| 630 |
+
pass
|
| 631 |
+
|
| 632 |
+
# Create an informative error message based on the state
|
| 633 |
+
state_info = ""
|
| 634 |
+
try:
|
| 635 |
+
if isinstance(original_image_state, str):
|
| 636 |
+
parsed_state = json.loads(original_image_state)
|
| 637 |
+
if "video_path" in parsed_state:
|
| 638 |
+
video_name = os.path.basename(parsed_state["video_path"])
|
| 639 |
+
state_info = f"Video: {video_name}"
|
| 640 |
+
except:
|
| 641 |
+
state_info = "State format unknown"
|
| 642 |
+
|
| 643 |
+
# Fallback: show message that backend is required
|
| 644 |
+
error_message = f"""
|
| 645 |
+
<div style='border: 3px solid #ff6b6b; border-radius: 10px; padding: 20px; background-color: #fff5f5;'>
|
| 646 |
+
<h3 style='color: #d63031; margin-bottom: 15px;'>⚠️ Backend Processing Required</h3>
|
| 647 |
+
<p style='color: #2d3436; line-height: 1.6;'>
|
| 648 |
+
The tracking and visualization features require backend processing. The current setup is using local processing which is incompatible with the backend API.
|
| 649 |
+
</p>
|
| 650 |
+
<h4 style='color: #d63031; margin: 15px 0 10px 0;'>Solutions:</h4>
|
| 651 |
+
<ul style='color: #2d3436; line-height: 1.6;'>
|
| 652 |
+
<li><strong>Upload video again:</strong> This will properly initialize the backend state</li>
|
| 653 |
+
<li><strong>Select points on the frame:</strong> Ensure you've clicked on the object to track</li>
|
| 654 |
+
<li><strong>Check backend connection:</strong> Ensure the backend Space is running</li>
|
| 655 |
+
<li><strong>Use compatible state:</strong> Avoid local processing mode</li>
|
| 656 |
+
</ul>
|
| 657 |
+
<div style='background-color: #f8f9fa; border-radius: 5px; padding: 10px; margin-top: 15px;'>
|
| 658 |
+
<p style='color: #2d3436; font-weight: bold; margin: 0 0 5px 0;'>Debug Information:</p>
|
| 659 |
+
<p style='color: #666; font-size: 12px; margin: 0;'>Backend Available: {BACKEND_AVAILABLE}</p>
|
| 660 |
+
<p style='color: #666; font-size: 12px; margin: 0;'>Backend Client: {backend_client is not None}</p>
|
| 661 |
+
<p style='color: #666; font-size: 12px; margin: 0;'>Backend URL: {BACKEND_SPACE_URL}</p>
|
| 662 |
+
<p style='color: #666; font-size: 12px; margin: 0;'>State Info: {state_info}</p>
|
| 663 |
+
<p style='color: #666; font-size: 12px; margin: 0;'>Processing Mode: {"Backend" if BACKEND_AVAILABLE else "Local (Limited)"}</p>
|
| 664 |
+
</div>
|
| 665 |
+
<div style='background-color: #e3f2fd; border-radius: 5px; padding: 10px; margin-top: 10px; border-left: 4px solid #2196f3;'>
|
| 666 |
+
<p style='color: #1976d2; font-weight: bold; margin: 0 0 5px 0;'>💡 Quick Fix:</p>
|
| 667 |
+
<p style='color: #1976d2; font-size: 13px; margin: 0;'>
|
| 668 |
+
Try uploading your video again - this should properly initialize the backend state for tracking.
|
| 669 |
+
</p>
|
| 670 |
+
</div>
|
| 671 |
+
</div>
|
| 672 |
+
"""
|
| 673 |
+
return error_message, None, None
|
| 674 |
+
|
| 675 |
+
except Exception as e:
|
| 676 |
+
print(f"Error in launch_viz: {e}")
|
| 677 |
+
return None, None, None
|
| 678 |
+
|
| 679 |
+
def clear_all():
|
| 680 |
+
"""Clear all buffers and temporary files"""
|
| 681 |
+
return (None, None, [],
|
| 682 |
+
gr.update(value=50),
|
| 683 |
+
gr.update(value=756),
|
| 684 |
+
gr.update(value=3))
|
| 685 |
+
|
| 686 |
+
def clear_all_with_download():
|
| 687 |
+
"""Clear all buffers including download component"""
|
| 688 |
+
return (None, None, [],
|
| 689 |
+
gr.update(value=50),
|
| 690 |
+
gr.update(value=756),
|
| 691 |
+
gr.update(value=3),
|
| 692 |
+
None) # HTML download component
|
| 693 |
+
|
| 694 |
+
def update_tracker_model(model_name):
|
| 695 |
+
"""Update tracker model (placeholder function)"""
|
| 696 |
+
return
|
| 697 |
+
|
| 698 |
+
def get_video_settings(video_name):
|
| 699 |
+
"""Get video-specific settings based on video name"""
|
| 700 |
+
video_settings = {
|
| 701 |
+
"kiss": (45, 700, 10),
|
| 702 |
+
"backpack": (40, 600, 2),
|
| 703 |
+
"kitchen": (60, 800, 3),
|
| 704 |
+
"pillow": (35, 500, 2),
|
| 705 |
+
"handwave": (35, 500, 8),
|
| 706 |
+
"hockey": (45, 700, 2),
|
| 707 |
+
"drifting": (35, 1000, 6),
|
| 708 |
+
"basketball": (45, 1500, 5),
|
| 709 |
+
"ken_block_0": (45, 700, 2),
|
| 710 |
+
"ego_kc1": (45, 500, 4),
|
| 711 |
+
"vertical_place": (45, 500, 3),
|
| 712 |
+
"ego_teaser": (45, 1200, 10),
|
| 713 |
+
"robot_unitree": (45, 500, 4),
|
| 714 |
+
"robot_3": (35, 400, 5),
|
| 715 |
+
"teleop2": (45, 256, 7),
|
| 716 |
+
"pusht": (45, 256, 10),
|
| 717 |
+
"cinema_0": (45, 356, 5),
|
| 718 |
+
"cinema_1": (45, 756, 3),
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
return video_settings.get(video_name, (50, 756, 3))
|
| 722 |
+
|
| 723 |
+
def test_backend_connection():
|
| 724 |
+
"""Test if backend is actually working"""
|
| 725 |
+
global BACKEND_AVAILABLE
|
| 726 |
+
if not backend_client:
|
| 727 |
+
return False
|
| 728 |
+
|
| 729 |
+
try:
|
| 730 |
+
print("Testing backend connection with a simple call...")
|
| 731 |
+
# Check if we have fns available
|
| 732 |
+
if hasattr(backend_client, 'fns') and backend_client.fns:
|
| 733 |
+
print("✅ Backend API functions are available")
|
| 734 |
+
print(f"🔧 Available function indices: {list(backend_client.fns.keys())}")
|
| 735 |
+
return True
|
| 736 |
+
else:
|
| 737 |
+
print("❌ Backend API functions not found")
|
| 738 |
+
return False
|
| 739 |
+
except Exception as e:
|
| 740 |
+
print(f"❌ Backend connection test failed: {e}")
|
| 741 |
+
return False
|
| 742 |
+
|
| 743 |
+
def test_backend_api():
|
| 744 |
+
"""Test specific backend API functions"""
|
| 745 |
+
if not BACKEND_AVAILABLE or not backend_client:
|
| 746 |
+
print("❌ Backend not available for testing")
|
| 747 |
+
return False
|
| 748 |
+
|
| 749 |
+
try:
|
| 750 |
+
print("🧪 Testing backend API functions...")
|
| 751 |
+
|
| 752 |
+
# Test if fns exist and show available indices
|
| 753 |
+
if hasattr(backend_client, 'fns') and backend_client.fns:
|
| 754 |
+
print(f"✅ Backend has {len(backend_client.fns)} functions available")
|
| 755 |
+
for idx in backend_client.fns.keys():
|
| 756 |
+
print(f"✅ Function {idx} is available")
|
| 757 |
+
else:
|
| 758 |
+
print("❌ No functions found in backend API")
|
| 759 |
+
return False
|
| 760 |
+
|
| 761 |
+
return True
|
| 762 |
+
|
| 763 |
+
except Exception as e:
|
| 764 |
+
print(f"❌ Backend API test failed: {e}")
|
| 765 |
+
return False
|
| 766 |
+
|
| 767 |
+
# Initialize the backend connection
|
| 768 |
+
print("🚀 Initializing frontend application...")
|
| 769 |
+
result = initialize_backend()
|
| 770 |
+
|
| 771 |
+
# Test backend connection if available
|
| 772 |
+
if result and BACKEND_AVAILABLE:
|
| 773 |
+
print("✅ Backend connection successful!")
|
| 774 |
+
else:
|
| 775 |
+
print("❌ Backend connection failed!")
|
| 776 |
+
|
| 777 |
+
# Create the Gradio interface
|
| 778 |
+
print("🎨 Creating Gradio interface...")
|
| 779 |
+
|
| 780 |
+
with gr.Blocks(
|
| 781 |
+
theme=gr.themes.Soft(),
|
| 782 |
+
title="SpatialTracker V2 - Frontend",
|
| 783 |
+
css="""
|
| 784 |
+
.gradio-container {
|
| 785 |
+
max-width: 1200px !important;
|
| 786 |
+
margin: auto !important;
|
| 787 |
+
}
|
| 788 |
+
.gr-button {
|
| 789 |
+
margin: 5px;
|
| 790 |
+
}
|
| 791 |
+
.gr-form {
|
| 792 |
+
background: white;
|
| 793 |
+
border-radius: 10px;
|
| 794 |
+
padding: 20px;
|
| 795 |
+
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
| 796 |
+
}
|
| 797 |
+
/* 固定视频上传组件高度 */
|
| 798 |
+
.gr-video {
|
| 799 |
+
height: 300px !important;
|
| 800 |
+
min-height: 300px !important;
|
| 801 |
+
max-height: 300px !important;
|
| 802 |
+
}
|
| 803 |
+
.gr-video video {
|
| 804 |
+
height: 260px !important;
|
| 805 |
+
max-height: 260px !important;
|
| 806 |
+
object-fit: contain !important;
|
| 807 |
+
background: #f8f9fa;
|
| 808 |
+
}
|
| 809 |
+
.gr-video .gr-video-player {
|
| 810 |
+
height: 260px !important;
|
| 811 |
+
max-height: 260px !important;
|
| 812 |
+
}
|
| 813 |
+
/* 水平滚动的示例视频样式 */
|
| 814 |
+
.example-videos .gr-examples {
|
| 815 |
+
overflow: visible !important;
|
| 816 |
+
}
|
| 817 |
+
.example-videos .gr-examples .gr-table-wrapper {
|
| 818 |
+
overflow-x: auto !important;
|
| 819 |
+
overflow-y: hidden !important;
|
| 820 |
+
scrollbar-width: thin;
|
| 821 |
+
scrollbar-color: #667eea #f1f1f1;
|
| 822 |
+
}
|
| 823 |
+
.example-videos .gr-examples .gr-table-wrapper::-webkit-scrollbar {
|
| 824 |
+
height: 8px;
|
| 825 |
+
}
|
| 826 |
+
.example-videos .gr-examples .gr-table-wrapper::-webkit-scrollbar-track {
|
| 827 |
+
background: #f1f1f1;
|
| 828 |
+
border-radius: 4px;
|
| 829 |
+
}
|
| 830 |
+
.example-videos .gr-examples .gr-table-wrapper::-webkit-scrollbar-thumb {
|
| 831 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 832 |
+
border-radius: 4px;
|
| 833 |
+
}
|
| 834 |
+
.example-videos .gr-examples .gr-table-wrapper::-webkit-scrollbar-thumb:hover {
|
| 835 |
+
background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
|
| 836 |
+
}
|
| 837 |
+
.example-videos .gr-examples .gr-table {
|
| 838 |
+
display: flex !important;
|
| 839 |
+
flex-wrap: nowrap !important;
|
| 840 |
+
min-width: max-content !important;
|
| 841 |
+
gap: 10px !important;
|
| 842 |
+
}
|
| 843 |
+
.example-videos .gr-examples .gr-table tbody {
|
| 844 |
+
display: flex !important;
|
| 845 |
+
flex-direction: row !important;
|
| 846 |
+
flex-wrap: nowrap !important;
|
| 847 |
+
gap: 10px !important;
|
| 848 |
+
}
|
| 849 |
+
.example-videos .gr-examples .gr-table tbody tr {
|
| 850 |
+
display: flex !important;
|
| 851 |
+
flex-direction: column !important;
|
| 852 |
+
min-width: 120px !important;
|
| 853 |
+
max-width: 120px !important;
|
| 854 |
+
margin: 0 !important;
|
| 855 |
+
background: white;
|
| 856 |
+
border-radius: 8px;
|
| 857 |
+
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
| 858 |
+
transition: all 0.3s ease;
|
| 859 |
+
cursor: pointer;
|
| 860 |
+
}
|
| 861 |
+
.example-videos .gr-examples .gr-table tbody tr:hover {
|
| 862 |
+
transform: translateY(-2px);
|
| 863 |
+
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
|
| 864 |
+
}
|
| 865 |
+
.example-videos .gr-examples .gr-table tbody tr td {
|
| 866 |
+
text-align: center !important;
|
| 867 |
+
padding: 8px !important;
|
| 868 |
+
border: none !important;
|
| 869 |
+
}
|
| 870 |
+
.example-videos .gr-examples .gr-table tbody tr td video {
|
| 871 |
+
border-radius: 6px !important;
|
| 872 |
+
width: 100% !important;
|
| 873 |
+
height: auto !important;
|
| 874 |
+
}
|
| 875 |
+
.example-videos .gr-examples .gr-table tbody tr td:last-child {
|
| 876 |
+
font-size: 12px !important;
|
| 877 |
+
font-weight: 500 !important;
|
| 878 |
+
color: #333 !important;
|
| 879 |
+
padding-top: 4px !important;
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
/* 新的水平滚动示例视频样式 */
|
| 883 |
+
.horizontal-examples .gr-examples {
|
| 884 |
+
overflow: visible !important;
|
| 885 |
+
}
|
| 886 |
+
.horizontal-examples .gr-examples .gr-table-wrapper {
|
| 887 |
+
overflow-x: auto !important;
|
| 888 |
+
overflow-y: hidden !important;
|
| 889 |
+
scrollbar-width: thin;
|
| 890 |
+
scrollbar-color: #667eea #f1f1f1;
|
| 891 |
+
padding: 10px 0;
|
| 892 |
+
}
|
| 893 |
+
.horizontal-examples .gr-examples .gr-table-wrapper::-webkit-scrollbar {
|
| 894 |
+
height: 8px;
|
| 895 |
+
}
|
| 896 |
+
.horizontal-examples .gr-examples .gr-table-wrapper::-webkit-scrollbar-track {
|
| 897 |
+
background: #f1f1f1;
|
| 898 |
+
border-radius: 4px;
|
| 899 |
+
}
|
| 900 |
+
.horizontal-examples .gr-examples .gr-table-wrapper::-webkit-scrollbar-thumb {
|
| 901 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 902 |
+
border-radius: 4px;
|
| 903 |
+
}
|
| 904 |
+
.horizontal-examples .gr-examples .gr-table-wrapper::-webkit-scrollbar-thumb:hover {
|
| 905 |
+
background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
|
| 906 |
+
}
|
| 907 |
+
.horizontal-examples .gr-examples .gr-table {
|
| 908 |
+
display: flex !important;
|
| 909 |
+
flex-wrap: nowrap !important;
|
| 910 |
+
min-width: max-content !important;
|
| 911 |
+
gap: 15px !important;
|
| 912 |
+
padding-bottom: 10px;
|
| 913 |
+
}
|
| 914 |
+
.horizontal-examples .gr-examples .gr-table tbody {
|
| 915 |
+
display: flex !important;
|
| 916 |
+
flex-direction: row !important;
|
| 917 |
+
flex-wrap: nowrap !important;
|
| 918 |
+
gap: 15px !important;
|
| 919 |
+
}
|
| 920 |
+
.horizontal-examples .gr-examples .gr-table tbody tr {
|
| 921 |
+
display: flex !important;
|
| 922 |
+
flex-direction: column !important;
|
| 923 |
+
min-width: 160px !important;
|
| 924 |
+
max-width: 160px !important;
|
| 925 |
+
margin: 0 !important;
|
| 926 |
+
background: white;
|
| 927 |
+
border-radius: 12px;
|
| 928 |
+
box-shadow: 0 3px 12px rgba(0,0,0,0.12);
|
| 929 |
+
transition: all 0.3s ease;
|
| 930 |
+
cursor: pointer;
|
| 931 |
+
overflow: hidden;
|
| 932 |
+
}
|
| 933 |
+
.horizontal-examples .gr-examples .gr-table tbody tr:hover {
|
| 934 |
+
transform: translateY(-4px);
|
| 935 |
+
box-shadow: 0 8px 20px rgba(102, 126, 234, 0.25);
|
| 936 |
+
}
|
| 937 |
+
.horizontal-examples .gr-examples .gr-table tbody tr td {
|
| 938 |
+
text-align: center !important;
|
| 939 |
+
padding: 0 !important;
|
| 940 |
+
border: none !important;
|
| 941 |
+
}
|
| 942 |
+
.horizontal-examples .gr-examples .gr-table tbody tr td:first-child {
|
| 943 |
+
padding: 0 !important;
|
| 944 |
+
}
|
| 945 |
+
.horizontal-examples .gr-examples .gr-table tbody tr td video {
|
| 946 |
+
border-radius: 8px 8px 0 0 !important;
|
| 947 |
+
width: 100% !important;
|
| 948 |
+
height: 90px !important;
|
| 949 |
+
object-fit: cover !important;
|
| 950 |
+
}
|
| 951 |
+
.horizontal-examples .gr-examples .gr-table tbody tr td:last-child {
|
| 952 |
+
font-size: 11px !important;
|
| 953 |
+
font-weight: 600 !important;
|
| 954 |
+
color: #333 !important;
|
| 955 |
+
padding: 8px 12px !important;
|
| 956 |
+
background: linear-gradient(135deg, #f8f9ff 0%, #e6f3ff 100%);
|
| 957 |
+
border-radius: 0 0 8px 8px;
|
| 958 |
+
}
|
| 959 |
+
"""
|
| 960 |
+
) as demo:
|
| 961 |
+
|
| 962 |
+
gr.Markdown("""
|
| 963 |
+
# 🎯 SpatialTracker V2 - Frontend Interface
|
| 964 |
+
|
| 965 |
+
Welcome to SpatialTracker V2! This interface allows you to track any pixels in 3D using our model.
|
| 966 |
+
|
| 967 |
+
**Instructions:**
|
| 968 |
+
1. Upload a video file or select from examples below
|
| 969 |
+
2. Click on the object you want to track in the first frame
|
| 970 |
+
3. Adjust tracking parameters if needed
|
| 971 |
+
4. Click "Launch Visualization" to start tracking
|
| 972 |
+
|
| 973 |
+
""")
|
| 974 |
+
|
| 975 |
+
# Status indicator with more detailed information
|
| 976 |
+
if BACKEND_AVAILABLE:
|
| 977 |
+
status_text = "🟢 Backend Connected"
|
| 978 |
+
status_details = f"Connected to: {BACKEND_SPACE_URL}"
|
| 979 |
+
else:
|
| 980 |
+
status_text = "🟡 Running in Standalone Mode"
|
| 981 |
+
status_details = f"Backend unavailable: {BACKEND_SPACE_URL}"
|
| 982 |
+
|
| 983 |
+
gr.Markdown(f"**Status:** {status_text}")
|
| 984 |
+
gr.Markdown(f"<small style='color: #666;'>{status_details}</small>", elem_id="status-details")
|
| 985 |
+
|
| 986 |
+
# Example videos section - moved to top
|
| 987 |
+
with gr.Group(elem_classes=["example-videos"]):
|
| 988 |
+
gr.Markdown("### 📂 Example Videos")
|
| 989 |
+
gr.Markdown("Try these example videos to get started quickly:")
|
| 990 |
+
|
| 991 |
+
# Custom horizontal scrolling video gallery
|
| 992 |
+
gr.HTML("""
|
| 993 |
+
<div style='background-color: #f8f9ff; border-radius: 8px; padding: 10px; margin: 10px 0; border-left: 4px solid #667eea;'>
|
| 994 |
+
<p style='margin: 0; font-size: 13px; color: #666; display: flex; align-items: center; gap: 8px;'>
|
| 995 |
+
<span style='font-size: 16px;'>💡</span>
|
| 996 |
+
<strong>Tip:</strong> Scroll horizontally below to see all example videos
|
| 997 |
+
</p>
|
| 998 |
+
</div>
|
| 999 |
+
""")
|
| 1000 |
+
|
| 1001 |
+
# Define video_input here so it can be referenced in examples
|
| 1002 |
+
video_input = gr.Video(
|
| 1003 |
+
label="Upload Video or Select Example",
|
| 1004 |
+
format="mp4",
|
| 1005 |
+
height=300
|
| 1006 |
+
)
|
| 1007 |
+
|
| 1008 |
+
# Create a horizontal scrolling container for the examples
|
| 1009 |
+
with gr.Group(elem_classes=["horizontal-examples"]):
|
| 1010 |
+
gr.Examples(
|
| 1011 |
+
examples=[
|
| 1012 |
+
["examples/kiss.mp4"],
|
| 1013 |
+
["examples/backpack.mp4"],
|
| 1014 |
+
["examples/pillow.mp4"],
|
| 1015 |
+
["examples/handwave.mp4"],
|
| 1016 |
+
["examples/hockey.mp4"],
|
| 1017 |
+
["examples/drifting.mp4"],
|
| 1018 |
+
["examples/ken_block_0.mp4"],
|
| 1019 |
+
["examples/kitchen.mp4"],
|
| 1020 |
+
["examples/basketball.mp4"],
|
| 1021 |
+
["examples/ego_kc1.mp4"],
|
| 1022 |
+
["examples/vertical_place.mp4"],
|
| 1023 |
+
["examples/ego_teaser.mp4"],
|
| 1024 |
+
["examples/robot_unitree.mp4"],
|
| 1025 |
+
["examples/robot_3.mp4"],
|
| 1026 |
+
["examples/teleop2.mp4"],
|
| 1027 |
+
["examples/pusht.mp4"],
|
| 1028 |
+
["examples/cinema_0.mp4"],
|
| 1029 |
+
["examples/cinema_1.mp4"],
|
| 1030 |
+
],
|
| 1031 |
+
inputs=video_input,
|
| 1032 |
+
label="🎬 Click on any example to load it",
|
| 1033 |
+
examples_per_page=16
|
| 1034 |
+
)
|
| 1035 |
+
|
| 1036 |
+
with gr.Row():
|
| 1037 |
+
with gr.Column(scale=1):
|
| 1038 |
+
# Interactive frame display
|
| 1039 |
+
with gr.Group():
|
| 1040 |
+
gr.Markdown("### 🎯 Point Selection")
|
| 1041 |
+
gr.Markdown("Click on the object you want to track in the frame below:")
|
| 1042 |
+
|
| 1043 |
+
interactive_frame = gr.Image(
|
| 1044 |
+
label="Click to select tracking points",
|
| 1045 |
+
type="numpy",
|
| 1046 |
+
interactive=True
|
| 1047 |
+
)
|
| 1048 |
+
|
| 1049 |
+
with gr.Row():
|
| 1050 |
+
point_type = gr.Radio(
|
| 1051 |
+
choices=["positive_point", "negative_point"],
|
| 1052 |
+
value="positive_point",
|
| 1053 |
+
label="Point Type",
|
| 1054 |
+
info="Positive points indicate the object to track, negative points indicate areas to avoid"
|
| 1055 |
+
)
|
| 1056 |
+
|
| 1057 |
+
with gr.Row():
|
| 1058 |
+
reset_points_btn = gr.Button("🔄 Reset Points", variant="secondary")
|
| 1059 |
+
clear_all_btn = gr.Button("🗑️ Clear All", variant="stop")
|
| 1060 |
+
|
| 1061 |
+
with gr.Column(scale=1):
|
| 1062 |
+
# Tracking results
|
| 1063 |
+
with gr.Group():
|
| 1064 |
+
gr.Markdown("### 🎬 Tracking Results")
|
| 1065 |
+
tracking_result_video = gr.Video(
|
| 1066 |
+
label="Tracking Result Video",
|
| 1067 |
+
interactive=False,
|
| 1068 |
+
height=300
|
| 1069 |
+
)
|
| 1070 |
+
|
| 1071 |
+
# HTML文件下载组件
|
| 1072 |
+
html_download = gr.File(
|
| 1073 |
+
label="📥 Download 3D Visualization HTML",
|
| 1074 |
+
interactive=False,
|
| 1075 |
+
visible=True
|
| 1076 |
+
)
|
| 1077 |
+
|
| 1078 |
+
# Advanced settings section - changed to open=True
|
| 1079 |
+
with gr.Accordion("⚙️ Advanced Settings", open=True):
|
| 1080 |
+
gr.Markdown("Adjust these parameters to optimize tracking performance:")
|
| 1081 |
+
with gr.Row():
|
| 1082 |
+
grid_size = gr.Slider(
|
| 1083 |
+
minimum=10,
|
| 1084 |
+
maximum=100,
|
| 1085 |
+
step=10,
|
| 1086 |
+
value=50,
|
| 1087 |
+
label="Grid Size",
|
| 1088 |
+
info="Size of the tracking grid (larger = more detailed)"
|
| 1089 |
+
)
|
| 1090 |
+
vo_points = gr.Slider(
|
| 1091 |
+
minimum=100,
|
| 1092 |
+
maximum=2000,
|
| 1093 |
+
step=50,
|
| 1094 |
+
value=756,
|
| 1095 |
+
label="VO Points",
|
| 1096 |
+
info="Number of visual odometry points (more = better accuracy)"
|
| 1097 |
+
)
|
| 1098 |
+
fps = gr.Slider(
|
| 1099 |
+
minimum=1,
|
| 1100 |
+
maximum=30,
|
| 1101 |
+
step=1,
|
| 1102 |
+
value=3,
|
| 1103 |
+
label="FPS",
|
| 1104 |
+
info="Frames per second for processing (higher = smoother but slower)"
|
| 1105 |
+
)
|
| 1106 |
+
|
| 1107 |
+
# Launch button
|
| 1108 |
+
with gr.Row():
|
| 1109 |
+
launch_btn = gr.Button("🚀 Start Tracking Now!", variant="primary", size="lg")
|
| 1110 |
+
|
| 1111 |
+
# 3D Visualization - Make it larger and more prominent
|
| 1112 |
+
with gr.Row():
|
| 1113 |
+
with gr.Column():
|
| 1114 |
+
with gr.Group():
|
| 1115 |
+
gr.Markdown("### 🌐 3D Trajectory Visualization")
|
| 1116 |
+
gr.Markdown("Interactive 3D visualization of 3D point tracking and camera motion:")
|
| 1117 |
+
viz_html = gr.HTML(
|
| 1118 |
+
label="3D Trajectory Visualization",
|
| 1119 |
+
value="""
|
| 1120 |
+
<div style='border: 3px solid #667eea; border-radius: 15px; padding: 40px;
|
| 1121 |
+
background: linear-gradient(135deg, #f8f9ff 0%, #e6f3ff 100%);
|
| 1122 |
+
text-align: center; min-height: 600px; display: flex;
|
| 1123 |
+
flex-direction: column; justify-content: center; align-items: center;
|
| 1124 |
+
box-shadow: 0 8px 32px rgba(102, 126, 234, 0.2);'>
|
| 1125 |
+
<div style='font-size: 48px; margin-bottom: 20px;'>🌐</div>
|
| 1126 |
+
<h2 style='color: #667eea; margin-bottom: 15px; font-size: 28px; font-weight: 600;'>
|
| 1127 |
+
3D Trajectory Visualization
|
| 1128 |
+
</h2>
|
| 1129 |
+
<p style='color: #666; font-size: 16px; line-height: 1.6; max-width: 500px; margin-bottom: 25px;'>
|
| 1130 |
+
Perceive the world with Pixel-wise 3D Motions!
|
| 1131 |
+
</p>
|
| 1132 |
+
<div style='background: rgba(102, 126, 234, 0.1); border-radius: 25px;
|
| 1133 |
+
padding: 12px 24px; border: 2px solid rgba(102, 126, 234, 0.2);'>
|
| 1134 |
+
<span style='color: #667eea; font-weight: 600; font-size: 14px;'>
|
| 1135 |
+
⚡ Powered by SpatialTracker V2
|
| 1136 |
+
</span>
|
| 1137 |
+
</div>
|
| 1138 |
+
</div>
|
| 1139 |
+
""",
|
| 1140 |
+
elem_id="viz_container"
|
| 1141 |
+
)
|
| 1142 |
+
|
| 1143 |
+
# Hidden state variables
|
| 1144 |
+
original_image_state = gr.State(None)
|
| 1145 |
+
selected_points = gr.State([])
|
| 1146 |
+
|
| 1147 |
+
# Event handlers
|
| 1148 |
+
video_input.change(
|
| 1149 |
+
fn=handle_video_upload,
|
| 1150 |
+
inputs=[video_input],
|
| 1151 |
+
outputs=[original_image_state, interactive_frame, selected_points, grid_size, vo_points, fps]
|
| 1152 |
+
)
|
| 1153 |
+
|
| 1154 |
+
interactive_frame.select(
|
| 1155 |
+
fn=select_point,
|
| 1156 |
+
inputs=[original_image_state, selected_points, point_type],
|
| 1157 |
+
outputs=[interactive_frame, selected_points]
|
| 1158 |
+
)
|
| 1159 |
+
|
| 1160 |
+
reset_points_btn.click(
|
| 1161 |
+
fn=reset_points,
|
| 1162 |
+
inputs=[original_image_state, selected_points],
|
| 1163 |
+
outputs=[interactive_frame, selected_points]
|
| 1164 |
+
)
|
| 1165 |
+
|
| 1166 |
+
clear_all_btn.click(
|
| 1167 |
+
fn=clear_all_with_download,
|
| 1168 |
+
outputs=[video_input, interactive_frame, selected_points, grid_size, vo_points, fps, html_download]
|
| 1169 |
+
)
|
| 1170 |
+
|
| 1171 |
+
launch_btn.click(
|
| 1172 |
+
fn=launch_viz,
|
| 1173 |
+
inputs=[grid_size, vo_points, fps, original_image_state],
|
| 1174 |
+
outputs=[viz_html, tracking_result_video, html_download]
|
| 1175 |
+
)
|
| 1176 |
+
|
| 1177 |
+
# GitHub Star Reminder - Added back!
|
| 1178 |
+
gr.HTML("""
|
| 1179 |
+
<div style='background: linear-gradient(135deg, #e8eaff 0%, #f0f2ff 100%);
|
| 1180 |
+
border-radius: 10px;
|
| 1181 |
+
padding: 15px;
|
| 1182 |
+
margin: 15px 0;
|
| 1183 |
+
box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
|
| 1184 |
+
border: 1px solid rgba(102, 126, 234, 0.15);'>
|
| 1185 |
+
<div style='text-align: center; color: #4a5568;'>
|
| 1186 |
+
<h3 style='margin: 0 0 10px 0; font-size: 18px; text-shadow: none; color: #2d3748;'>
|
| 1187 |
+
⭐ Love SpatialTracker? Give us a Star! ⭐
|
| 1188 |
+
</h3>
|
| 1189 |
+
<p style='margin: 0 0 12px 0; font-size: 14px; opacity: 0.8; color: #4a5568;'>
|
| 1190 |
+
Help us grow by starring our repository on GitHub! 🚀
|
| 1191 |
+
</p>
|
| 1192 |
+
<div style='display: flex; justify-content: center;'>
|
| 1193 |
+
<a href="https://github.com/henry123-boy/SpaTrackerV2"
|
| 1194 |
+
target="_blank"
|
| 1195 |
+
style='display: inline-flex;
|
| 1196 |
+
align-items: center;
|
| 1197 |
+
gap: 6px;
|
| 1198 |
+
background: rgba(102, 126, 234, 0.1);
|
| 1199 |
+
color: #4a5568;
|
| 1200 |
+
padding: 8px 16px;
|
| 1201 |
+
border-radius: 20px;
|
| 1202 |
+
text-decoration: none;
|
| 1203 |
+
font-weight: bold;
|
| 1204 |
+
font-size: 14px;
|
| 1205 |
+
backdrop-filter: blur(5px);
|
| 1206 |
+
border: 1px solid rgba(102, 126, 234, 0.2);
|
| 1207 |
+
transition: all 0.3s ease;'
|
| 1208 |
+
onmouseover="this.style.background='rgba(102, 126, 234, 0.15)'; this.style.transform='translateY(-1px)'"
|
| 1209 |
+
onmouseout="this.style.background='rgba(102, 126, 234, 0.1)'; this.style.transform='translateY(0)'">
|
| 1210 |
+
<span style='font-size: 16px;'>⭐</span>
|
| 1211 |
+
Star on GitHub
|
| 1212 |
+
</a>
|
| 1213 |
+
</div>
|
| 1214 |
+
</div>
|
| 1215 |
+
</div>
|
| 1216 |
+
""")
|
| 1217 |
+
|
| 1218 |
+
# Acknowledgment section for TAPIR3D - moved to the end
|
| 1219 |
+
gr.HTML("""
|
| 1220 |
+
<div style='background: linear-gradient(135deg, #fff8e1 0%, #fffbf0 100%);
|
| 1221 |
+
border-radius: 8px;
|
| 1222 |
+
padding: 12px;
|
| 1223 |
+
margin: 15px 0;
|
| 1224 |
+
box-shadow: 0 1px 4px rgba(255, 193, 7, 0.1);
|
| 1225 |
+
border: 1px solid rgba(255, 193, 7, 0.2);'>
|
| 1226 |
+
<div style='text-align: center; color: #5d4037;'>
|
| 1227 |
+
<h5 style='margin: 0 0 6px 0; font-size: 14px; color: #5d4037;'>
|
| 1228 |
+
Acknowledgments
|
| 1229 |
+
</h5>
|
| 1230 |
+
<p style='margin: 0; font-size: 12px; opacity: 0.9; color: #5d4037; line-height: 1.3;'>
|
| 1231 |
+
Our 3D visualizer is adapted from <strong>TAPIP3D</strong>. We thank the authors for their excellent work!
|
| 1232 |
+
</p>
|
| 1233 |
+
<div style='margin-top: 6px;'>
|
| 1234 |
+
<a href="https://github.com/zbw001/TAPIP3D"
|
| 1235 |
+
target="_blank"
|
| 1236 |
+
style='display: inline-flex;
|
| 1237 |
+
align-items: center;
|
| 1238 |
+
gap: 3px;
|
| 1239 |
+
background: rgba(255, 193, 7, 0.15);
|
| 1240 |
+
color: #5d4037;
|
| 1241 |
+
padding: 3px 10px;
|
| 1242 |
+
border-radius: 12px;
|
| 1243 |
+
text-decoration: none;
|
| 1244 |
+
font-weight: 500;
|
| 1245 |
+
font-size: 11px;
|
| 1246 |
+
border: 1px solid rgba(255, 193, 7, 0.3);
|
| 1247 |
+
transition: all 0.3s ease;'
|
| 1248 |
+
onmouseover="this.style.background='rgba(255, 193, 7, 0.2)'"
|
| 1249 |
+
onmouseout="this.style.background='rgba(255, 193, 7, 0.15)'">
|
| 1250 |
+
📚 TAPIP3D Repository
|
| 1251 |
+
</a>
|
| 1252 |
+
</div>
|
| 1253 |
+
</div>
|
| 1254 |
+
</div>
|
| 1255 |
+
""")
|
| 1256 |
+
|
| 1257 |
+
# Launch the interface
|
| 1258 |
+
if __name__ == "__main__":
|
| 1259 |
+
print("🌟 Launching SpatialTracker V2 Frontend...")
|
| 1260 |
+
print(f"🔗 Backend Status: {'Connected' if BACKEND_AVAILABLE else 'Disconnected'}")
|
| 1261 |
+
|
| 1262 |
+
demo.launch(
|
| 1263 |
+
server_name="0.0.0.0",
|
| 1264 |
+
server_port=7860,
|
| 1265 |
+
share=True,
|
| 1266 |
+
debug=True,
|
| 1267 |
+
show_error=True
|
| 1268 |
+
)
|