File size: 6,903 Bytes
e31e7b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import argparse
import pandas as pd
from tqdm import tqdm

from concurrent.futures import ThreadPoolExecutor, as_completed
import threading

# 添加线程锁保护共享资源
video_data_lock = threading.Lock()
matched_count_lock = threading.Lock()

def process_video_file(video_file, args, csv_video_mapping):
    """处理单个视频文件的函数"""
    video_path = os.path.join(args.input_video_root, video_file)
    video_filename = os.path.splitext(video_file)[0]
    
    matched_row = None
    for csv_prefix, row in csv_video_mapping.items():
        if video_filename.startswith(csv_prefix):
            matched_row = row
            break

    result = None
    if matched_row is not None:
        final_csv_path = os.path.join(args.output_csv_path, (video_filename + ".csv"))
        
        if os.path.exists(final_csv_path):
            # 检查CSV文件是否损坏
            try:
                import pandas as pd
                # 尝试读取CSV文件来验证其完整性
                pd.read_csv(final_csv_path)
                return None  # 文件存在且有效,不需要重新处理
            except (pd.errors.EmptyDataError, pd.errors.ParserError, UnicodeDecodeError, FileNotFoundError) as e:
                # CSV文件损坏,删除它
                print(f"Warning: CSV file {final_csv_path} is corrupted ({e}). Deleting and will recreate.")
                os.remove(final_csv_path)

        result = {
            'videoFile': video_filename + ".mp4",
            'cameraFile': matched_row['cameraFile'],
            'location': matched_row['location'],  
            'scene': matched_row['scene'], 
            'crowdDensity': matched_row['crowdDensity'], 
            'weather': matched_row['weather'], 
            'timeOfDay': matched_row['timeOfDay'],
        }
    else:
        print(f"Warning: No CSV record found for video file: {video_file}")
    
    return result

# 多线程处理主代码
def process_videos_multithreaded(video_files, args, csv_video_mapping, max_workers=4):
    video_data = []
    matched_count = 0
    
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        # 提交所有任务
        future_to_video = {
            executor.submit(process_video_file, video_file, args, csv_video_mapping): video_file 
            for video_file in video_files
        }
        
        # 处理完成的任务
        for future in tqdm(as_completed(future_to_video), total=len(video_files), desc="Processing videos"):
            video_file = future_to_video[future]
            try:
                result = future.result()
                if result is not None:
                    with video_data_lock:
                        video_data.append(result)
                    with matched_count_lock:
                        matched_count += 1
            except Exception as exc:
                print(f'Video {video_file} generated an exception: {exc}')
    
    return video_data, matched_count

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--input_csv",
        type=str,
        default="/mnt/bn/yufan-dev-my/ysh/Ckpts/Lixsp11/0_final_sekai_dataset/yamls/sekai-game-walking_updated.csv",
    )
    parser.add_argument(
        "--input_video_root", type=str, default="/mnt/bn/yufan-dev-my/ysh/Ckpts/Lixsp11/0_final_sekai_dataset/sekai-game-walking-386"
    )
    parser.add_argument(
        "--output_csv_path",
        type=str,
        default="/mnt/bn/yufan-dev-my/ysh/Ckpts/Lixsp11/0_final_sekai_dataset/yamls/sekai-game-walking-386",
    )
    parser.add_argument(
        "--output_csv_file",
        type=str,
        default="/mnt/bn/yufan-dev-my/ysh/Ckpts/Lixsp11/0_final_sekai_dataset/yamls/temp_input_csv/sekai-game-walking-386.csv",
    )
    parser.add_argument("--num_workers", type=int, default=16)
    args = parser.parse_args()
    return args

if __name__ == "__main__":
    args = parse_args()

    # 读取CSV文件
    df = pd.read_csv(args.input_csv)

    # 保留需要的字段,过滤掉不需要的字段
    keep_columns = ['videoFile', 'cameraFile', 'caption', 'location', 'scene', 'crowdDensity', 'weather', 'timeOfDay']
    df = df[keep_columns].copy()

    # 创建CSV中视频文件名前缀到记录的映射
    csv_video_mapping = {}
    for idx, row in df.iterrows():
        video_prefix = os.path.splitext(os.path.basename(row['videoFile']))[0]
        csv_video_mapping[video_prefix] = row

    # 获取视频文件夹中的所有视频文件
    video_files = []
    for file in os.listdir(args.input_video_root):
        if file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv')):  # 添加更多视频格式
            video_files.append(file)

    # # 准备视频数据
    # video_data = []
    # matched_count = 0
    
    # for video_file in tqdm(video_files):
    #     video_path = os.path.join(args.input_video_root, video_file)
    #     video_filename = os.path.splitext(video_file)[0]
        
    #     matched_row = None
    #     for csv_prefix, row in csv_video_mapping.items():
    #         if video_filename.startswith(csv_prefix):
    #             matched_row = row
    #             break

    #     if matched_row is not None:
    #         final_csv_path = os.path.join(args.output_csv_path, (video_filename + ".csv"))
    #         if not os.path.exists(final_csv_path):
    #             video_data.append({
    #                 "video_key": video_filename,
    #                 'videoFile': video_filename + ".mp4",
    #                 'cameraFile': matched_row['cameraFile'],
    #                 'location': matched_row['location'],  
    #                 'scene': matched_row['scene'], 
    #                 'crowdDensity': matched_row['crowdDensity'], 
    #                 'weather': matched_row['weather'], 
    #                 'timeOfDay': matched_row['timeOfDay'],
    #             })
    #             matched_count += 1
    #     else:
    #         print(f"Warning: No CSV record found for video file: {video_file}")
    video_data, matched_count = process_videos_multithreaded(video_files, args, csv_video_mapping, max_workers=args.num_workers)
    
    print(f"Successfully matched {matched_count} videos with CSV records")
    print(f"Total video data to process: {len(video_data)}")

    if video_data:
        output_df = pd.DataFrame(video_data)
        output_csv_file = args.output_csv_file
        output_df.to_csv(output_csv_file, index=False)
        print(f"Video data saved to: {output_csv_file}")
        print(f"Saved {len(video_data)} video records")
    else:
        output_df = pd.DataFrame()
        output_csv_file = args.output_csv_file
        output_df.to_csv(output_csv_file, index=False)
        print(f"Empty video data saved to: {output_csv_file}")
        print("No video data to save - created empty CSV file")