|
from datasets import load_dataset |
|
import pandas as pd |
|
import re |
|
import json |
|
|
|
|
|
dataset = load_dataset('squad') |
|
|
|
|
|
def find_previous_punctuation(text, start_index): |
|
|
|
punctuation_pattern = r"[.?!;]" |
|
|
|
matches = list(re.finditer(punctuation_pattern, text[:start_index])) |
|
if matches: |
|
|
|
return matches[-1].end() |
|
return 0 |
|
|
|
|
|
def find_next_punctuation(text, start_index): |
|
|
|
punctuation_pattern = r"[.?!;]" |
|
|
|
match = re.search(punctuation_pattern, text[start_index:]) |
|
if match: |
|
|
|
return start_index + match.end() |
|
return len(text) |
|
|
|
|
|
def get_row_context(row): |
|
|
|
answer_idx = row.get('answers').get('answer_start')[0] |
|
|
|
start_idx = find_previous_punctuation(row['context'], answer_idx) |
|
|
|
end_idx = find_next_punctuation(row['context'], answer_idx + len(row.get('answers').get('text')[0])) |
|
|
|
return row['context'][start_idx:end_idx].strip() |
|
|
|
|
|
def join_squad_dataset(dataset): |
|
|
|
df = pd.DataFrame(dataset) |
|
|
|
df['context'] = df.apply(get_row_context, axis=1) |
|
df['answer'] = df['answers'].apply(lambda x: x['text'][0]) |
|
|
|
return df[['context', 'question', 'answer']] |
|
|
|
|
|
train_df = join_squad_dataset(dataset['train']) |
|
test_df = join_squad_dataset(dataset['validation']) |
|
|
|
with open("train.json", "w", encoding="utf-8") as f: |
|
json.dump(train_df.to_dict(orient='records'), f, indent=4, ensure_ascii=False) |
|
|
|
with open("validation.json", "w", encoding="utf-8") as f: |
|
json.dump(test_df.to_dict(orient='records'), f, indent=4, ensure_ascii=False) |
|
|