zakerytclarke
commited on
Create generate.py
Browse files- generate.py +43 -0
generate.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
from datasets import load_dataset
|
3 |
+
|
4 |
+
# Load the SQuAD dataset
|
5 |
+
squad_dataset = load_dataset("squad")
|
6 |
+
|
7 |
+
# Convert the 'train' and 'validation' splits to pandas DataFrames
|
8 |
+
train_df = pd.DataFrame(squad_dataset['train'])
|
9 |
+
validation_df = pd.DataFrame(squad_dataset['validation'])
|
10 |
+
|
11 |
+
|
12 |
+
import re
|
13 |
+
import pandas as pd
|
14 |
+
|
15 |
+
df = pd.concat([train_df, validation_df], ignore_index=True)
|
16 |
+
|
17 |
+
|
18 |
+
def get_closest_sentence_section(text, provided_index):
|
19 |
+
# Regular expression to match any punctuation that ends a sentence
|
20 |
+
sentence_end_punctuation = r'[.!?]'
|
21 |
+
|
22 |
+
# Find all occurrences of sentence-ending punctuation and their indices
|
23 |
+
punctuation_indices = [match.start() for match in re.finditer(sentence_end_punctuation, text)]
|
24 |
+
|
25 |
+
# Add the start and end of the string as virtual punctuation indices
|
26 |
+
punctuation_indices = [-1] + punctuation_indices + [len(text)]
|
27 |
+
|
28 |
+
# Find the closest punctuation index above (<= provided_index)
|
29 |
+
closest_above = max([idx for idx in punctuation_indices if idx < provided_index], default=0)
|
30 |
+
|
31 |
+
# Find the closest punctuation index below (> provided_index)
|
32 |
+
closest_below = min([idx for idx in punctuation_indices if idx > provided_index], default=len(text))
|
33 |
+
|
34 |
+
# Trim the string based on closest punctuation above and below
|
35 |
+
trimmed_text = text[closest_above + 1: closest_below + 1].strip()
|
36 |
+
|
37 |
+
return trimmed_text
|
38 |
+
|
39 |
+
# Trim the context to only the relevant sentence
|
40 |
+
df['context'] = df.apply(lambda row: get_closest_sentence_section(row.context, row.answers.get('answer_start')[0]) , axis=1)
|
41 |
+
df['answer'] = df.apply(lambda row: row.answers.get('text')[0] , axis=1)
|
42 |
+
|
43 |
+
df[['title','context','question','answer']].to_parquet('tinysquad.parquet')
|