import pandas as pd from datasets import load_dataset # Load the SQuAD dataset squad_dataset = load_dataset("squad") # Convert the 'train' and 'validation' splits to pandas DataFrames train_df = pd.DataFrame(squad_dataset['train']) validation_df = pd.DataFrame(squad_dataset['validation']) import re import pandas as pd df = pd.concat([train_df, validation_df], ignore_index=True) def get_closest_sentence_section(text, provided_index): # Regular expression to match any punctuation that ends a sentence sentence_end_punctuation = r'[.!?]' # Find all occurrences of sentence-ending punctuation and their indices punctuation_indices = [match.start() for match in re.finditer(sentence_end_punctuation, text)] # Add the start and end of the string as virtual punctuation indices punctuation_indices = [-1] + punctuation_indices + [len(text)] # Find the closest punctuation index above (<= provided_index) closest_above = max([idx for idx in punctuation_indices if idx < provided_index], default=0) # Find the closest punctuation index below (> provided_index) closest_below = min([idx for idx in punctuation_indices if idx > provided_index], default=len(text)) # Trim the string based on closest punctuation above and below trimmed_text = text[closest_above + 1: closest_below + 1].strip() return trimmed_text # Trim the context to only the relevant sentence df['context'] = df.apply(lambda row: get_closest_sentence_section(row.context, row.answers.get('answer_start')[0]) , axis=1) df['answer'] = df.apply(lambda row: row.answers.get('text')[0] , axis=1) df[['title','context','question','answer']].to_parquet('tinysquad.parquet')