ytcollector 1.0.8__py3-none-any.whl → 1.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ytcollector/utils.py CHANGED
@@ -1,144 +1,126 @@
1
- """
2
- Utility functions for the SBS Dataset Collection Pipeline
3
- """
4
- from pathlib import Path
5
- from datetime import datetime
6
- import re
7
- import json
8
-
9
-
10
- def timestamp_to_seconds(minutes: int, seconds: int) -> int:
11
- """분:초를 총 초로 변환"""
12
- return minutes * 60 + seconds
13
-
14
-
15
- def seconds_to_timestamp(total_seconds: int) -> str:
16
- """초를 MM:SS 형식으로 변환"""
17
- minutes = total_seconds // 60
18
- seconds = total_seconds % 60
19
- return f"{minutes:02d}:{seconds:02d}"
20
-
21
-
22
- def extract_video_id(url: str) -> str:
23
- """YouTube URL에서 video ID 추출"""
24
- patterns = [
25
- r'(?:v=|/)([0-9A-Za-z_-]{11}).*',
26
- r'(?:embed/)([0-9A-Za-z_-]{11})',
27
- r'(?:youtu\.be/)([0-9A-Za-z_-]{11})',
1
+ import os
2
+ import subprocess
3
+
4
+ def get_video_duration(file_path):
5
+ """영상 전체 길이를 초 단위로 반환"""
6
+ cmd = [
7
+ 'ffprobe', '-v', 'error', '-show_entries', 'format=duration',
8
+ '-of', 'default=noprint_wrappers=1:nokey=1', file_path
28
9
  ]
29
-
30
- for pattern in patterns:
31
- match = re.search(pattern, url)
32
- if match:
33
- return match.group(1)
34
-
35
- return url[-11:] if len(url) >= 11 else url
36
-
37
-
38
- def ensure_dir(path: Path) -> Path:
39
- """디렉토리 생성 (없으면)"""
40
10
  try:
41
- path.mkdir(parents=True, exist_ok=True)
42
- except PermissionError:
43
- # 네트워크 드라이브 권한 문제 등
44
- pass
45
- return path
46
-
47
-
48
- def get_output_dir(base_dir: Path) -> Path:
49
- """영상이 저장될 실제 디렉토리 반환"""
50
- from .config import CUSTOM_OUTPUT_DIR
51
-
52
- if CUSTOM_OUTPUT_DIR:
53
- return ensure_dir(Path(CUSTOM_OUTPUT_DIR))
54
-
55
- # 기본값: 프로젝트 폴더 내 video/ (단일 폴더 모드)
56
- # 기존에는 video/{task_type}이었으나, 요구사항 변경으로 "한 폴더 안에" 저장
57
- return ensure_dir(base_dir / "video")
58
-
59
-
60
- def get_next_filename(output_dir: Path, task_type: str) -> str:
61
- """
62
- 순차적인 파일명 생성 (task_0001.mp4)
63
- 폴더 내의 기존 파일을 스캔하여 가장 큰 번호 + 1 반환
64
- """
65
- # glob은 느릴 있으므로 파일이 많아지면 최적화 필요
66
- # 현재는 100개 제한이므로 괜찮음
67
- existing_files = list(output_dir.glob(f"{task_type}_*.mp4"))
68
- max_num = 0
11
+ output = subprocess.check_output(cmd).decode('utf-8').strip()
12
+ return float(output)
13
+ except:
14
+ return 0.0
15
+
16
+ def timestamp_to_seconds(timestamp):
17
+ """MM:SS 또는 SS 형식을 초 단위로 변환"""
18
+ if isinstance(timestamp, (int, float)):
19
+ return float(timestamp)
20
+ try:
21
+ parts = str(timestamp).split(':')
22
+ if len(parts) == 2:
23
+ return int(parts[0]) * 60 + int(parts[1])
24
+ return float(parts[0])
25
+ except:
26
+ return 0.0
27
+
28
+ def seconds_to_timestamp(seconds):
29
+ """초 단위를 MM:SS 형식으로 변환"""
30
+ m = int(seconds // 60)
31
+ s = int(seconds % 60)
32
+ return f"{m:02d}:{s:02d}"
33
+
34
+ def clip_video(input_path, output_path, center_sec, window_seconds=90):
35
+ """center_sec를 기준으로 앞뒤 window_seconds만큼 자름"""
36
+ duration = get_video_duration(input_path)
37
+ if duration == 0:
38
+ return False
69
39
 
70
- pattern = re.compile(rf"{task_type}_(\d{{4}})\.mp4")
40
+ start_sec = max(0, center_sec - window_seconds)
41
+ end_sec = min(duration, start_sec + (window_seconds * 2))
71
42
 
72
- for file_path in existing_files:
73
- match = pattern.match(file_path.name)
74
- if match:
75
- num = int(match.group(1))
76
- if num > max_num:
77
- max_num = num
43
+ if (end_sec - start_sec) < (window_seconds * 2) and start_sec > 0:
44
+ start_sec = max(0, end_sec - (window_seconds * 2))
78
45
 
79
- next_num = max_num + 1
80
- return f"{task_type}_{next_num:04d}"
81
-
46
+ actual_duration = end_sec - start_sec
82
47
 
83
- def get_clip_path(base_dir: Path, task_type: str, filename: str = None) -> Path:
84
- """클립 저장 경로 반환"""
85
- # filename이 None이면 순차적 이름 생성
86
- output_dir = get_output_dir(base_dir)
48
+ # 임시 파일 경로
49
+ temp_output = output_path + ".tmp.mp4"
87
50
 
88
- if filename is None:
89
- filename_str = get_next_filename(output_dir, task_type)
90
- return output_dir / f"{filename_str}.mp4"
51
+ cmd = [
52
+ 'ffmpeg', '-y', '-ss', f"{start_sec:.2f}", '-t', f"{actual_duration:.2f}",
53
+ '-i', input_path, '-c', 'copy', temp_output
54
+ ]
91
55
 
92
- # 확장자 보정
93
- if not filename.endswith('.mp4'):
94
- filename += '.mp4'
95
-
96
- return output_dir / filename
97
-
98
-
99
- def get_task_video_count(base_dir: Path, task_type: str) -> int:
100
- """해당 태스크의 영상 개수 확인 (파일명 기준)"""
101
- output_dir = get_output_dir(base_dir)
102
- return len(list(output_dir.glob(f"{task_type}_*.mp4")))
103
-
104
-
105
- def load_history(base_dir: Path) -> dict:
106
- """다운로드 히스토리 로드 (URL 중복 방지용)"""
107
- # 히스토리 파일은 항상 프로젝트 로컬 폴더에 저장 (네트워크 공유 X)
108
- history_path = base_dir / "download_history.json"
109
- if history_path.exists():
56
+ try:
57
+ subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
58
+ if os.path.exists(output_path):
59
+ os.remove(output_path)
60
+ os.rename(temp_output, output_path)
61
+ return True
62
+ except:
63
+ # copy 실패 재인코딩
64
+ cmd[7:9] = ['-c:v', 'libx264', '-crf', '23', '-c:a', 'aac']
110
65
  try:
111
- return json.loads(history_path.read_text(encoding='utf-8'))
66
+ subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
67
+ if os.path.exists(temp_output):
68
+ if os.path.exists(output_path): os.remove(output_path)
69
+ os.rename(temp_output, output_path)
70
+ return True
112
71
  except:
113
- return {}
114
- return {}
115
-
116
-
117
- def save_history(base_dir: Path, history: dict):
118
- """다운로드 히스토리 저장"""
119
- history_path = base_dir / "download_history.json"
120
- history_path.write_text(json.dumps(history, indent=2, ensure_ascii=False), encoding='utf-8')
121
-
122
-
123
- def get_url_file_path(base_dir: Path, task_type: str) -> Path:
124
- """URL 파일 경로 반환"""
125
- # URL 파일은 로컬 urls/task_type/youtube_url.txt
126
- task_dir = ensure_dir(base_dir / "urls" / task_type)
127
- return task_dir / "youtube_url.txt"
128
-
129
-
130
- def get_report_path(base_dir: Path, task_type: str, filename: str) -> Path:
131
- """리포트 저장 경로 반환"""
132
- task_dir = ensure_dir(base_dir / "outputs" / "reports" / task_type)
133
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
134
- return task_dir / f"{filename}_report_{timestamp}.json"
135
-
136
-
137
- def validate_url(url: str) -> bool:
138
- """YouTube URL 유효성 검사"""
139
- youtube_patterns = [
140
- r'(https?://)?(www\.)?youtube\.com/watch\?v=',
141
- r'(https?://)?(www\.)?youtu\.be/',
142
- r'(https?://)?(www\.)?youtube\.com/embed/',
143
- ]
144
- return any(re.match(pattern, url) for pattern in youtube_patterns)
72
+ if os.path.exists(temp_output): os.remove(temp_output)
73
+ return False
74
+
75
+ def append_to_url_list(file_path, url, timestamp, task):
76
+ """youtube_url.txt에 데이터 추가"""
77
+ line = f"{url}, {timestamp}, {task}\n"
78
+ # 파일이 없으면 헤더 추가
79
+ exists = os.path.exists(file_path)
80
+ with open(file_path, 'a', encoding='utf-8') as f:
81
+ if not exists:
82
+ f.write("# URL, MM:SS, TaskName\n")
83
+ f.write(line)
84
+
85
+ def get_url_list(file_path):
86
+ """youtube_url.txt 파일을 읽어서 리스트로 반환"""
87
+ if not os.path.exists(file_path):
88
+ return []
89
+
90
+ urls = []
91
+ with open(file_path, 'r', encoding='utf-8') as f:
92
+ for line in f:
93
+ line = line.strip()
94
+ if not line or line.startswith('#'):
95
+ continue
96
+ parts = [p.strip() for p in line.split(',')]
97
+ if len(parts) >= 3:
98
+ urls.append({
99
+ 'url': parts[0],
100
+ 'timestamp': parts[1],
101
+ 'task': parts[2]
102
+ })
103
+ return urls
104
+
105
+ def get_next_index(directory, prefix):
106
+ """
107
+ directory 내에서 {prefix}_{index:04d}.mp4 형식의 파일들을 찾아
108
+ 가장 높은 index + 1을 반환함. 파일이 없으면 1 반환.
109
+ """
110
+ if not os.path.exists(directory):
111
+ return 1
112
+
113
+ max_idx = 0
114
+ pattern = f"{prefix}_"
115
+ for filename in os.listdir(directory):
116
+ if filename.startswith(pattern) and filename.endswith(".mp4"):
117
+ try:
118
+ # {prefix}_0001.mp4 -> 0001 추출
119
+ idx_part = filename[len(pattern):].split('.')[0]
120
+ idx = int(idx_part)
121
+ if idx > max_idx:
122
+ max_idx = idx
123
+ except (ValueError, IndexError):
124
+ continue
125
+
126
+ return max_idx + 1
@@ -0,0 +1,207 @@
1
+ Metadata-Version: 2.4
2
+ Name: ytcollector
3
+ Version: 1.1.1
4
+ Summary: YouTube 콘텐츠 수집기 - 얼굴, 번호판, 타투, 텍스트 감지
5
+ Author: YTCollector Team
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/yourusername/ytcollector
8
+ Project-URL: Documentation, https://github.com/yourusername/ytcollector#readme
9
+ Project-URL: Repository, https://github.com/yourusername/ytcollector
10
+ Keywords: youtube,downloader,video-analysis,face-detection,ocr
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Requires-Python: >=3.8
21
+ Description-Content-Type: text/markdown
22
+ Requires-Dist: yt-dlp>=2024.0.0
23
+ Provides-Extra: analysis
24
+ Requires-Dist: opencv-python>=4.5.0; extra == "analysis"
25
+ Requires-Dist: easyocr>=1.6.0; extra == "analysis"
26
+ Requires-Dist: numpy>=1.20.0; extra == "analysis"
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
29
+ Requires-Dist: black>=23.0.0; extra == "dev"
30
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
31
+ Provides-Extra: all
32
+ Requires-Dist: ytcollector[analysis,dev]; extra == "all"
33
+
34
+ # YouTube 콘텐츠 수집기
35
+
36
+ 유튜브에서 특정 카테고리(얼굴, 번호판, 타투, 텍스트)의 영상을 자동으로 검색, 다운로드, 분석하여 수집하는 CLI 도구입니다.
37
+
38
+ ## 설치
39
+
40
+ ### 필수 패키지
41
+
42
+ ```bash
43
+ pip install yt-dlp
44
+ ```
45
+
46
+ ### 분석 기능용 패키지 (권장)
47
+
48
+ ```bash
49
+ pip install opencv-python easyocr numpy
50
+ ```
51
+
52
+ ## 사용법
53
+
54
+ ### 기본 실행
55
+
56
+ ```bash
57
+ ytcollector
58
+ ```
59
+
60
+ 기본값: 얼굴 카테고리 5개, 최대 3분 영상
61
+
62
+ ### 옵션
63
+
64
+ | 옵션 | 설명 | 기본값 |
65
+ |------|------|--------|
66
+ | `-c`, `--categories` | 수집할 카테고리 | `face` |
67
+ | `-n`, `--count` | 카테고리당 다운로드 수 | `5` |
68
+ | `-d`, `--duration` | 최대 영상 길이(분) | `3` |
69
+ | `-o`, `--output` | 저장 경로 | `.` (현재 폴더) |
70
+ | `--fast` | 고속 모드 (병렬 다운로드) | 비활성화 |
71
+ | `-w`, `--workers` | 병렬 다운로드 수 | `3` |
72
+ | `--proxy` | 프록시 주소 | 없음 |
73
+
74
+ ### 카테고리 종류
75
+
76
+ | 카테고리 | 설명 | 검색 소스 |
77
+ |----------|------|-----------|
78
+ | `face` | 얼굴/인물 | SBS 인터뷰, 런닝맨, 미운우리새끼 등 |
79
+ | `license_plate` | 자동차 번호판 | 중고차 매물, 세차 영상, 신차 출고 등 |
80
+ | `tattoo` | 타투/문신 | 타투 시술, 타투이스트 작업 영상 |
81
+ | `text` | 텍스트/자막 | SBS 예능 (런닝맨, 골목식당 등) |
82
+
83
+ ## 예시
84
+
85
+ ### 단일 카테고리
86
+
87
+ ```bash
88
+ # 얼굴 영상 10개 수집
89
+ ytcollector -c face -n 10
90
+
91
+ # 번호판 영상 수집 (최대 5분)
92
+ ytcollector -c license_plate -d 5
93
+
94
+ # 타투 영상 수집
95
+ ytcollector -c tattoo -n 5
96
+ ```
97
+
98
+ ### 여러 카테고리
99
+
100
+ ```bash
101
+ # 얼굴과 텍스트 각 10개씩
102
+ ytcollector -c face text -n 10
103
+
104
+ # 모든 카테고리 수집
105
+ ytcollector -c face license_plate tattoo text -n 5
106
+ ```
107
+
108
+ ### 고속 모드
109
+
110
+ ```bash
111
+ # 병렬 다운로드 (기본 3개 동시)
112
+ ytcollector -c face -n 10 --fast
113
+
114
+ # 5개 동시 다운로드
115
+ ytcollector -c face -n 10 --fast -w 5
116
+ ```
117
+
118
+ ### 저장 경로 지정
119
+
120
+ ```bash
121
+ ytcollector -c face -o /path/to/save
122
+ ```
123
+
124
+ ### 프록시 사용
125
+
126
+ ```bash
127
+ ytcollector -c face --proxy http://proxy.server:8080
128
+ ```
129
+
130
+ ## SBS Dataset 구축 (URL 리스트 기반)
131
+
132
+ URL 리스트를 기반으로 영상을 수집하고 특정 시점을 기준으로 자동으로 클리핑(3분 미만)하는 기능입니다.
133
+
134
+ ### 실행 방법
135
+
136
+ ```bash
137
+ ytc-dataset youtube_url.txt
138
+ ```
139
+
140
+ ### youtube_url.txt 형식
141
+
142
+ `URL, MM:SS, TaskName` 형식으로 작성합니다.
143
+ ```text
144
+ https://www.youtube.com/watch?v=aqz-KE-bpKQ, 00:10, sample_task
145
+ ```
146
+
147
+ ### 상세 옵션
148
+
149
+ | 옵션 | 설명 | 기본값 |
150
+ |------|------|--------|
151
+ | `file` | URL 리스트 파일 경로 | (필수) |
152
+ | `-o`, `--output` | 저장 루트 경로 | `.` |
153
+
154
+ ### 특징
155
+ - **자동 트리밍**: 지정된 MM:SS 시점 기준 $\pm$ 1.5분(총 3분)을 자동으로 자릅니다.
156
+ - **중복 방지**: 인덱스 기반으로 이미 다운로드/클리핑된 영상은 건너뜁니다.
157
+ - **저장 구조**: `./video/` (원본), `./video_clips/` (클립) 폴더가 생성됩니다.
158
+
159
+ ## 출력 폴더 구조
160
+
161
+ ```
162
+ 저장경로/
163
+ ├── 얼굴/ # 얼굴 감지된 영상
164
+ ├── 번호판/ # 번호판 감지된 영상
165
+ ├── 번호판_미감지/ # 번호판 미감지 (수동 확인용)
166
+ ├── 타투/ # 타투 감지된 영상
167
+ ├── 텍스트/ # 텍스트 감지된 영상
168
+ └── .archive.txt # 다운로드 기록 (중복 방지)
169
+ ```
170
+
171
+ ## 파일 구조
172
+
173
+ ```
174
+ 260202_test/
175
+ ├── main.py # CLI 진입점
176
+ ├── config.py # 설정 (검색어, UA 등)
177
+ ├── analyzer.py # 영상 분석 (OpenCV, EasyOCR)
178
+ ├── downloader.py # 다운로드 로직
179
+ └── README.md # 사용설명서
180
+ ```
181
+
182
+ ## 분석 기능
183
+
184
+ | 감지 항목 | 사용 기술 | 설명 |
185
+ |-----------|-----------|------|
186
+ | 얼굴 | OpenCV Haar Cascade | 정면 얼굴 감지 |
187
+ | 텍스트 | EasyOCR | 한국어/영어 문자 인식 |
188
+ | 번호판 | EasyOCR + 정규식 | 번호판 패턴 매칭 |
189
+ | 타투 | OpenCV HSV 분석 | 피부 영역 내 잉크 패턴 |
190
+
191
+ ## 주의사항
192
+
193
+ - 영상은 다운로드 후 분석하여 해당 카테고리가 감지된 경우에만 저장됩니다
194
+ - 번호판 카테고리는 미감지 영상도 별도 폴더에 보관됩니다 (수동 확인용)
195
+ - 이미 다운로드한 영상은 자동으로 스킵됩니다 (`.archive.txt` 기록)
196
+ - 비공개/삭제/저작권 영상은 자동 스킵됩니다
197
+
198
+ ## 고속 모드 vs 일반 모드
199
+
200
+ | 항목 | 일반 모드 | 고속 모드 |
201
+ |------|-----------|-----------|
202
+ | 다운로드 | 순차 | 병렬 |
203
+ | 딜레이 | 0.5~1.5초 | 없음 |
204
+ | 재시도 | 3회 | 1회 |
205
+ | 타임아웃 | 30초 | 10초 |
206
+
207
+ 고속 모드는 빠르지만 YouTube 차단 위험이 높아질 수 있습니다.
@@ -0,0 +1,12 @@
1
+ ytcollector/__init__.py,sha256=OkibE8GYgt1qwOmkiBNXywkGVdnMj5sVpVzDVPSRXQg,1094
2
+ ytcollector/analyzer.py,sha256=d86jmykpLxZSv5lGsu642BUt1EQBJoiq9A-aIVP4RSo,7584
3
+ ytcollector/cli.py,sha256=xbqcCivkiqA4ixa05WsbCkDtKUIX3XAm-9WwRBT40DA,5577
4
+ ytcollector/config.py,sha256=WRy41EXDc5BFfN0jJmA0Xdt_YNTuSi0khka9_UL2Ktg,2561
5
+ ytcollector/dataset_builder.py,sha256=nfArEwszoCln48n3T0Eff_4OOaYv8FF0YH8cARBGMWQ,2608
6
+ ytcollector/downloader.py,sha256=ss6V3aBjNZkwLR6FRZuxAwrMkt86Xd6hZc6G2PrNt28,13253
7
+ ytcollector/utils.py,sha256=6XDif-e3GbMHmUvTsBT0YblxNxYnS-2I8HnmjMBZs-M,4254
8
+ ytcollector-1.1.1.dist-info/METADATA,sha256=2x-M9QYgRcGRMw_IaqnmJpf0qh5w_J7blLVU0IuTEkI,6169
9
+ ytcollector-1.1.1.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
10
+ ytcollector-1.1.1.dist-info/entry_points.txt,sha256=waiVuSJJYt-6_DAal-T4JkHgejo7wKYLdKrEI7tZ-ms,127
11
+ ytcollector-1.1.1.dist-info/top_level.txt,sha256=wozNyCUm0eMOm-9U81yTql6oGaM2O5rWVBXDb93zzyQ,12
12
+ ytcollector-1.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ ytc = ytcollector.cli:main
3
+ ytc-dataset = ytcollector.dataset_builder:main
4
+ ytcollector = ytcollector.cli:main
config/settings.py DELETED
@@ -1,39 +0,0 @@
1
- """
2
- SBS Dataset Collection Pipeline - Settings
3
- """
4
- from pathlib import Path
5
-
6
- # Base paths
7
- BASE_DIR = Path(__file__).parent.parent
8
- DATA_DIR = BASE_DIR / "data"
9
- URLS_DIR = DATA_DIR / "urls"
10
- VIDEOS_DIR = DATA_DIR / "videos"
11
- CLIPS_DIR = DATA_DIR / "clips"
12
- OUTPUTS_DIR = BASE_DIR / "outputs"
13
- REPORTS_DIR = OUTPUTS_DIR / "reports"
14
-
15
- # Video settings
16
- CLIP_DURATION_BEFORE = 90 # 1분 30초 (초 단위)
17
- CLIP_DURATION_AFTER = 90 # 1분 30초 (초 단위)
18
- MAX_CLIP_DURATION = 180 # 최대 3분
19
-
20
- # Download settings
21
- VIDEO_FORMAT = "best[ext=mp4]/best"
22
- DOWNLOAD_RETRIES = 3
23
-
24
- # YOLO-World settings
25
- YOLO_MODEL = "yolov8s-worldv2.pt"
26
- CONFIDENCE_THRESHOLD = 0.25
27
- FRAME_SAMPLE_RATE = 30 # 매 30프레임마다 샘플링 (약 1초)
28
-
29
- # Task-specific class prompts
30
- TASK_CLASSES = {
31
- "face": ["human face", "person face", "close-up face"],
32
- "license_plate": ["car license plate", "vehicle license plate", "korean license plate"],
33
- "tattoo": ["tattoo", "body tattoo", "skin tattoo"],
34
- "text": ["text on screen", "subtitle", "korean text", "caption"]
35
- }
36
-
37
- # Create directories if not exist
38
- for dir_path in [URLS_DIR, VIDEOS_DIR, CLIPS_DIR, REPORTS_DIR]:
39
- dir_path.mkdir(parents=True, exist_ok=True)