| """ |
| 数据预处理脚本 |
| 支持提取文本、图像、音频等多模态数据 |
| 使用先进的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 |
| |
| |
| 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) |
| |
| |
| 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) |
| |
| |
| 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: |
| |
| 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", |
| "-ar", "16000", |
| "-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: |
| |
| 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") |
| |
| |
| 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" 或 "test") |
| |
| 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") |
| ) |
| |
| |
| 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" 或 "test") |
| """ |
| print(f"开始处理 {dataset_type} 数据集...") |
| |
| all_results = [] |
| |
| |
| 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} 个视频已完成转录") |
| |
| |
| 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}") |
| |
| |
| 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(): |
| """主函数:只处理test数据""" |
| import argparse |
| |
| parser = argparse.ArgumentParser(description="数据预处理:提取test数据集的多模态数据") |
| parser.add_argument( |
| "--whisper-model", |
| type=str, |
| default="base", |
| choices=["tiny", "base", "small", "medium", "large-v2"], |
| help="Whisper模型大小 (默认: base)" |
| ) |
| parser.add_argument( |
| "--video-dir", |
| type=str, |
| default=None, |
| help="直接指定test视频目录(默认: /root/kk/cxk/First-Impression/data/first-impressions-v2/test)" |
| ) |
| |
| args = parser.parse_args() |
| |
| print("=" * 60) |
| print("数据预处理:test数据集多模态数据提取") |
| 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: |
| test_dir = args.video_dir |
| else: |
| |
| test_dir = "/root/kk/cxk/First-Impression/data/first-impressions-v2/test" |
| |
| if not os.path.exists(test_dir): |
| test_dir = "../First-Impression/data/first-impressions-v2/test" |
| |
| |
| if not os.path.exists(test_dir): |
| print(f"错误: test视频目录不存在: {test_dir}") |
| print("请使用 --video-dir 参数指定正确的test视频目录") |
| return |
| |
| print(f"\n使用test视频目录: {test_dir}") |
| |
| |
| print("\n开始处理test数据...") |
| preprocessor.process_dataset(video_dir=test_dir, dataset_type="test") |
| |
| print("\n" + "=" * 60) |
| print("test数据预处理完成!") |
| print("=" * 60) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|
|
|