Spaces:
Sleeping
Sleeping
Update tools/youtube_species_tool.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071from langchain.tools import BaseToolimport cv2import tempfileimport osimport torchimport torchvision.transforms as Tfrom torchvision.models.detection import fasterrcnn_resnet50_fpnimport reimport yt_dlpclass YouTubeSpeciesTool(BaseTool):"""Инструмент для анализа видео YouTube: находит максимальное число птиц в кадре.Скачивает видео через yt-dlp и детектирует птиц Faster R-CNN."""name: str = "youtube_species"description: str = ("Скачивает видео по URL, детектирует птиц с помощью Faster R-CNN ""и возвращает максимальное число птиц в кадре.")def _run(self, text: str) -> str:# 1) Извлекаем URL из произвольного текстаm = re.search(r"(https?://[^\s,]+)", text)if not m:return "Ошибка: не найден корректный URL."url = m.group(1)# 2) Скачиваем видео через yt-dlptemp_dir = tempfile.mkdtemp()ydl_opts = {"outtmpl": os.path.join(temp_dir, "%(id)s.%(ext)s"),"format": "mp4",}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(url, download=True)video_path = os.path.join(temp_dir, f"{info['id']}.mp4")# 3) Готовим модельdevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")model = fasterrcnn_resnet50_fpn(pretrained=True).to(device)model.eval()transform = T.Compose([T.ToTensor()])# 4) Обрабатываем кадрыcap = cv2.VideoCapture(video_path)max_count = 0while True:ret, frame = cap.read()if not ret:breakimg = transform(frame).to(device)with torch.no_grad():out = model([img])[0]labels = out["labels"].cpu().numpy()# COCO class 15 = 'bird'count = int((labels == 15).sum())max_count = max(max_count, count)cap.release()# 5) Удаляем временные файлыos.remove(video_path)os.rmdir(temp_dir)return f"Максимальное число птиц в кадре: {max_count}"async def _arun(self, text: str) -> str:raise NotImplementedError("Async not supported.")123456789101112131415161718192021222324252627282930313233343536373839import osfrom langchain.tools import BaseToolfrom yt_dlp import YoutubeDLclass YouTubeSpeciesTool(BaseTool):"""Инструмент для подсчёта максимального числа видов птиц,появившихся одновременно в кадре YouTube-видео.Поддерживает передачу cookies для аутентификации на YouTube."""name: str = "youtube_species"description: str = ("Подсчитывает число видов птиц в видео; ""поддерживает cookies-файл через переменную YTDLP_COOKIES.")def _run(self, url: str) -> str:try:# Опции для yt-dlp: skip downloadydl_opts = {"quiet": True,"no_warnings": True,"skip_download": True}# Если указан файл cookies, добавляем для аутентификацииcookies = os.environ.get("YTDLP_COOKIES")if cookies:ydl_opts["cookiefile"] = cookieswith YoutubeDL(ydl_opts) as ydl:info = ydl.extract_info(url, download=False)# Здесь должна быть логика анализа кадров и подсчёта видов# Пока возвращаем placeholderreturn "Unable to count species: placeholder result"except Exception as e:return f"ERROR: Unable to process YouTube URL: {e}"async def _arun(self, url: str) -> str:raise NotImplementedError("Async not supported.")
tools/youtube_species_tool.py+39-71