PerSets commited on
Commit
e8461b5
·
1 Parent(s): fb31e12

fix: error handling

Browse files
Files changed (1) hide show
  1. asr_dataset.py +107 -78
asr_dataset.py CHANGED
@@ -39,92 +39,121 @@ class ASRDataset(datasets.GeneratorBasedBuilder):
39
  }),
40
  supervised_keys=None,
41
  citation=_CITATION,
42
- # Explicitly specify columns to show in the data viewer
43
- homepage="https://huggingface.co/datasets/your-dataset",
44
- license="",
45
- task_templates=[
46
- datasets.AutomaticSpeechRecognition(
47
- audio_column="audio",
48
- transcription_column="sentence",
49
- )
50
- ],
51
  )
52
 
53
  def _split_generators(self, dl_manager):
54
- return [
55
- datasets.SplitGenerator(
56
- name=datasets.Split.TRAIN,
57
- gen_kwargs={
58
- "split": "train",
59
- "data_dir": self.config.data_dir,
60
- },
61
- ),
62
- ]
 
 
 
 
 
 
63
 
64
  def _prepare_metadata(self, data_dir: str) -> pd.DataFrame:
65
- """Prepare metadata by adding tar file information."""
66
- logger.info("Preparing metadata with tar file information...")
67
-
68
- # Read metadata
69
- metadata_path = os.path.join(data_dir, "metadata.csv")
70
- df = pd.read_csv(metadata_path, sep='\t', names=['file_name', 'sentence'], encoding="utf-8")
71
-
72
- # Add tar_file column
73
- clips_dir = os.path.join(data_dir, "clips")
74
- tar_files = [f for f in os.listdir(clips_dir) if f.endswith('.tar')]
75
-
76
- # Initialize tar_file column
77
- df['tar_file'] = None
78
-
79
- # Find which tar file contains each audio file
80
- for tar_file in tar_files:
81
- tar_path = os.path.join(clips_dir, tar_file)
82
- with tarfile.open(tar_path, 'r') as tar:
83
- file_list = tar.getnames()
84
- mask = df['file_name'].isin(file_list)
85
- df.loc[mask, 'tar_file'] = tar_file
86
-
87
- # Remove entries where tar_file is None (file not found in any tar)
88
- df = df.dropna(subset=['tar_file'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- return df
 
 
 
91
 
92
  def _generate_examples(self, split, data_dir):
93
- """Yields examples."""
94
- # Prepare metadata with tar file information
95
- df = self._prepare_metadata(data_dir)
96
- clips_dir = os.path.join(data_dir, "clips")
97
-
98
- idx = 0
99
- # Group by tar_file for efficient processing
100
- for tar_file, group in df.groupby('tar_file'):
101
- tar_path = os.path.join(clips_dir, tar_file)
102
- logger.info(f"Processing {tar_file}...")
103
 
104
- try:
105
- with tarfile.open(tar_path, 'r') as tar:
106
- for _, row in group.iterrows():
107
- try:
108
- member = tar.getmember(row['file_name'])
109
- f = tar.extractfile(member)
110
- if f is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  continue
112
 
113
- audio_bytes = f.read()
114
- f.close()
115
-
116
- yield idx, {
117
- "file_name": row['file_name'],
118
- "audio": {"path": f"{tar_path}::{row['file_name']}", "bytes": audio_bytes},
119
- "sentence": row['sentence'],
120
- "tar_file": tar_file,
121
- }
122
- idx += 1
123
-
124
- except Exception as e:
125
- logger.warning(f"Error processing file {row['file_name']}: {str(e)}")
126
- continue
127
-
128
- except Exception as e:
129
- logger.error(f"Error processing tar file {tar_file}: {str(e)}")
130
- continue
 
39
  }),
40
  supervised_keys=None,
41
  citation=_CITATION,
 
 
 
 
 
 
 
 
 
42
  )
43
 
44
  def _split_generators(self, dl_manager):
45
+ """Returns SplitGenerators with added error handling."""
46
+ try:
47
+ return [
48
+ datasets.SplitGenerator(
49
+ name=datasets.Split.TRAIN,
50
+ gen_kwargs={
51
+ "split": "train",
52
+ "data_dir": self.config.data_dir,
53
+ },
54
+ ),
55
+ ]
56
+ except Exception as e:
57
+ logger.error(f"Error in _split_generators: {e}")
58
+ logger.error(traceback.format_exc())
59
+ raise
60
 
61
  def _prepare_metadata(self, data_dir: str) -> pd.DataFrame:
62
+ """Prepare metadata with comprehensive error handling."""
63
+ try:
64
+ logger.info("Preparing metadata with tar file information...")
65
+
66
+ # Read metadata
67
+ metadata_path = os.path.join(data_dir, "metadata.csv")
68
+
69
+ # Add error handling for metadata reading
70
+ try:
71
+ df = pd.read_csv(metadata_path, sep='\t', names=['file_name', 'sentence'], encoding="utf-8")
72
+ except Exception as read_error:
73
+ logger.error(f"Failed to read metadata file: {read_error}")
74
+ raise
75
+
76
+ # Validate dataframe
77
+ if df.empty:
78
+ raise ValueError("Metadata file is empty")
79
+
80
+ # Add tar_file column
81
+ clips_dir = os.path.join(data_dir, "clips")
82
+ tar_files = [f for f in os.listdir(clips_dir) if f.endswith('.tar')]
83
+
84
+ # Initialize tar_file column
85
+ df['tar_file'] = None
86
+
87
+ # Find which tar file contains each audio file
88
+ for tar_file in tar_files:
89
+ tar_path = os.path.join(clips_dir, tar_file)
90
+ try:
91
+ with tarfile.open(tar_path, 'r') as tar:
92
+ file_list = tar.getnames()
93
+ mask = df['file_name'].isin(file_list)
94
+ df.loc[mask, 'tar_file'] = tar_file
95
+ except Exception as tar_error:
96
+ logger.warning(f"Error processing tar file {tar_file}: {tar_error}")
97
+
98
+ # Remove entries where tar_file is None (file not found in any tar)
99
+ df = df.dropna(subset=['tar_file'])
100
+
101
+ # Additional logging
102
+ logger.info(f"Total entries after tar file mapping: {len(df)}")
103
+
104
+ return df
105
 
106
+ except Exception as e:
107
+ logger.error(f"Unexpected error in _prepare_metadata: {e}")
108
+ logger.error(traceback.format_exc())
109
+ raise
110
 
111
  def _generate_examples(self, split, data_dir):
112
+ """Yields examples with comprehensive error handling."""
113
+ try:
114
+ # Prepare metadata with tar file information
115
+ df = self._prepare_metadata(data_dir)
116
+ clips_dir = os.path.join(data_dir, "clips")
 
 
 
 
 
117
 
118
+ idx = 0
119
+ # Group by tar_file for efficient processing
120
+ for tar_file, group in df.groupby('tar_file'):
121
+ tar_path = os.path.join(clips_dir, tar_file)
122
+ logger.info(f"Processing tar file: {tar_file}")
123
+
124
+ try:
125
+ with tarfile.open(tar_path, 'r') as tar:
126
+ for _, row in group.iterrows():
127
+ try:
128
+ # More robust file extraction
129
+ member = tar.getmember(row['file_name'])
130
+ f = tar.extractfile(member)
131
+ if f is None:
132
+ logger.warning(f"Could not extract file: {row['file_name']}")
133
+ continue
134
+
135
+ audio_bytes = f.read()
136
+ f.close()
137
+
138
+ yield idx, {
139
+ "file_name": row['file_name'],
140
+ "audio": {"path": f"{tar_path}::{row['file_name']}", "bytes": audio_bytes},
141
+ "sentence": row['sentence'],
142
+ "tar_file": tar_file,
143
+ }
144
+ idx += 1
145
+
146
+ except Exception as file_error:
147
+ logger.warning(f"Error processing file {row['file_name']}: {file_error}")
148
  continue
149
 
150
+ except Exception as tar_error:
151
+ logger.error(f"Error processing tar file {tar_file}: {tar_error}")
152
+ continue
153
+
154
+ logger.info(f"Total examples generated: {idx}")
155
+
156
+ except Exception as e:
157
+ logger.error(f"Unexpected error in _generate_examples: {e}")
158
+ logger.error(traceback.format_exc())
159
+ raise