eckendoerffer commited on
Commit
c73141b
1 Parent(s): 468fffe

Upload explore_dataset.py

Browse files
Files changed (1) hide show
  1. explore_dataset.py +77 -0
explore_dataset.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_news_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
+
41
+ def get_line(file_path, line_number, index, i):
42
+ """
43
+ Fetches a specific line from the dataset using the provided index.
44
+ """
45
+ with open(file_path, 'r', encoding='utf-8') as f:
46
+ if shift_one:
47
+ f.seek(index[line_number] + line_number)
48
+ else:
49
+ f.seek(index[line_number])
50
+ text = f.readline()
51
+
52
+ show = f"{i}) {text}\n"
53
+ show += ' ' + '-'*220 + '\n'
54
+ return show
55
+
56
+ # Build index if it doesn't exist
57
+ if not os.path.exists(path_index):
58
+ build_index()
59
+
60
+ # Load the index file
61
+ with open(path_index, 'r') as file:
62
+ index = json.load(file)
63
+
64
+ # Display 10 random lines from the dataset
65
+ for i in range(10):
66
+ print(get_line(path_dataset, random.randint(0, len(index)-1), index, i+1))
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+