File size: 17,805 Bytes
cef1eca | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | """
数据预处理脚本
支持提取文本、图像、音频等多模态数据
使用先进的Whisper ASR进行语音转文本
"""
import os
import cv2
import zipfile
import subprocess
import pickle
import pandas as pd
from pathlib import Path
from typing import List, Optional, Dict
from config import Config
from asr_transcription import ASRTranscriber, get_transcription_text
class DataPreprocessor:
"""数据预处理器"""
def __init__(self, whisper_model_size: str = "base"):
"""
初始化数据预处理器
Args:
whisper_model_size: Whisper模型大小 (tiny/base/small/medium/large-v2)
"""
Config.create_dirs()
self.asr_transcriber = None
self.whisper_model_size = whisper_model_size
# 如果启用文本模态,初始化ASR
if Config.MODALITIES["text"]:
try:
self.asr_transcriber = ASRTranscriber(model_size=whisper_model_size)
print(f"ASR转录器已初始化 (模型: {whisper_model_size})")
except Exception as e:
print(f"警告: ASR转录器初始化失败: {e}")
print("文本模态将被禁用")
Config.MODALITIES["text"] = False
def extract_images_from_video(
self,
video_path: str,
output_dir: str,
max_frames: int = None
) -> List[str]:
"""
从视频提取图像帧
Args:
video_path: 视频文件路径
output_dir: 输出目录
max_frames: 最大提取帧数
Returns:
提取的图像路径列表
"""
max_frames = max_frames or Config.MAX_FRAMES
video_name = Path(video_path).stem
# 创建输出目录
frame_dir = os.path.join(output_dir, video_name)
os.makedirs(frame_dir, exist_ok=True)
# 打开视频
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"无法打开视频: {video_path}")
return []
frame_paths = []
count = 0
while count < max_frames:
ret, frame = cap.read()
if not ret:
break
# 调整大小
frame = cv2.resize(
frame,
(Config.IMAGE_SIZE, Config.IMAGE_SIZE),
interpolation=cv2.INTER_CUBIC
)
# 保存帧
frame_path = os.path.join(frame_dir, f"frame_{count:03d}.jpg")
cv2.imwrite(frame_path, frame)
frame_paths.append(frame_path)
count += 1
cap.release()
return frame_paths
def extract_audio_from_video(
self,
video_path: str,
output_dir: str
) -> Optional[str]:
"""
从视频提取音频
Args:
video_path: 视频文件路径
output_dir: 输出目录
Returns:
音频文件路径
"""
video_name = Path(video_path).stem
audio_path = os.path.join(output_dir, f"{video_name}.wav")
os.makedirs(output_dir, exist_ok=True)
# 使用 ffmpeg 提取音频
command = [
"ffmpeg",
"-i", video_path,
"-ab", "320k",
"-ac", "2",
"-ar", str(Config.AUDIO_SAMPLE_RATE),
"-vn", # 不包含视频
"-y", # 覆盖输出文件
audio_path
]
try:
subprocess.run(
command,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
return audio_path
except subprocess.CalledProcessError:
print(f"提取音频失败: {video_path}")
return None
def extract_text_from_video(
self,
video_path: str,
output_dir: str,
use_audio: bool = True
) -> Optional[Dict]:
"""
从视频提取文本转录(使用先进的Whisper ASR)
Args:
video_path: 视频文件路径
output_dir: 输出目录
use_audio: 如果为True,先提取音频再转录(更高效);False则直接从视频转录
Returns:
包含转录信息的字典:
{
"text_path": "文本文件路径",
"json_path": "JSON文件路径",
"transcription": 转录结果字典
}
"""
if not Config.MODALITIES["text"]:
return None
video_name = Path(video_path).stem
os.makedirs(output_dir, exist_ok=True)
# 初始化ASR(如果尚未初始化)
if self.asr_transcriber is None:
try:
self.asr_transcriber = ASRTranscriber(model_size=self.whisper_model_size)
except Exception as e:
print(f"无法初始化ASR转录器: {e}")
return None
try:
# 方法1: 如果已有音频文件,直接转录音频(更快)
if use_audio:
# 先提取音频
audio_dir = os.path.join(os.path.dirname(output_dir), "audio_temp")
os.makedirs(audio_dir, exist_ok=True)
audio_path = os.path.join(audio_dir, f"{video_name}.wav")
# 提取音频(如果不存在)
if not os.path.exists(audio_path):
command = [
"ffmpeg",
"-i", video_path,
"-ab", "320k",
"-ac", "1", # 单声道(Whisper推荐)
"-ar", "16000", # 16kHz(Whisper推荐)
"-vn",
"-y",
audio_path
]
try:
subprocess.run(
command,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
except subprocess.CalledProcessError:
print(f"提取音频失败,尝试直接从视频转录")
audio_path = None
# 转录音频或视频
if audio_path and os.path.exists(audio_path):
transcription = self.asr_transcriber.transcribe_audio(audio_path)
else:
transcription = self.asr_transcriber.transcribe_video(video_path)
else:
# 方法2: 直接从视频转录
transcription = self.asr_transcriber.transcribe_video(video_path)
# 保存转录结果
json_path = os.path.join(output_dir, f"{video_name}_transcription.json")
txt_path = os.path.join(output_dir, f"{video_name}_transcription.txt")
# 保存JSON(包含完整信息)
self.asr_transcriber.save_transcription(transcription, json_path, "json")
# 保存纯文本
self.asr_transcriber.save_transcription(transcription, txt_path, "txt")
print(f"转录完成: {video_name} (语言: {transcription.get('language', 'unknown')}, "
f"文本长度: {len(transcription['text'])} 字符)")
return {
"text_path": txt_path,
"json_path": json_path,
"transcription": transcription
}
except Exception as e:
print(f"转录失败 {video_name}: {e}")
import traceback
traceback.print_exc()
return None
def process_video(
self,
video_path: str,
video_name: str,
dataset_type: str = "training"
) -> Dict:
"""
处理单个视频,提取所有模态数据
Args:
video_path: 视频文件路径
video_name: 视频名称
dataset_type: 数据集类型 ("training" 或 "validation")
Returns:
包含各模态数据路径的字典
"""
result = {
"video_name": video_name,
"video_path": video_path, # 保存原始视频路径
"images": [],
"audio_path": None,
"text_path": None,
"text_json_path": None,
"transcription": None
}
# 提取图像
if Config.MODALITIES["vision"]:
result["images"] = self.extract_images_from_video(
video_path,
os.path.join(Config.IMAGE_DATA_DIR, f"{dataset_type}Data"),
max_frames=Config.MAX_FRAMES
)
# 提取音频
if Config.MODALITIES["audio"]:
result["audio_path"] = self.extract_audio_from_video(
video_path,
os.path.join(Config.AUDIO_DATA_DIR, f"{dataset_type}Data")
)
# 提取文本转录(使用Whisper ASR)
if Config.MODALITIES["text"]:
text_result = self.extract_text_from_video(
video_path,
os.path.join(Config.TEXT_DATA_DIR, f"{dataset_type}Data"),
use_audio=True # 使用已提取的音频(如果存在)
)
if text_result:
result["text_path"] = text_result["text_path"]
result["text_json_path"] = text_result["json_path"]
result["transcription"] = text_result["transcription"]
return result
def process_dataset(
self,
zip_files: List[str] = None,
video_dir: str = None,
dataset_type: str = "training"
):
"""
处理整个数据集
Args:
zip_files: zip文件路径列表(可选)
video_dir: 视频目录路径(可选,如果提供则直接处理目录中的mp4文件)
dataset_type: 数据集类型 ("training" 或 "validation")
"""
print(f"开始处理 {dataset_type} 数据集...")
all_results = []
# 方式1: 如果提供了视频目录,直接处理目录中的mp4文件
if video_dir and os.path.exists(video_dir):
print(f"从目录处理视频: {video_dir}")
import glob
video_files = glob.glob(os.path.join(video_dir, "*.mp4"))
print(f"找到 {len(video_files)} 个视频文件")
for video_path in video_files:
video_name = Path(video_path).stem
result = self.process_video(video_path, video_name, dataset_type)
all_results.append(result)
if len(all_results) % 10 == 0:
print(f"已处理 {len(all_results)}/{len(video_files)} 个视频")
# 显示转录统计
if Config.MODALITIES["text"]:
transcribed_count = sum(
1 for r in all_results
if r.get("transcription") is not None
)
print(f" 其中 {transcribed_count} 个视频已完成转录")
# 方式2: 从zip文件处理(原始方式)
elif zip_files:
for zip_file in zip_files:
if not os.path.exists(zip_file):
print(f"文件不存在: {zip_file}")
continue
print(f"处理: {zip_file}")
# 解压zip文件
with zipfile.ZipFile(zip_file, 'r') as archive:
archive.extractall(f"./unzippedData/{dataset_type}")
# 处理每个视频
for file_name in archive.namelist():
if file_name.endswith('.mp4'):
video_path = os.path.join(
f"./unzippedData/{dataset_type}",
file_name
)
if os.path.exists(video_path):
video_name = Path(file_name).stem
result = self.process_video(video_path, video_name, dataset_type)
all_results.append(result)
if len(all_results) % 10 == 0:
print(f"已处理 {len(all_results)} 个视频")
# 显示转录统计
if Config.MODALITIES["text"]:
transcribed_count = sum(
1 for r in all_results
if r.get("transcription") is not None
)
print(f" 其中 {transcribed_count} 个视频已完成转录")
# 保存处理结果
output_file = os.path.join(
Config.OUTPUT_DIR,
f"{dataset_type}_data_info.pkl"
)
with open(output_file, "wb") as f:
pickle.dump(all_results, f)
print(f"处理完成!共处理 {len(all_results)} 个视频")
print(f"结果已保存到: {output_file}")
return all_results
def load_annotations(self, annotation_file: str) -> pd.DataFrame:
"""
加载标注文件
Args:
annotation_file: 标注文件路径
Returns:
标注DataFrame
"""
with open(annotation_file, "rb") as f:
pickle_data = pickle.load(f, encoding="latin1")
df = pd.DataFrame(pickle_data)
df.reset_index(inplace=True)
if "interview" in df.columns:
del df["interview"]
df.columns = [
"VideoName",
"ValueExtraversion",
"ValueNeuroticism",
"ValueAgreeableness",
"ValueConscientiousness",
"ValueOpenness",
]
return df
def main():
"""主函数:处理训练和验证数据"""
import argparse
parser = argparse.ArgumentParser(description="数据预处理:提取多模态数据")
parser.add_argument(
"--whisper-model",
type=str,
default="base",
choices=["tiny", "base", "small", "medium", "large-v2"],
help="Whisper模型大小 (默认: base)"
)
parser.add_argument(
"--skip-training",
action="store_true",
help="跳过训练数据处理"
)
parser.add_argument(
"--skip-validation",
action="store_true",
help="跳过验证数据处理"
)
parser.add_argument(
"--video-dir",
type=str,
default=None,
help="直接指定视频目录(而不是zip文件)"
)
args = parser.parse_args()
print("=" * 60)
print("数据预处理:多模态数据提取")
print("=" * 60)
print(f"Whisper模型: {args.whisper_model}")
print(f"激活的模态: {Config.get_active_modalities()}")
print("=" * 60)
preprocessor = DataPreprocessor(whisper_model_size=args.whisper_model)
# 如果指定了视频目录,直接使用
if args.video_dir:
print(f"\n使用视频目录: {args.video_dir}")
preprocessor.process_dataset(video_dir=args.video_dir, dataset_type="training")
else:
# 尝试从first-impressions-v2目录处理
train_dir = "../First-Impression/data/first-impressions-v2/train"
val_dir = "../First-Impression/data/first-impressions-v2/validation"
if os.path.exists(train_dir):
# 处理训练数据
if not args.skip_training:
print("\n开始处理训练数据...")
preprocessor.process_dataset(video_dir=train_dir, dataset_type="training")
# 处理验证数据
if not args.skip_validation:
print("\n开始处理验证数据...")
preprocessor.process_dataset(video_dir=val_dir, dataset_type="validation")
else:
# 回退到zip文件方式
if not args.skip_training:
print("\n开始处理训练数据(从zip文件)...")
training_zips = [
f"../First-Impression/data/training80_{i:02d}.zip"
for i in range(1, 76)
]
preprocessor.process_dataset(training_zips, dataset_type="training")
if not args.skip_validation:
print("\n开始处理验证数据(从zip文件)...")
validation_zips = [
f"../First-Impression/data/validation80_{i:02d}.zip"
for i in range(1, 26)
]
preprocessor.process_dataset(validation_zips, dataset_type="validation")
print("\n" + "=" * 60)
print("数据预处理完成!")
print("=" * 60)
if __name__ == "__main__":
main()
|