forked from THUDM/WebGLM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdownload.py
More file actions
145 lines (122 loc) · 5.78 KB
/
download.py
File metadata and controls
145 lines (122 loc) · 5.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import argparse
import os
import re
from tqdm import tqdm
import requests
import json, argparse
sess = requests.Session()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--link', '-l', type=str, required=True, help='Share link of Tsinghua Cloud')
parser.add_argument('--password', '-p', type=str, default='', help='Password of the share link')
parser.add_argument('--save', '-s', type=str, default='./', help='Save directory')
parser.add_argument('--file', '-f', type=str, default=None, help='File name, support regex, if not set, download all files')
return parser.parse_args()
def get_share_key(url):
prefix = 'https://cloud.tsinghua.edu.cn/d/'
if not url.startswith(prefix):
raise ValueError('Share link of Tsinghua Cloud should start with {}'.format(prefix))
share_key = url[len(prefix):].replace('/', '')
print('Share key: {}'.format(share_key))
return share_key
def dfs_search_files(share_key: str, path="/"):
global sess
filelist = []
print('https://cloud.tsinghua.edu.cn/api/v2.1/share-links/{}/dirents/?path={}'.format(share_key, path))
r = sess.get('https://cloud.tsinghua.edu.cn/api/v2.1/share-links/{}/dirents/?path={}'.format(share_key, path))
objects = r.json()['dirent_list']
for obj in objects:
if obj["is_dir"]:
filelist += dfs_search_files(share_key, obj['folder_path'])
else:
filelist.append(obj)
return filelist
def download_single_file(url: str, fname: str):
global sess
resp = sess.get(url, stream=True)
total = int(resp.headers.get('content-length', 0))
dir_name = os.path.dirname(fname)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
with open(fname, 'wb') as file, tqdm(
total=total,
ncols=120,
unit='iB',
unit_scale=True,
unit_divisor=1024,
) as bar:
for data in resp.iter_content(chunk_size=1024):
size = file.write(data)
bar.update(size)
def download(url, save_dir):
share_key = get_share_key(url)
print("Searching for files to be downloaded...")
search_files = dfs_search_files(share_key)
# for file in search_files:
# print(file['is_dir'], file.keys())
filelist = sorted(search_files, key=lambda x: x['file_path'])
print("Found {} files in the share link.".format(len(filelist)))
print("Last Modified Time".ljust(25), " ", "File Size".rjust(10), " ", "File Path")
print("-" * 100)
for file in filelist:
print(file["last_modified"], " ", str(file["size"]).rjust(10), " ", file["file_path"])
print("-" * 100)
if not args.yes:
while True:
key = input("Start downloading? [y/n]")
if key == 'y':
break
elif key == 'n':
return
flag = True
for i, file in enumerate(filelist):
file_url = 'https://cloud.tsinghua.edu.cn/d/{}/files/?p={}&dl=1'.format(share_key, file["file_path"])
save_path = os.path.join(save_dir, file["file_path"][1:])
if not os.path.exists(save_dir):
os.makedirs(save_dir)
print("[{}/{}] Downloading File: {}".format(i + 1, len(filelist), save_path))
try:
download_single_file(file_url, save_path)
except Exception as e:
print("Error happened when downloading file: {}".format(save_path))
print(e)
flag = False
if flag:
print("Download finished.")
else:
print("Download finished with error.")
return flag
def make_data(sample):
src = ""
for ix, ref in enumerate(sample['references']):
src += "Reference [%d]: %s\\" % (ix+1, ref)
src += "Question: %s\\Answer:" % (sample['question'])
source = src.replace("\n", " ").replace("\r", " ")
target = sample['answer'].replace("\n"," ").replace("\r", " ")
return source, target
if __name__ == "__main__":
arg = argparse.ArgumentParser()
arg.add_argument('target', type=str, choices=["generator-training-data", "retriever-training-data", "retriever-pretrained-checkpoint", "all"], help='Target to download')
arg.add_argument('--save', '-s', type=str, default='./download', help='Save directory')
arg.add_argument("-y", "--yes", action="store_true", help="Download without confirmation")
args = arg.parse_args()
if args.target in ["all", "generator-training-data"]:
save_dir = os.path.join(args.save, 'generator-training-data', 'raw')
if download('https://cloud.tsinghua.edu.cn/d/d290dcfc92e342f9a017/', save_dir):
for split in ['train', 'val', 'test']:
ds = [json.loads(data) for data in open(f'{save_dir}/{split}.jsonl').readlines()]
processed_dir = os.path.join(args.save, 'generator-training-data', 'processed')
if not os.path.exists(processed_dir):
os.makedirs(processed_dir)
source_out = open(os.path.join(processed_dir, f'{split}.source'), 'w')
target_out = open(os.path.join(processed_dir, f'{split}.target'), 'w')
for sample in tqdm(ds):
source, target = make_data(sample)
source_out.write(source + '\n')
target_out.write(target + '\n')
source_out.close()
target_out.close()
if args.target in ["all", "retriever-training-data"]:
download("https://cloud.tsinghua.edu.cn/d/3927b67a834c475288e2/", os.path.join(args.save, 'retriever-training-data'))
if args.target in ["all", "retriever-pretrained-checkpoint"]:
download("https://cloud.tsinghua.edu.cn/d/bc96946dd9a14c84b8d4/", os.path.join(args.save, 'retriever-pretrained-checkpoint'))