eckendoerffer commited on
Commit
6fabaef
1 Parent(s): 4b9805b

Upload explore_dataset.py

Browse files

Random Line Fetcher for Large Datasets

Files changed (1) hide show
  1. explore_dataset.py +78 -0
explore_dataset.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """
4
+ Random Line Fetcher for Large Datasets
5
+
6
+ This script allows users to randomly fetch and display lines from a large dataset.
7
+ An index file is created to keep track of the positions of each line in the dataset,
8
+ allowing for efficient random line retrieval.
9
+
10
+ Author : Guillaume Eckendoerffer
11
+ Date : 06-07-23
12
+ Repository : https://github.com/Eckendoerffer/TorchTrainerFlow/
13
+ """
14
+
15
+ import os
16
+ import random
17
+ import json
18
+
19
+ # Path configurations
20
+ path = os.path.dirname(os.path.abspath(__file__))
21
+ path_dataset = os.path.join(path, "train.txt")
22
+ path_index = os.path.join(path, "dataset_wiki_index.txt") # Index file
23
+
24
+ # Flag to determine if an offset of one byte should be applied
25
+ shift_one = True
26
+
27
+ def build_index():
28
+ """
29
+ Constructs an index for the dataset where each line's starting position is stored.
30
+ """
31
+ index = []
32
+ with open(path_dataset, 'r', encoding='utf-8') as f:
33
+ offset = 0
34
+ for line in f:
35
+ index.append(offset)
36
+ offset += len(line.encode('utf-8'))
37
+
38
+ with open(path_index, 'w', encoding="utf8") as f:
39
+ json.dump(index, f)
40
+ return index
41
+
42
+ def get_line(file_path, line_number, index, i):
43
+ """
44
+ Fetches a specific line from the dataset using the provided index.
45
+ """
46
+ with open(file_path, 'r', encoding='utf-8') as f:
47
+ if shift_one:
48
+ f.seek(index[line_number] + line_number)
49
+ else:
50
+ f.seek(index[line_number])
51
+ text = f.readline()
52
+
53
+ show = f"{i}) {text}\n"
54
+ show += ' ' + '-'*220 + '\n'
55
+ return show
56
+
57
+ # Build index if it doesn't exist
58
+ if not os.path.exists(path_index):
59
+ index = build_index()
60
+
61
+ # Load the index file
62
+ with open(path_index, 'r', encoding='utf-8') as file:
63
+ index = json.load(file)
64
+
65
+ # Display 10 random lines from the dataset
66
+ for i in range(10):
67
+ print(get_line(path_dataset, random.randint(0, len(index)-1), index, i+1))
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+