Download annotations.py from ibmectech/minds-libras-raw: direct link, hf CLI and curl.
- Browser
- Download file 5.49 kB
-
https://huggingface.co/datasets/ibmectech/minds-libras-raw/resolve/main/annotations.py
- Command line
-
hf download hf://datasets/ibmectech/minds-libras-raw/annotations.py
-
curl -L -o annotations.py https://huggingface.co/datasets/ibmectech/minds-libras-raw/resolve/main/annotations.py
5.49 kB
| """ | |
| generate_annotations.py | |
| ======================= | |
| Gera o arquivo annotations.csv para o dataset minds-libras. | |
| Uso: | |
| python generate_annotations.py | |
| O script deve ser colocado na pasta PAI da pasta 'videos', ou seja: | |
| dataset/minds-libras/ | |
| generate_annotations.py <-- aqui | |
| annotations.csv <-- gerado aqui | |
| videos/ | |
| 01AcontecerSinalizador01-1.mp4 | |
| ... | |
| Dependências: | |
| - ffprobe (parte do ffmpeg): extrai width, height e fps reais de cada vídeo. | |
| Caso contrário, as colunas ficam como None. | |
| Ubuntu/Debian: sudo apt install ffmpeg | |
| macOS: brew install ffmpeg | |
| """ | |
| import os | |
| import re | |
| import csv | |
| import json | |
| import subprocess | |
| from pathlib import Path | |
| # --------------------------------------------------------------------------- | |
| # Configuração | |
| # --------------------------------------------------------------------------- | |
| SCRIPT_DIR = Path(__file__).parent.resolve() | |
| VIDEOS_DIR = SCRIPT_DIR / "videos" | |
| OUTPUT_CSV = SCRIPT_DIR / "annotations.csv" | |
| FILENAME_PATTERN = re.compile( | |
| r"^(?P<class_id>\d{2})(?P<class_name>[A-Za-záéíóúàâêôãõüçÁÉÍÓÚÀÂÊÔÃÕÜÇ]+)" | |
| r"Sinalizador(?P<user_id>\d{2})-(?P<rep>\d+)\.mp4$" | |
| ) | |
| def get_video_metadata(filepath: Path) -> dict: | |
| """Retorna width, height e frame_count via ffprobe. Retorna None em caso de erro.""" | |
| try: | |
| cmd = [ | |
| "ffprobe", "-v", "quiet", | |
| "-print_format", "json", | |
| "-select_streams", "v:0", | |
| "-show_streams", | |
| str(filepath) | |
| ] | |
| result = subprocess.run(cmd, capture_output=True, text=True, timeout=10) | |
| if result.returncode != 0: | |
| return {"width": None, "height": None, "fps": None} | |
| data = json.loads(result.stdout) | |
| stream = data.get("streams", [{}])[0] | |
| width = stream.get("width") | |
| height = stream.get("height") | |
| # fps: tenta nb_frames (contagem real), depois avg_frame_rate | |
| nb_frames = stream.get("nb_frames") | |
| if nb_frames and nb_frames != "N/A": | |
| fps = float(nb_frames) | |
| else: | |
| # avg_frame_rate vem como "30/1" ou "30000/1001" | |
| avg_fr = stream.get("avg_frame_rate", "0/1") | |
| num, den = avg_fr.split("/") | |
| fps = round(float(num) / float(den), 2) if float(den) != 0 else None | |
| return {"width": width, "height": height, "fps": fps} | |
| except (FileNotFoundError, subprocess.TimeoutExpired, Exception): | |
| return {"width": None, "height": None, "fps": None} | |
| def ffprobe_available() -> bool: | |
| try: | |
| subprocess.run(["ffprobe", "-version"], capture_output=True, timeout=5) | |
| return True | |
| except (FileNotFoundError, subprocess.TimeoutExpired): | |
| return False | |
| def main(): | |
| if not VIDEOS_DIR.exists(): | |
| raise FileNotFoundError(f"Pasta de vídeos não encontrada: {VIDEOS_DIR}") | |
| use_ffprobe = ffprobe_available() | |
| if use_ffprobe: | |
| print("ffprobe detectado — extraindo metadados reais dos vídeos.") | |
| else: | |
| print("ffprobe NÃO encontrado — colunas width/height/fps serão None.") | |
| print(" Para extrair metadados: sudo apt install ffmpeg (ou brew install ffmpeg)") | |
| # Coleta e ordena os arquivos | |
| mp4_files = sorted(VIDEOS_DIR.glob("*.mp4")) | |
| print(f"\nArquivos .mp4 encontrados: {len(mp4_files)}") | |
| rows = [] | |
| skipped = [] | |
| for filepath in mp4_files: | |
| filename = filepath.name | |
| m = FILENAME_PATTERN.match(filename) | |
| if not m: | |
| skipped.append(filename) | |
| continue | |
| class_name = m.group("class_name") | |
| user_id = f"Sinalizador{m.group('user_id')}" | |
| rep = m.group("rep") | |
| video_id = filename # usa o próprio filename como ID (análogo ao dataset original) | |
| video_name = f"{class_name}_{user_id}-{rep}.mp4" | |
| # Metadados do vídeo | |
| if use_ffprobe: | |
| meta = get_video_metadata(filepath) | |
| print(f" {filename} -> {meta}") | |
| else: | |
| meta = {"width": None, "height": None, "fps": None} | |
| rows.append({ | |
| "video_id": video_id, | |
| "video_name": video_name, | |
| "class": class_name, | |
| "user_id": user_id, | |
| "width": meta["width"], | |
| "height": meta["height"], | |
| "fps": meta["fps"], | |
| }) | |
| # Relatório de arquivos não reconhecidos | |
| if skipped: | |
| print(f"\n⚠️ {len(skipped)} arquivo(s) não reconhecido(s) pelo padrão e ignorado(s):") | |
| for s in skipped: | |
| print(f" {s}") | |
| # Escreve CSV | |
| fieldnames = ["video_id", "video_name", "class", "user_id", "width", "height", "fps"] | |
| with open(OUTPUT_CSV, "w", newline="", encoding="utf-8") as f: | |
| writer = csv.DictWriter(f, fieldnames=fieldnames) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| # Resumo | |
| classes = sorted(set(r["class"] for r in rows)) | |
| users = sorted(set(r["user_id"] for r in rows)) | |
| reps = sorted(set( | |
| re.search(r"-(\d+)\.mp4$", r["video_id"]).group(1) for r in rows | |
| )) | |
| print(f"\n✅ annotations.csv gerado em: {OUTPUT_CSV}") | |
| print(f" Total de linhas (vídeos): {len(rows)}") | |
| print(f" Classes ({len(classes)}): {classes}") | |
| print(f" Sinalizadores ({len(users)}): {users}") | |
| print(f" Repetições: {reps}") | |
| if __name__ == "__main__": | |
| main() | |