Spaces:
Configuration error
Configuration error
Update app.py
Browse files13 unmodified lines141516171718192010 unmodified lines313233343435363712 unmodified lines50515253535455565 unmodified lines626364656566676867686970717273737475767737 unmodified lines11511611711711811912012136 unmodified lines15815916016016116216316469 unmodified lines23423523623623723723823924024115 unmodified lines2572582592592602602612622632646 unmodified lines27127227327327427527627720 unmodified lines29829930030030130230330423 unmodified lines32832933033133233333413 unmodified lines34834935034935135135235235335435435535635735835535635735835936036136236336436536636736836937037137213 unmodified linesfrom ultralytics import YOLO
# ==========================================
# 讞讬砖讜讘 谞转讬讘讬诐 诪讜讞诇讟讬诐
# 1. 讞讬砖讜讘 谞转讬讘讬诐 诪讜讞诇讟讬诐
# ==========================================
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_MODEL_PATH = os.path.join(BASE_DIR, 'best.pt')10 unmodified linessocketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')
# ==========================================
# 讟注讬谞转 TrOCR 讬爪讬讘讛
# 2. 讟注讬谞转 TrOCR
# ==========================================
trocr_available = False
processor = None12 unmodified lines print(f"鈿狅笍 讗讝讛专讛: TrOCR 诇讗 谞讟注谉. 砖讙讬讗讛: {e}")
# ==========================================
# 诪讞诇拽转 讟专谞住驻讜专诪爪讬讛 (讻讬讜诇)
# 3. 诪讞诇拽转 讻讬讜诇 讛讜诪讜讙专驻讬讛 (注诐 谞专诪讜诇)
# ==========================================
class HomographyTransformer:
def __init__(self):5 unmodified lines dst = np.array(dst_pts, dtype=np.float32)
self.H, _ = cv2.findHomography(src, dst)
def transform_point(self, x, y):
def transform_point(self, norm_x, norm_y):
if self.H is None:
return x, y
pt = np.array([[[x, y]]], dtype=np.float32)
# 讗诐 讗讬谉 讻讬讜诇, 诪讞讝讬专 注专讻讬诐 讘专讬专转 诪讞讚诇
return norm_x * 600, norm_y * 400
pt = np.array([[[norm_x, norm_y]]], dtype=np.float32)
transformed = cv2.perspectiveTransform(pt, self.H)
return float(transformed[0][0][0]), float(transformed[0][0][1])
# ==========================================
# 诪谞讜注 讛注讬讘讜讚 讛专讗砖讬
# 4. 诪谞讜注 注讬讘讜讚 讛住讟专讬诐 讜讛-AI
# ==========================================
class TrOCRStreamEngine:
def __init__(self):37 unmodified lines
stream_url = url_or_path
if "youtube.com" in url_or_path or "youtu.be" in url_or_path:
ydl_opts = {'format': 'best[ext=mp4]', 'quiet': True}
ydl_opts = {'format': 'best[ext=mp4]/best', 'quiet': True}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url_or_path, download=False)
stream_url = info['url']36 unmodified lines time.sleep(0.01)
continue
# --- Frame Skipping: 注讬讘讜讚 讻诇 驻专讬讬诐 砖诇讬砖讬 诇诪谞讬注转 注讜诪住 讜讚讬诇讬讬 ---
# Frame Skipping 诇注讘讜讚讛 讞诇拽讛 讘-CPU
frame_counter += 1
if frame_counter % 3 != 0:
time.sleep(0.01)69 unmodified lines pass
else:
team_number = str(self.robot_team_cache.get(track_id, f"Robot-{track_id}" if track_id else "Robot"))
bot_x = float((x1 + x2) / 2.0)
bot_y = float(y2)
bot_x = float((x1 + x2) / 2.0) / width
bot_y = float(y2) / height
real_map_x, real_map_y = self.homography.transform_point(bot_x, bot_y)
15 unmodified lines b_cls_name = str(self.ball_model.names.get(b_cls_id, f"Class_{b_cls_id}")).lower()
if b_cls_name == 'fuel':
ball_center_x = float((bx1 + bx2) / 2.0)
ball_center_y = float((by1 + by2) / 2.0)
ball_center_x = float((bx1 + bx2) / 2.0) / width
ball_center_y = float((by1 + by2) / 2.0) / height
map_ball_x, map_ball_y = self.homography.transform_point(ball_center_x, ball_center_y)
6 unmodified lines })
except Exception as e:
print(f"Error during processing loop: {e}")
print(f"Error in processing loop: {e}")
self.current_telemetry = telemetry
self.current_scores = {20 unmodified linesengine = TrOCRStreamEngine()
# ==========================================
# API Routes
# 5. API Routes
# ==========================================
@app.route('/')
def index():23 unmodified lines
return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/api/start_stream', methods=['POST'])
@app.route('/api/start', methods=['POST'])
def start():
data = request.json or {}13 unmodified lines
@app.route('/api/update_calibration', methods=['POST'])
def update_calibration():
"""转诪讬锟斤拷讛 讘专讬讘讜讬 驻讜专诪讟讬诐 砖诇 讻讬讜诇 诪讛-Frontend"""
data = request.json or {}
src_norm = data.get('src_norm') or data.get('video') or data.get('src', [])
dst_norm = data.get('dst_norm') or data.get('map') or data.get('dst', [])
video_pts = data.get('video') or data.get('src_norm') or data.get('src', [])
map_pts = data.get('map') or data.get('dst_norm') or data.get('dst', [])
# 讛诪专转 谞拽讜讚讜转 诪驻讜专诪讟 dict 讘诪讬讚转 讛爪讜专讱
if src_norm and isinstance(src_norm[0], dict):
src_norm = [[p['x'], p['y']] for p in src_norm]
if dst_norm and isinstance(dst_norm[0], dict):
dst_norm = [[p['x'], p['y']] for p in dst_norm]
# 谞专诪讜诇 谞拽讜讚讜转 讛讜讜讬讚讗讜 (诇注专讻讬诐 诪-0 注讚 1)
src_norm = []
for p in video_pts:
if isinstance(p, dict):
src_norm.append([p['x'] / 600.0, p['y'] / 400.0])
else:
src_norm.append([p[0] / 600.0, p[1] / 400.0])
# 谞拽讜讚讜转 讛诪驻讛
dst_norm = []
for p in map_pts:
if isinstance(p, dict):
dst_norm.append([p['x'], p['y']])
else:
dst_norm.append([p[0], p[1]])
engine.update_calibration(src_norm, dst_norm)
return jsonify({'status': 'success'})app.py+34-23