lingjzhu commited on
Commit
a75cfd0
1 Parent(s): 65b6206

Upload generate_triplets.py

Browse files
Files changed (1) hide show
  1. generate_triplets.py +68 -0
generate_triplets.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import itertools
3
+ from datasets import load_dataset, load_from_disk, Dataset
4
+ import re
5
+ from tqdm import tqdm
6
+ import sys
7
+
8
+ def clean_markdown(text):
9
+ text = re.sub(r'<.*?>','',text)
10
+ text = re.sub(r'\n+','',text)
11
+ text = text.replace('#','')
12
+ return text
13
+
14
+
15
+ def parse_data(ds):
16
+ """Parse data into markdown-code pairs"""
17
+
18
+ for notebook in tqdm(ds):
19
+
20
+ types = notebook["cell_types"]
21
+ cells = notebook["cells"]
22
+
23
+ if len(types)>0:
24
+ if types[0] == "code":
25
+ # drop first cell of code to have the notebook start with markdown
26
+ cells = cells[1:]
27
+ types = types[1:]
28
+ #else:
29
+ # drop first the two cells of markdown followed by code
30
+ # the first markown cell of a notebook is often a long description of the whole notebook
31
+ # cells = notebooks["cells"][2:]
32
+ # types = notebooks["types"][2:]
33
+ if len(types)>0:
34
+ if types[-1] == 'markdown':
35
+ cells = cells[:-1]
36
+ types = types[:-1]
37
+
38
+ if len(cells) % 2 == 0:
39
+ inner_markdowns = [cells[j] for j in range(len(cells)) if j % 2 == 0]
40
+ inner_code_snippets = [cells[j+1] for j in range(len(cells) - 1) if j % 2 == 0]
41
+
42
+
43
+ for markdown_block, code_snippet in zip(inner_markdowns,inner_code_snippets):
44
+ markdown_block = ' '.join([clean_markdown(block[0]) for block in markdown_block])
45
+ code = '\n'.join([snippet[0] for snippet in code_snippet])
46
+ output = [snippet[1] for snippet in code_snippet][-1]
47
+
48
+ line = {'markdown':markdown_block,
49
+ 'code':code,
50
+ 'output':output,
51
+ 'license':notebook['max_issues_repo_licenses'][0],
52
+ 'path':notebook['max_stars_repo_path'],
53
+ 'repo_name':notebook['max_stars_repo_name'],
54
+ }
55
+ yield line
56
+
57
+
58
+ if __name__ == "__main__":
59
+ file = sys.argv[1]
60
+
61
+ dataset = load_dataset("bigcode/jupyter-parsed")
62
+ with open(file,'w') as out:
63
+ for line in parse_data(data):
64
+ out.write(json.dumps(line)+'\n')
65
+
66
+ dataset = load_dataset('json',ata_files=file)
67
+
68
+ dataset.push_to_hub("bigcode/jupyter-code-text-pairs")