Open-Sora: Democratizing Efficient Video Production for All
Python
[feat] faster get file list
Zangwei Zheng6e2f42cd9f12
diff --git a/copy_over_caption.py b/copy_over_caption.pynew file mode 100644index 0000000..ae6e10a--- /dev/null+++ b/copy_over_caption.py@@ -0,0 +1,46 @@+import argparse+import json++import pandas as pd+from pandarallel import pandarallel+++def process_csv(original_csv_path, original_video_format="mp4"):+ pandarallel.initialize(progress_bar=True)++ # Construct the new CSV file name by adding '_caption' before the '.csv' extension+ caption_file = original_csv_path.replace(".csv", "_caption.csv")+ df = pd.read_csv(original_csv_path)++ # Add a new column for captions initialized with 'None'+ df["caption"] = "None"++ def process_row(row):+ path = row["path"]+ json_path = path.replace(original_video_format, "json")++ with open(json_path, "r") as f:+ json_data = json.load(f)++ row["caption"] = json_data["caption"]+ return row++ # Iterate over each row to replace video format with json in the path, and extract captions+ df = df.parallel_apply(process_row, axis=1)++ # Save the modified DataFrame to a new CSV file+ df.to_csv(caption_file, index=False)+ print(f"New CSV file with captions is saved as {caption_file}")+++if __name__ == "__main__":+ # Setup argument parser+ parser = argparse.ArgumentParser(description="Process a CSV file to add video captions.")+ parser.add_argument("csv_path", type=str, help="The path to the original CSV file.")+ parser.add_argument("video_format", nargs="?", default="mp4", help="The original video format (default: mp4).")++ # Parse arguments+ args = parser.parse_args()++ # Call the function with the provided arguments+ process_csv(args.csv_path, args.video_format)diff --git a/tools/datasets/convert.py b/tools/datasets/convert.pyindex ad80461..ef6eee3 100644--- a/tools/datasets/convert.py+++ b/tools/datasets/convert.py@@ -1,5 +1,6 @@import argparseimport os+import timeimport pandas as pdfrom torchvision.datasets import ImageNet@@ -8,14 +9,40 @@ IMG_EXTENSIONS = (".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tifVID_EXTENSIONS = (".mp4", ".avi", ".mov", ".mkv")+def scan_recursively(root):+ num = 0+ for entry in os.scandir(root):+ if entry.is_file():+ yield entry+ elif entry.is_dir():+ num += 1+ if num % 100 == 0:+ print(f"Scanned {num} directories.")+ yield from scan_recursively(entry.path)++def get_filelist(file_path, exts=None):- Filelist = []- for home, dirs, files in os.walk(file_path):- for filename in files:- ext = os.path.splitext(filename)[-1].lower()+ filelist = []+ time_start = time.time()++ # == OS Walk ==+ # for home, dirs, files in os.walk(file_path):+ # for filename in files:+ # ext = os.path.splitext(filename)[-1].lower()+ # if exts is None or ext in exts:+ # filelist.append(os.path.join(home, filename))++ # == Scandir ==+ obj = scan_recursively(file_path)+ for entry in obj:+ if entry.is_file():+ ext = os.path.splitext(entry.name)[-1].lower()if exts is None or ext in exts:- Filelist.append(os.path.join(home, filename))- return Filelist+ filelist.append(entry.path)++ time_end = time.time()+ print(f"Scanned {len(filelist)} files in {time_end - time_start:.2f} seconds.")+ return filelistdef split_by_capital(name):diff --git a/tools/datasets/csvutil.py b/tools/datasets/csvutil.pyindex 1bd0a19..9b21dac 100644--- a/tools/datasets/csvutil.py+++ b/tools/datasets/csvutil.py@@ -1,5 +1,6 @@import argparseimport html+import jsonimport osimport randomimport re@@ -329,6 +330,20 @@ def text_preprocessing(text, use_text_preprocessing: bool = True):return text.lower().strip()+# ======================================================+# load caption+# ======================================================+++def load_caption(path, ext):+ assert ext in ["json"]+ json_path = path.split(".")[0] + ".json"+ with open(json_path, "r") as f:+ data = json.load(f)+ caption = data["caption"]+ return caption++# ======================================================# read & write# ======================================================@@ -461,6 +476,9 @@ def main(args):data["fps"],data["resolution"],) = zip(*info)+ if args.load_caption is not None:+ assert "path" in data.columns+ data["text"] = apply(data["path"], load_caption, ext=args.load_caption)# sortif args.sort is not None:@@ -520,7 +538,7 @@ def parse_args():parser.add_argument("--shard", type=int, default=None, help="shard the dataset")parser.add_argument("--sort", type=str, default=None, help="sort by column")parser.add_argument("--sort-ascending", type=str, default=None, help="sort by column (ascending order)")- parser.add_argument("--difference", type=str, default=None, help="remove the paths in csv from the dataset")+ parser.add_argument("--difference", type=str, default=None, help="get difference from the dataset")parser.add_argument("--intersection", type=str, default=None, help="keep the paths in csv from the dataset and merge columns")@@ -538,7 +556,6 @@ def parse_args():parser.add_argument("--remove-empty-caption",action="store_true",- help="remove the empty caption",help="remove rows with empty caption",)parser.add_argument("--remove-url", action="store_true", help="remove rows with url in caption")@@ -556,6 +573,9 @@ def parse_args():parser.add_argument("--count-num-token", type=str, choices=["t5"], default=None, help="Count the number of tokens in the caption")+ parser.add_argument(+ "--load-caption", type=str, default=None, choices=["json", "txt"], help="load the caption from json or txt"+ )# score filteringparser.add_argument("--fmin", type=int, default=None, help="filter the dataset by minimum number of frames")@@ -619,6 +639,8 @@ def get_output_path(args, input_name):name += "_cmcaption"if args.count_num_token:name += "_ntoken"+ if args.load_caption:+ name += f"_load{args.load_caption}"# score filteringif args.fmin is not None: