azayz commited on
Commit
4ce09e7
1 Parent(s): 0e0ef7b

add scripts to reproduce

Browse files
Files changed (2) hide show
  1. create_data.py +122 -0
  2. preprocess.py +103 -0
create_data.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import os
3
+ from datasets import load_dataset
4
+ import pickle
5
+
6
+
7
+ # Define a helper function to load datasets with retry mechanism
8
+ def load_dataset_with_retries(dataset_name, *args, retries=3, wait=5, **kwargs):
9
+ for attempt in range(retries):
10
+ try:
11
+ return load_dataset(dataset_name, *args, **kwargs)
12
+ except Exception as e:
13
+ print(f"Attempt {attempt + 1} failed for {dataset_name}. Error: {e}")
14
+ if attempt < retries - 1:
15
+ time.sleep(wait)
16
+ else:
17
+ raise
18
+
19
+
20
+ # Checkpoint file to save progress
21
+ checkpoint_file = 'tunisian_data_checkpoint.txt'
22
+ dataset_count_path = 'data_count.pkl'
23
+
24
+ # Load progress if checkpoint exists
25
+ if os.path.exists(checkpoint_file):
26
+ with open(checkpoint_file, 'r') as f:
27
+ final_data = eval(f.read())
28
+ else:
29
+ final_data = []
30
+
31
+ if os.path.exists(dataset_count_path):
32
+ # Loading the variable back
33
+ with open(dataset_count_path, 'rb') as f:
34
+ loaded_data = pickle.load(f)
35
+ datasets_completed = loaded_data['datasets_completed']
36
+ else:
37
+ datasets_completed = 0
38
+
39
+
40
+ # Helper function to save progress to a checkpoint file
41
+ def save_checkpoint(data):
42
+ with open(checkpoint_file, 'w') as f:
43
+ f.write(str(data))
44
+
45
+
46
+ def save_datasets_completed(num):
47
+ # Saving the variable to a file
48
+ with open(dataset_count_path, 'wb') as f:
49
+ pickle.dump({'datasets_completed': num}, f)
50
+
51
+
52
+ # Load and process datasets
53
+ try:
54
+ if datasets_completed < 1:
55
+ ds_xp3x = load_dataset_with_retries("Muennighoff/xP3x", "aeb_Arab", trust_remote_code=True)
56
+ final_data.extend(list(sentence['targets'] for sentence in ds_xp3x['train']))
57
+ save_checkpoint(final_data)
58
+ datasets_completed += 1
59
+
60
+ if datasets_completed < 2:
61
+ ds_glotcc = load_dataset_with_retries("cis-lmu/glotcc-v1", name="aeb-Arab", split="train")
62
+ final_data.extend(list(sentence['content'] for sentence in ds_glotcc))
63
+ save_checkpoint(final_data)
64
+ datasets_completed += 1
65
+
66
+ if datasets_completed < 3:
67
+ ds_flores = load_dataset_with_retries('facebook/flores', 'aeb_Arab')
68
+ final_data.extend(list(sentence['sentence'] for sentence in ds_flores['dev']))
69
+ final_data.extend(list(sentence['sentence'] for sentence in ds_flores['devtest']))
70
+ save_checkpoint(final_data)
71
+ datasets_completed += 1
72
+
73
+ if datasets_completed < 4:
74
+ ds_glotstory = load_dataset_with_retries('cis-lmu/GlotStoryBook', 'default', split='train')
75
+ glotstory_sentences = [sentence for sentence in ds_glotstory if sentence["Language"] == 'aeb']
76
+ final_data.extend(glotstory_sentences)
77
+ save_checkpoint(final_data)
78
+ datasets_completed += 1
79
+
80
+ if datasets_completed < 5:
81
+ ds_sib200 = load_dataset_with_retries('Davlan/sib200', 'aeb_Arab')
82
+ final_data.extend(list(sentence['text'] for sentence in ds_sib200['train']))
83
+ final_data.extend(list(sentence['text'] for sentence in ds_sib200['validation']))
84
+ final_data.extend(list(sentence['text'] for sentence in ds_sib200['test']))
85
+ save_checkpoint(final_data)
86
+ datasets_completed += 1
87
+
88
+ if datasets_completed < 6:
89
+ ds_xsimplus = load_dataset_with_retries("jaygala24/xsimplusplus", "aeb_Arab")
90
+ final_data.extend(list(sentence['query'] for sentence in ds_xsimplus['dev']))
91
+ final_data.extend(list(sentence['query'] for sentence in ds_xsimplus['devtest']))
92
+ save_checkpoint(final_data)
93
+ datasets_completed += 1
94
+
95
+ if datasets_completed < 7:
96
+ ds_gentai = load_dataset_with_retries("gentaiscool/bitext_sib200_miners", "eng_Latn-aeb_Arab")
97
+ final_data.extend(list(sentence['sentence2'] for sentence in ds_gentai['train']))
98
+ save_checkpoint(final_data)
99
+ datasets_completed += 1
100
+
101
+ if datasets_completed < 8:
102
+ dataset_reddit = load_dataset_with_retries('dataverse-scraping/reddit_dataset_219', split='train',
103
+ streaming=True)
104
+
105
+
106
+ def filter_function(example):
107
+ return example['communityName'] == 'r/Tunisia' # Replace with your filter condition
108
+
109
+
110
+ filtered_dataset = dataset_reddit.filter(filter_function)
111
+ final_data.extend(list(sentence['text'] for sentence in filtered_dataset))
112
+ save_checkpoint(final_data)
113
+ datasets_completed += 1
114
+
115
+ # Final save to a text file
116
+ with open('tunisian_data.txt', 'w') as f:
117
+ for line in final_data:
118
+ f.write(f"{line}\n")
119
+
120
+ except Exception as e:
121
+ print(f"An error occurred: {e}. Progress saved.")
122
+ save_checkpoint(final_data)
preprocess.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from collections import Counter
3
+
4
+ import pandas as pd
5
+ from datasketch import MinHash, MinHashLSH
6
+ from lingua import Language, LanguageDetectorBuilder
7
+
8
+ # Initialize variables for statistics
9
+ word_count = Counter()
10
+ longest_sentence = ""
11
+ shortest_sentence = None
12
+ total_sentences = 0
13
+ all_sentences = []
14
+
15
+
16
+ def tokenize(text):
17
+ """
18
+ Clean and split text into words.
19
+ """
20
+ # Remove punctuation and split by whitespace
21
+ words = re.findall(r'\b\w+\b', text.lower())
22
+ return words
23
+
24
+
25
+ # Open the file and process line by line
26
+ with open('tunisian_data.txt', 'r') as file:
27
+ for line in file:
28
+ # Strip leading/trailing whitespace
29
+ line = line.strip()
30
+
31
+ # Skip empty lines
32
+ if not line:
33
+ continue
34
+
35
+ # Split the line into sentences (using '.', '!', or '?' as delimiters)
36
+ sentences = re.split(r'[.!?]', line)
37
+
38
+ for sentence in sentences:
39
+ sentence = sentence.strip()
40
+ if sentence:
41
+ all_sentences.append(sentence)
42
+ total_sentences += 1
43
+
44
+ # Update longest and shortest sentences
45
+ if len(sentence) > len(longest_sentence):
46
+ longest_sentence = sentence
47
+ if shortest_sentence is None or len(sentence) < len(shortest_sentence):
48
+ shortest_sentence = sentence
49
+
50
+ # Tokenize and count words
51
+ words = tokenize(sentence)
52
+ word_count.update(words)
53
+
54
+ # Get the most common words
55
+ most_common_words = word_count.most_common(10)
56
+ print(f"Most Common Words: {most_common_words}")
57
+
58
+
59
+ def get_minhash(text, num_perm=128):
60
+ """
61
+ Generate a MinHash for a given text.
62
+ """
63
+ tokens = set(text.split())
64
+ m = MinHash(num_perm=num_perm)
65
+ for token in tokens:
66
+ m.update(token.encode('utf8'))
67
+ return m
68
+
69
+
70
+ def minhash_deduplication(docs, threshold=0.8, num_perm=128):
71
+ """
72
+ Remove near-duplicate documents using MinHash LSH.
73
+ """
74
+ lsh = MinHashLSH(threshold=threshold, num_perm=num_perm)
75
+ unique_docs = []
76
+
77
+ for i, doc in enumerate(docs):
78
+ m = get_minhash(doc, num_perm=num_perm)
79
+ if not lsh.query(m): # Check if the document is a near duplicate
80
+ lsh.insert(i, m)
81
+ unique_docs.append(doc)
82
+
83
+ return unique_docs
84
+
85
+
86
+ unique_docs = minhash_deduplication(all_sentences, threshold=0.8)
87
+ print(f"Number of unique documents: {len(unique_docs)}")
88
+
89
+ # Language detection
90
+ detector = LanguageDetectorBuilder.from_languages(*Language.all()).build()
91
+ labels = []
92
+ cleaned_text = []
93
+
94
+ for s in unique_docs:
95
+ l = detector.detect_language_of(s)
96
+ if not l:
97
+ print(f"Could not detect language for sentence: {s}")
98
+ else:
99
+ labels.append(l.name)
100
+ cleaned_text.append(s)
101
+
102
+ # Create a DataFrame with the cleaned text
103
+ df = pd.DataFrame({'text': cleaned_text})