Spaces:
Configuration error
Configuration error
Update app.py
Browse files13 unmodified lines1415161718192010 unmodified lines3132333435363712 unmodified lines505152535455565 unmodified lines62636465666768697071727374757637 unmodified lines11411511611711811912036 unmodified lines15715815916016116216369 unmodified lines23323423523623723823924015 unmodified lines2562572582592602612622636 unmodified lines27027127227327427527620 unmodified lines29729829930030130230323 unmodified lines32732832933033133213 unmodified lines34634734834935035135235335435535635735835936036113 unmodified linesfrom ultralytics import YOLO# ==========================================# 讞讬砖讜讘 谞转讬讘讬诐 诪讜讞诇讟讬诐# ==========================================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 讬爪讬讘讛# ==========================================trocr_available = Falseprocessor = None12 unmodified linesprint(f"鈿狅笍 讗讝讛专讛: TrOCR 诇讗 谞讟注谉. 砖讙讬讗讛: {e}")# ==========================================# 诪讞诇拽转 讟专谞住驻讜专诪爪讬讛 (讻讬讜诇)# ==========================================class HomographyTransformer:def __init__(self):5 unmodified linesdst = np.array(dst_pts, dtype=np.float32)self.H, _ = cv2.findHomography(src, dst)def transform_point(self, x, y):if self.H is None:return x, ypt = np.array([[[x, y]]], dtype=np.float32)transformed = cv2.perspectiveTransform(pt, self.H)return float(transformed[0][0][0]), float(transformed[0][0][1])# ==========================================# 诪谞讜注 讛注讬讘讜讚 讛专讗砖讬# ==========================================class TrOCRStreamEngine:def __init__(self):37 unmodified linesstream_url = url_or_pathif "youtube.com" in url_or_path or "youtu.be" in url_or_path:ydl_opts = {'format': 'best[ext=mp4]', '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 linestime.sleep(0.01)continue# --- Frame Skipping: 注讬讘讜讚 讻诇 驻专讬讬诐 砖诇讬砖讬 诇诪谞讬注转 注讜诪住 讜讚讬诇讬讬 ---frame_counter += 1if frame_counter % 3 != 0:time.sleep(0.01)69 unmodified linespasselse: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)real_map_x, real_map_y = self.homography.transform_point(bot_x, bot_y)15 unmodified linesb_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)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}")self.current_telemetry = telemetryself.current_scores = {20 unmodified linesengine = TrOCRStreamEngine()# ==========================================# API Routes# ==========================================@app.route('/')def index():23 unmodified linesreturn Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')@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', [])# 讛诪专转 谞拽讜讚讜转 诪驻讜专诪讟 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]engine.update_calibration(src_norm, dst_norm)return jsonify({'status': 'success'})13 unmodified lines1415161718192010 unmodified lines3132333435363712 unmodified lines505152535455565 unmodified lines6263646566676869707172737475767737 unmodified lines11511611711811912012136 unmodified lines15815916016116216316469 unmodified lines23423523623723823924024115 unmodified lines2572582592602612622632646 unmodified lines27127227327427527627720 unmodified lines29829930030130230330423 unmodified lines32832933033133233333413 unmodified lines34834935035135235335435535635735835936036136236336436536636736836937037137213 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')# ==========================================# 2. 讟注讬谞转 TrOCR# ==========================================trocr_available = Falseprocessor = None12 unmodified linesprint(f"鈿狅笍 讗讝讛专讛: TrOCR 诇讗 谞讟注谉. 砖讙讬讗讛: {e}")# ==========================================# 3. 诪讞诇拽转 讻讬讜诇 讛讜诪讜讙专驻讬讛 (注诐 谞专诪讜诇)# ==========================================class HomographyTransformer:def __init__(self):5 unmodified linesdst = np.array(dst_pts, dtype=np.float32)self.H, _ = cv2.findHomography(src, dst)def transform_point(self, norm_x, norm_y):if self.H is None:# 讗诐 讗讬谉 讻讬讜诇, 诪讞讝讬专 注专讻讬诐 讘专讬专转 诪讞讚诇return norm_x * 600, norm_y * 400pt = 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 linesstream_url = url_or_pathif "youtube.com" in url_or_path or "youtu.be" in url_or_path: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 linestime.sleep(0.01)continue# Frame Skipping 诇注讘讜讚讛 讞诇拽讛 讘-CPUframe_counter += 1if frame_counter % 3 != 0:time.sleep(0.01)69 unmodified linespasselse: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) / widthbot_y = float(y2) / heightreal_map_x, real_map_y = self.homography.transform_point(bot_x, bot_y)15 unmodified linesb_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) / widthball_center_y = float((by1 + by2) / 2.0) / heightmap_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 in processing loop: {e}")self.current_telemetry = telemetryself.current_scores = {20 unmodified linesengine = TrOCRStreamEngine()# ==========================================# 5. API Routes# ==========================================@app.route('/')def index():23 unmodified linesreturn 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():data = request.json or {}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', [])# 谞专诪讜诇 谞拽讜讚讜转 讛讜讜讬讚讗讜 (诇注专讻讬诐 诪-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