in gemini/prompts/prompt_optimizer/vapo_lib.py [0:0]
def parse_and_validate_csv(data_str: str) -> list[dict[str, str]]:
"""Parses and validates the content of a CSV file and returns a list of dictionaries."""
data = []
csv_reader = csv.reader(io.StringIO(data_str))
# Extract and validate headers
try:
headers = next(csv_reader)
if not headers:
raise ValueError("The CSV file has an empty or invalid header row.")
except StopIteration as e:
raise ValueError("The CSV file is empty.") from e
# Validate and process rows
for row_number, row in enumerate(csv_reader, start=2):
if len(row) != len(headers):
raise ValueError(
f"Row {row_number} has an inconsistent number of fields. "
f"Expected {len(headers)} fields but found {len(row)}."
)
# Create dictionary for each row using headers as keys
item = dict(zip(headers, row))
data.append(item)
return data