hahunavth commited on
Commit
2a8b18d
β€’
1 Parent(s): 7f9f741

update source

Browse files
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ tmp
.idea/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
.idea/inspectionProfiles/profiles_settings.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
.idea/kaggle-utils.iml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$" />
5
+ <orderEntry type="inheritedJdk" />
6
+ <orderEntry type="sourceFolder" forTests="false" />
7
+ </component>
8
+ </module>
.idea/misc.xml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="Black">
4
+ <option name="sdkName" value="vlsp2023-tts-api" />
5
+ </component>
6
+ <component name="ProjectRootManager" version="2" project-jdk-name="vlsp2023-tts-api" project-jdk-type="Python SDK" />
7
+ </project>
.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/kaggle-utils.iml" filepath="$PROJECT_DIR$/.idea/kaggle-utils.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
cli.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from types import SimpleNamespace
4
+
5
+ from kaggle_service import KernelRerunService, NbJob
6
+ import argparse
7
+ from logger import sheet_logger
8
+
9
+
10
+ def main(args):
11
+ if not os.path.exists(args.config):
12
+ print(f"Config folder not found: {os.path.abspath(args.config)}")
13
+ exit(1)
14
+
15
+ configs = []
16
+ if os.path.isdir(args.config):
17
+ files = os.listdir(args.config)
18
+ for file in files:
19
+ with open(os.path.join(args.config, file), "r") as f:
20
+ obj = json.loads(f.read())
21
+ configs.append(obj)
22
+ print(obj)
23
+ elif os.path.isfile(args.config):
24
+ with open(args.config, "r") as f:
25
+ obj = json.loads(f.read())
26
+ configs.append(obj)
27
+ print(obj)
28
+
29
+ service = KernelRerunService()
30
+ for config in configs:
31
+ service.add_job(NbJob.from_dict(config))
32
+
33
+ if args.option == "run":
34
+ service.run_all()
35
+ elif args.option == "validate":
36
+ service.validate_all()
37
+ elif args.option == "status":
38
+ service.status_all()
39
+ else:
40
+ print(f"Invalid option: {args.option}")
41
+
42
+
43
+ if __name__ == "__main__":
44
+ # parser = argparse.ArgumentParser()
45
+ # parser.add_argument("option", type=str, default="run", choices=["run", "validate", "status"])
46
+ # parser.add_argument("--config", type=str, default="./config")
47
+ #
48
+ # args = parser.parse_args()
49
+ args = SimpleNamespace(option="validate", config='./config')
50
+
51
+ main(args)
config/aasist-train.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "accounts": {
3
+ "hahunavth": "fb3d65ea4d06f91a83cf571e9a39d40d",
4
+ "mrhakk": "26780db435523a697855d5d13355744d",
5
+ "havthust": "c54e96568075fcc277bd10ba0e0a52b9"
6
+ },
7
+ "slug": "hahunavth/vlsp-sv-2023-aasist-train"
8
+ }
credentials.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "service_account",
3
+ "project_id": "vlsp2023-tts-api",
4
+ "private_key_id": "411335f1452da99ac34dbaeaaea212dab3ff2400",
5
+ "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQClPtZ/kYuBkYrP\nzbfJ/ye2DmHm4xt2o0Fvdqnuddri63662YA0GmQ+3RpH/yMg4b9Kgcyl0GXJ6Q6r\nZZzdueg3Edx5B9DkBWgYkPaTLFFe5XXOj1w2vgzc8UBN5+oomzS/WaTCpKmrs/D1\nVi05jt7Uo9mrALUkPD8wr2D9vkXQdM1G4NNxuFWCDoAF0MoVKcS5Le3f6bH4OgpL\nl5BniW4sh/UCLcWrWfXS6tuzK+8z/L6AI1ezNUJHlt58AzLjLi5Q8fOdeXviJT60\nf4w22W4gtY5YHdVCG7b7frM7ig6V9bWyVvHjGWqVkmXjYepOCIWnwQHVqja6NpVg\nR45HForBAgMBAAECggEATeqhTamdNE0iPPXtcWvEl82UUEBKFNjJ4/r6CZy8xz7v\nlL81+ltvZUzwNX6SW9DWWBV4H79yH5CrABp7qvkcC8t6P/91ee8qtFq2SZMeEzbz\nI6DphE581jlTbuiputfkOU3VqInoDzRbq/Mkg/1gCLfxzPYac6mMyjIH892iIbYP\nhlexZiXhZWRLqGFu9J3JHQAjlAtCxjhb/vBXkxzxO2j1MXv7BNrp6t7MAgFvX57k\ngRfIg/rmWohHni/NxQgWWQqTydy2JvxEVUUdPr2hgWF7hHgMk4WFbb7hzy6wH/T3\nMcjd5OHMHZcBF/NgrnxMD9NRuhD1cSbSNETJVTt9WQKBgQDS9I3MGOz5/j+jkWY7\n4CdjbbLCgat9RvvyBAkSonogLhVap1/jfKK4XQz1+aDFFY9YWW4MX/hCxKWOM5Fw\nnvDka/m2yjxha66ismflDdxvpfcjAvAt6WNX6cbiPNxFBkpJXQRH55ug9a9PKjXY\nUtc7ZOM5R/NyxfsqPjNm01faVwKBgQDIh6X0ypwCKr0CF8GP7gYPfVeK1Zh22s21\neIOEyGLB40HWOsi+PQxQHkva8teVaGMPKqppdxjs+d26d3h4Lo1rSYQrF9x+BoGm\nUU+d+3vfp1aLOj3VHMIKHKrQVOF0JSy/VdYFkz6vu6nFy3n4WdLg0XXFIQTS4Z+d\nFAD81nhEpwKBgQCqI9WNa/kNM7MuACH9Xq9F8P7BA4ZFVw/yxLBwmBx5gdF1ORMM\nTcSLf3jpljjFW7suHYq1bl2ztBh2lT7TH03YXQGdHIUQaaIC1HMY+VH1tlyZn1AJ\nJ3gZOpJOe5mIDiex/dRrDfCmJCENb1TYMRAodhkRZOeDhQwqqNoaL5BmpwKBgQCM\nWMQB67v8mETorg++2GxNcwBOHugyZzkKBWqnCEh2QsPVWBcfbkKr4Ehe2Q+hdgm+\nl7HlVoGPeeGBnBQoqQw5Rp7GOlELsyoSaV47x8MO6WNc1kpoWVRFF4NFg+K3Ez2a\nPE0qYb/B5qoP0TVwaA17Y531dgKWRWsc2N9IFiLeiQKBgQDNc2ygLHTkAKmqltcF\nzcccEnUTabPHvFkt6qycmx6oOrF6IXr1/x9ODZnwo/2JD5H/Mbub47M2k3I+BDdW\nwb0ETSEW3rdrtk85yPx3eVDIVtHoEr/Zhr9a9EYK+V8uAku3UM0L0TrnHtgqbM0W\nyGvFQOUt1hYxgoydw/Lx7h+1dA==\n-----END PRIVATE KEY-----\n",
6
+ "client_email": "[email protected]",
7
+ "client_id": "102309854252079057442",
8
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
9
+ "token_uri": "https://oauth2.googleapis.com/token",
10
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
11
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/hahunavth%40vlsp2023-tts-api.iam.gserviceaccount.com",
12
+ "universe_domain": "googleapis.com"
13
+ }
google_sheet.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gspread
2
+ from oauth2client.service_account import ServiceAccountCredentials
3
+ from typing import Dict
4
+
5
+ class SheetCRUDRepository:
6
+ def __init__(self, worksheet):
7
+ self.worksheet = worksheet
8
+ self.titles = self.worksheet.row_values(1) # Assuming titles are in the first row
9
+ assert len(set(self.titles)) == len(self.titles), f"Failed to init {SheetCRUDRepository.__class__}, titles: {self.titles} contain duplicated values!"
10
+
11
+ def create(self, data: Dict):
12
+ values = [data.get(title, '') for title in self.titles]
13
+ self.worksheet.append_row(values)
14
+
15
+ def read(self, row_index: int) -> Dict:
16
+ """
17
+ return {} if empty
18
+ """
19
+ values = self.worksheet.row_values(row_index)
20
+ return {title: value for title, value in zip(self.titles, values)}
21
+
22
+ def update(self, row_index: int, data: Dict):
23
+ values = [data.get(title, '') for title in self.titles]
24
+ self.worksheet.update(f"A{row_index}:Z{row_index}", [values])
25
+
26
+ def delete(self, row_index: int):
27
+ self.worksheet.delete_row(row_index)
28
+
29
+ def find(self, search_dict):
30
+ for col_title, value in search_dict.items():
31
+ if col_title in self.titles:
32
+ col_index = self.titles.index(col_title) + 1 # Adding 1 to match gspread indexing
33
+ cell = self.worksheet.find(value, in_column=col_index)
34
+ if cell is None:
35
+ break
36
+ row_number = cell.row
37
+ return row_number, self.read(row_number)
38
+ return None
39
+
40
+ def create_repositories():
41
+ scope = [
42
+ 'https://www.googleapis.com/auth/spreadsheets',
43
+ 'https://www.googleapis.com/auth/drive'
44
+ ]
45
+ creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
46
+ client = gspread.authorize(creds)
47
+ # sheet_url = "https://docs.google.com/spreadsheets/d/17OxKF0iP_aJJ0HCgJkwFsH762EUrtcEIYcPmyiiKnaM"
48
+ sheet_url = "https://docs.google.com/spreadsheets/d/1KzUYgWwbvYXGfyehOTyZCCQf0udZiwVXxaxpmkXEe3E/edit?usp=sharing"
49
+ sheet = client.open_by_url(sheet_url)
50
+
51
+ config_repository = SheetCRUDRepository(sheet.get_worksheet(0))
52
+ log_repository = SheetCRUDRepository(sheet.get_worksheet(1))
53
+ return config_repository, log_repository
54
+
55
+
56
+ conf_repo, log_repo = create_repositories()
57
+
58
+
59
+ if __name__ == "__main__":
60
+ a = create_repositories()
61
+ print(a)
kaggle_service.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from typing import Callable, List, Union, Dict
4
+
5
+ # fake default account to use kaggle.api.kaggle_api_extended
6
+ os.environ['KAGGLE_USERNAME']=''
7
+ os.environ['KAGGLE_KEY']=''
8
+
9
+ from kaggle.api.kaggle_api_extended import KaggleApi
10
+ from kaggle.rest import ApiException
11
+ import shutil
12
+ import time
13
+ import threading
14
+ import copy
15
+ from logger import sheet_logger
16
+
17
+
18
+ def get_api():
19
+ api = KaggleApi()
20
+ api.authenticate()
21
+ return api
22
+
23
+
24
+ class KaggleApiWrapper(KaggleApi):
25
+ """
26
+ Override KaggleApi.read_config_environment to use username and secret without environment variables
27
+ """
28
+
29
+ def __init__(self, username, secret):
30
+ super().__init__()
31
+ self.username = username
32
+ self.secret = secret
33
+
34
+ def read_config_environment(self, config_data=None, quiet=False):
35
+ config = super().read_config_environment(config_data, quiet)
36
+ config['username'] = self.username
37
+ config['key'] = self.secret
38
+ config['proxy'] = "http://proxy.server:3128"
39
+
40
+ return config_data
41
+
42
+ def __del__(self):
43
+ # todo: fix bug when delete api
44
+ pass
45
+
46
+
47
+ class KaggleNotebook:
48
+ def __init__(self, api: KaggleApi, kernel_slug: str, container_path: str = "./tmp"):
49
+ """
50
+ :param api: KaggleApi
51
+ :param kernel_slug: Notebook id, you can find it in the url of the notebook.
52
+ For example, `username/notebook-name-123456`
53
+ :param container_path: Path to the local folder where the notebook will be downloaded
54
+ """
55
+ self.api = api
56
+ self.kernel_slug = kernel_slug
57
+ self.container_path = container_path
58
+
59
+ def status(self) -> str or None:
60
+ """
61
+ :return:
62
+ "running"
63
+ "cancelAcknowledged"
64
+ "queued": waiting for run
65
+ "error": when raise exception in notebook
66
+ Throw exception when failed
67
+ """
68
+ res = self.api.kernels_status(self.kernel_slug)
69
+ print(f"Status: {res}")
70
+ if res is None:
71
+ return None
72
+ return res['status']
73
+
74
+ def _get_local_nb_path(self) -> str:
75
+ return os.path.join(self.container_path, self.kernel_slug)
76
+
77
+ def pull(self, path=None) -> str or None:
78
+ """
79
+
80
+ :param path:
81
+ :return:
82
+ :raises: ApiException if notebook not found or not share to user
83
+ """
84
+ self._clean()
85
+ path = path or self._get_local_nb_path()
86
+ metadata_path = os.path.join(path, "kernel-metadata.json")
87
+ res = self.api.kernels_pull(self.kernel_slug, path=path, metadata=True, quiet=False)
88
+ if not os.path.exists(metadata_path):
89
+ print(f"Warn: Not found {metadata_path}. Clean {path}")
90
+ self._clean()
91
+ return None
92
+ return res
93
+
94
+ def push(self, path=None) -> str or None:
95
+ status = self.status()
96
+ if status in ['queued', 'running']:
97
+ print("Warn: Notebook is " + status + ". Skip push notebook!")
98
+ return None
99
+
100
+ self.api.kernels_push(path or self._get_local_nb_path())
101
+ time.sleep(1)
102
+ status = self.status()
103
+ return status
104
+
105
+ def _clean(self) -> None:
106
+ if os.path.exists(self._get_local_nb_path()):
107
+ shutil.rmtree(self._get_local_nb_path())
108
+
109
+ def get_metadata(self, path=None):
110
+ path = path or self._get_local_nb_path()
111
+ metadata_path = os.path.join(path, "kernel-metadata.json")
112
+ if not os.path.exists(metadata_path):
113
+ return None
114
+ return json.loads(open(metadata_path).read())
115
+
116
+ def check_nb_permission(self) -> Union[tuple[bool], tuple[bool, None]]:
117
+ try:
118
+ status = self.status()
119
+ if status is None:
120
+ return False, status
121
+ return True, status
122
+ except ApiException as e:
123
+ print(f"Error: {e.status} {e.reason} with notebook {self.kernel_slug}")
124
+ return False, None
125
+
126
+ def check_datasets_permission(self) -> bool:
127
+ meta = self.get_metadata()
128
+ if meta is None:
129
+ print("Warn: cannot get metadata. Pull and try again?")
130
+ dataset_sources = meta['dataset_sources']
131
+ for dataset in dataset_sources:
132
+ try:
133
+ self.api.dataset_status(dataset)
134
+ except ApiException as e:
135
+ print(f"Error: {e.status} {e.reason} with dataset {dataset} in notebook {self.kernel_slug}")
136
+ return False
137
+ return True
138
+
139
+
140
+ class AccountTransactionManager:
141
+ def __init__(self, acc_secret_dict: dict=None):
142
+ """
143
+ :param acc_secret_dict: {username: secret}
144
+ """
145
+ self.acc_secret_dict = acc_secret_dict
146
+ if self.acc_secret_dict is None:
147
+ self.acc_secret_dict = {}
148
+ # self.api_dict = {username: KaggleApiWrapper(username, secret) for username, secret in acc_secret_dict.items()}
149
+ # lock for each account to avoid concurrent use api
150
+ self.lock_dict = {username: False for username in self.acc_secret_dict.keys()}
151
+ self.state_lock = threading.Lock()
152
+
153
+ def _get_api(self, username: str) -> KaggleApiWrapper:
154
+ # return self.api_dict[username]
155
+ return KaggleApiWrapper(username, self.acc_secret_dict[username])
156
+
157
+ def _get_lock(self, username: str) -> bool:
158
+ return self.lock_dict[username]
159
+
160
+ def _set_lock(self, username: str, lock: bool) -> None:
161
+ self.lock_dict[username] = lock
162
+
163
+ def add_account(self, username, secret):
164
+ if username not in self.acc_secret_dict.keys():
165
+ self.state_lock.acquire()
166
+ self.acc_secret_dict[username] = secret
167
+ self.lock_dict[username] = False
168
+ self.state_lock.release()
169
+
170
+ def remove_account(self, username):
171
+ if username in self.acc_secret_dict.keys():
172
+ self.state_lock.acquire()
173
+ del self.acc_secret_dict[username]
174
+ del self.lock_dict[username]
175
+ self.state_lock.release()
176
+ else:
177
+ print(f"Warn: try to remove account not in the list: {username}, list: {self.acc_secret_dict.keys()}")
178
+
179
+ def get_unlocked_api_unblocking(self, username_list: List[str]) -> tuple[KaggleApiWrapper, Callable[[], None]]:
180
+ """
181
+ :param username_list: list of username
182
+ :return: (api, release) where release is a function to release api
183
+ """
184
+ while True:
185
+ print("get_unlocked_api_unblocking" + str(username_list))
186
+ for username in username_list:
187
+ self.state_lock.acquire()
188
+ if not self._get_lock(username):
189
+ self._set_lock(username, True)
190
+ api = self._get_api(username)
191
+
192
+ def release():
193
+ self.state_lock.acquire()
194
+ self._set_lock(username, False)
195
+ api.__del__()
196
+ self.state_lock.release()
197
+
198
+ self.state_lock.release()
199
+ return api, release
200
+ self.state_lock.release()
201
+ time.sleep(1)
202
+
203
+
204
+ class NbJob:
205
+ def __init__(self, acc_dict: dict, nb_slug: str, rerun_stt: List[str] = None, not_rerun_stt: List[str] = None):
206
+ """
207
+
208
+ :param acc_dict:
209
+ :param nb_slug:
210
+ :param rerun_stt:
211
+ :param not_rerun_stt: If notebook status in this list, do not rerun it. (Note: do not add "queued", "running")
212
+ """
213
+ self.rerun_stt = rerun_stt
214
+ if self.rerun_stt is None:
215
+ self.rerun_stt = ['complete']
216
+ self.not_rerun_stt = not_rerun_stt
217
+
218
+ if self.not_rerun_stt is None:
219
+ self.not_rerun_stt = ['queued', 'running', 'cancelAcknowledged']
220
+ assert "queued" in self.not_rerun_stt
221
+ assert "running" in self.not_rerun_stt
222
+
223
+ self.acc_dict = acc_dict
224
+ self.nb_slug = nb_slug
225
+
226
+ def get_acc_dict(self):
227
+ return self.acc_dict
228
+
229
+ def get_username_list(self):
230
+ return list(self.acc_dict.keys())
231
+
232
+ def is_valid_with_acc(self, api):
233
+ notebook = KaggleNotebook(api, self.nb_slug)
234
+ try:
235
+ notebook.pull()
236
+ except ApiException as e:
237
+ return False
238
+ stt, _ = notebook.check_nb_permission()
239
+ if not stt:
240
+ return False
241
+ stt = notebook.check_datasets_permission()
242
+ if not stt:
243
+ return False
244
+ return True
245
+
246
+ def is_valid(self):
247
+ for username in self.acc_dict.keys():
248
+ secrets = self.acc_dict[username]
249
+ api = KaggleApiWrapper(username=username, secret=secrets)
250
+ api.authenticate()
251
+ if not self.is_valid_with_acc(api):
252
+ return False
253
+ return True
254
+
255
+ def acc_check_and_rerun_if_need(self, api: KaggleApi) -> bool:
256
+ """
257
+ :return:
258
+ True if rerun success or notebook is running
259
+ False user does not have enough gpu quotas
260
+ :raises
261
+ Exception if setup error
262
+ """
263
+ notebook = KaggleNotebook(api, self.nb_slug, "./tmp") # todo: change hardcode container_path here
264
+
265
+ notebook.pull()
266
+ assert notebook.check_datasets_permission(), f"User {api} does not have permission on datasets of notebook {self.nb_slug}"
267
+ success, status1 = notebook.check_nb_permission()
268
+ assert success, f"User {api} does not have permission on notebook {self.nb_slug}" # todo: using api.username
269
+
270
+ if status1 in self.rerun_stt:
271
+ status2 = notebook.push()
272
+ time.sleep(10)
273
+ status3 = notebook.status()
274
+
275
+ # if 3 times same stt -> acc out of quota
276
+ if status1 == status2 == status3:
277
+ sheet_logger.log(username=api.username, nb=self.nb_slug, log="Try but no effect. Seem account to be out of quota")
278
+ return False
279
+ if status3 in self.not_rerun_stt:
280
+ sheet_logger.log(username=api.username, nb=self.nb_slug, log=f"Notebook is in ignore status list {self.not_rerun_stt}, do nothing!")
281
+ return True
282
+ if status3 not in ["queued", "running"]:
283
+ # return False # todo: check when user is out of quota
284
+ print(f"Error: status is {status3}")
285
+ raise Exception("Setup exception")
286
+ sheet_logger.log(username=api.username, nb=self.nb_slug,
287
+ log=f"Schedule notebook successfully. Current status is '{status3}'")
288
+ return True
289
+
290
+ sheet_logger.log(username=api.username, nb=self.nb_slug, log=f"Notebook status is '{status1}' is not in {self.rerun_stt}, do nothing!")
291
+ return True
292
+
293
+ @staticmethod
294
+ def from_dict(obj: dict):
295
+ return NbJob(acc_dict=obj['accounts'], nb_slug=obj['slug'], rerun_stt=obj.get('rerun_status'), not_rerun_stt=obj.get('not_rerun_stt'))
296
+
297
+
298
+ class KernelRerunService:
299
+ def __init__(self):
300
+ self.jobs: Dict[str, NbJob] = {}
301
+ self.acc_manager = AccountTransactionManager()
302
+ self.username2jobid = {}
303
+ self.jobid2username = {}
304
+
305
+ def add_job(self, nb_job: NbJob):
306
+ if nb_job.nb_slug in self.jobs.keys():
307
+ print("Warn: nb_job already in job list")
308
+ return
309
+ self.jobs[nb_job.nb_slug] = nb_job
310
+ self.jobid2username[nb_job.nb_slug] = nb_job.get_username_list()
311
+ for username in nb_job.get_username_list():
312
+ if username not in self.username2jobid.keys():
313
+ self.username2jobid[username] = []
314
+ self.acc_manager.add_account(username, nb_job.acc_dict[username])
315
+ self.username2jobid[username].append(nb_job.nb_slug)
316
+
317
+ def remove_job(self, nb_job):
318
+ if nb_job.nb_slug not in self.jobs.keys():
319
+ print("Warn: try to remove nb_job not in list")
320
+ return
321
+ username_list = self.jobid2username[nb_job.nb_slug]
322
+ username_list = [username for username in username_list if len(self.username2jobid[username]) == 1]
323
+
324
+ for username in username_list:
325
+ del self.username2jobid[username]
326
+ self.acc_manager.remove_account(username)
327
+ del self.jobs[nb_job.nb_slug]
328
+ del self.jobid2username[nb_job.nb_slug]
329
+
330
+ def validate_all(self):
331
+ for username in self.acc_manager.acc_secret_dict.keys():
332
+ api, release = self.acc_manager.get_unlocked_api_unblocking([username])
333
+ api.authenticate()
334
+ print(f"Using username: {api.username}")
335
+
336
+ for job in self.jobs.values():
337
+ if username in job.get_username_list():
338
+ print(f"Validate user: {username}, job: {job.nb_slug}")
339
+ if not job.is_valid_with_acc(api):
340
+ print(f"Error: not valid")
341
+ a = f"Setup error: {username} does not have permission on notebook {job.nb_slug} or related datasets"
342
+ raise Exception(a)
343
+ release()
344
+ return True
345
+
346
+ def status_all(self):
347
+ for job in self.jobs.values():
348
+ print(f"Job: {job.nb_slug}")
349
+ api, release = self.acc_manager.get_unlocked_api_unblocking(job.get_username_list())
350
+ api.authenticate()
351
+ print(f"Using username: {api.username}")
352
+ notebook = KaggleNotebook(api, job.nb_slug)
353
+ print(f"Notebook: {notebook.kernel_slug}")
354
+ print(notebook.status())
355
+ release()
356
+
357
+ def run(self, nb_job: NbJob):
358
+ username_list = copy.copy(nb_job.get_username_list())
359
+ while len(username_list) > 0:
360
+ api, release = self.acc_manager.get_unlocked_api_unblocking(username_list)
361
+ api.authenticate()
362
+ print(f"Using username: {api.username}")
363
+
364
+ try:
365
+ result = nb_job.acc_check_and_rerun_if_need(api)
366
+ if result:
367
+ return True
368
+ except Exception as e:
369
+ print(e)
370
+ release()
371
+ break
372
+
373
+ if api.username in username_list:
374
+ username_list.remove(api.username)
375
+ release()
376
+ else:
377
+ release()
378
+ raise Exception("")
379
+ return False
380
+
381
+ def run_all(self):
382
+ for job in self.jobs.values():
383
+ success = self.run(job)
384
+ print(f"Job: {job.nb_slug} {success}")
385
+
386
+
387
+ if __name__ == "__main__":
388
+ service = KernelRerunService()
389
+ files = os.listdir("./config")
390
+ for file in files:
391
+ if '.example' not in file:
392
+ with open(os.path.join("./config", file), "r") as f:
393
+ obj = json.loads(f.read())
394
+ print(obj)
395
+ service.add_job(NbJob.from_dict(obj))
396
+ service.run_all()
397
+
398
+ # try:
399
+ # acc_secret_dict = {
400
+ # "hahunavth": "secret",
401
+ # "hahunavth2": "secret",
402
+ # "hahunavth3": "secret",
403
+ # "hahunavth4": "secret",
404
+ # "hahunavth5": "secret",
405
+ # }
406
+ # acc_manager = AccountTransactionManager(acc_secret_dict)
407
+ #
408
+ #
409
+ # def test1():
410
+ # username_list = ["hahunavth", "hahunavth2", "hahunavth3", "hahunavth4", "hahunavth5"]
411
+ # while len(username_list) > 0:
412
+ # api, release = acc_manager.get_unlocked_api_unblocking(username_list)
413
+ # print("test1 is using " + api.username)
414
+ # time.sleep(1)
415
+ # release()
416
+ # if api.username in username_list:
417
+ # username_list.remove(api.username)
418
+ # else:
419
+ # raise Exception("")
420
+ # print("test1 release " + api.username)
421
+ #
422
+ #
423
+ # def test2():
424
+ # username_list = ["hahunavth2", "hahunavth3", "hahunavth5"]
425
+ # while len(username_list) > 0:
426
+ # api, release = acc_manager.get_unlocked_api_unblocking(username_list)
427
+ # print("test2 is using " + api.username)
428
+ # time.sleep(3)
429
+ # release()
430
+ # if api.username in username_list:
431
+ # username_list.remove(api.username)
432
+ # else:
433
+ # raise Exception("")
434
+ # print("test2 release " + api.username)
435
+ #
436
+ #
437
+ # t1 = threading.Thread(target=test1)
438
+ # t2 = threading.Thread(target=test2)
439
+ # t1.start()
440
+ # t2.start()
441
+ # t1.join()
442
+ # t2.join()
443
+ #
444
+ # # kgapi = KaggleApiWrapper("hahunavth", "fb3d65ea4d06f91a83cf571e9a39d40d")
445
+ # # kgapi.authenticate()
446
+ # # # kgapi = get_api()
447
+ # # notebook = KaggleNotebook(kgapi, "hahunavth/ess-vlsp2023-denoising", "./tmp")
448
+ # # # print(notebook.pull())
449
+ # # # print(notebook.check_datasets_permission())
450
+ # # print(notebook.check_nb_permission())
451
+ # # # print(notebook.status())
452
+ # # # notebook.push()
453
+ # # # print(notebook.status())
454
+ # except ApiException as e:
455
+ # print(e.status)
456
+ # print(e.reason)
457
+ # raise e
458
+ # # 403 when nb not exists or not share to acc
459
+ # # 404 when push to unknow kenel_slug.username
460
+ # # 401 when invalid username, pass
logger.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import platform,socket,re,uuid,json,psutil,logging
2
+ from datetime import datetime as dt
3
+ from google_sheet import log_repo
4
+
5
+
6
+ version="v1.0.0"
7
+
8
+
9
+ def get_sys_info():
10
+ try:
11
+ info={}
12
+ info['platform']=platform.system()
13
+ info['platform-release']=platform.release()
14
+ info['platform-version']=platform.version()
15
+ info['architecture']=platform.machine()
16
+ info['hostname']=socket.gethostname()
17
+ info['ip-address']=socket.gethostbyname(socket.gethostname())
18
+ info['mac-address']=':'.join(re.findall('..', '%012x' % uuid.getnode()))
19
+ info['processor']=platform.processor()
20
+ info['ram']=str(round(psutil.virtual_memory().total / (1024.0 **3)))+" GB"
21
+ return json.dumps(info)
22
+ except Exception as e:
23
+ logging.exception(e)
24
+
25
+
26
+ class SheetLogger:
27
+ def __init__(self, log_repo):
28
+ self.log_repo = log_repo
29
+
30
+ def log(self, log='', nb='', username=''):
31
+ self.log_repo.create({
32
+ "time": str(dt.now()),
33
+ "notebook_name": nb,
34
+ "kaggle_username": username,
35
+ "log": log,
36
+ "device": str(get_sys_info()),
37
+ "version": version
38
+ })
39
+
40
+ sheet_logger = SheetLogger(log_repo)
main.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from google_sheet import conf_repo
2
+ import json
3
+
4
+ from kaggle_service import KernelRerunService, NbJob
5
+ from logger import sheet_logger
6
+
7
+
8
+ # if __name__ == "__main__":
9
+ configs = []
10
+ try:
11
+ for i in range(2, 1000):
12
+ rs = conf_repo.read(i)
13
+ if not rs:
14
+ break
15
+ cfg = json.loads(rs['config'])
16
+ configs.append(cfg)
17
+ print(cfg)
18
+ except Exception as e:
19
+ sheet_logger.log(log="Get config failed!!")
20
+
21
+ service = KernelRerunService()
22
+ for config in configs:
23
+ service.add_job(NbJob.from_dict(config))
24
+
25
+ try:
26
+ service.validate_all()
27
+ service.status_all()
28
+ service.run_all()
29
+ except Exception as e:
30
+ sheet_logger.log(log=str(e))
31
+
merged_file.py ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gspread
2
+ from oauth2client.service_account import ServiceAccountCredentials
3
+ from typing import Dict
4
+
5
+
6
+ class SheetCRUDRepository:
7
+ def __init__(self, worksheet):
8
+ self.worksheet = worksheet
9
+ self.titles = self.worksheet.row_values(1) # Assuming titles are in the first row
10
+ assert len(set(self.titles)) == len(self.titles), f"Failed to init {SheetCRUDRepository.__class__}, titles: {self.titles} contain duplicated values!"
11
+
12
+ def create(self, data: Dict):
13
+ values = [data.get(title, '') for title in self.titles]
14
+ self.worksheet.append_row(values)
15
+
16
+ def read(self, row_index: int) -> Dict:
17
+ """
18
+ return {} if empty
19
+ """
20
+ values = self.worksheet.row_values(row_index)
21
+ return {title: value for title, value in zip(self.titles, values)}
22
+
23
+ def update(self, row_index: int, data: Dict):
24
+ values = [data.get(title, '') for title in self.titles]
25
+ self.worksheet.update(f"A{row_index}:Z{row_index}", [values])
26
+
27
+ def delete(self, row_index: int):
28
+ self.worksheet.delete_row(row_index)
29
+
30
+ def find(self, search_dict):
31
+ for col_title, value in search_dict.items():
32
+ if col_title in self.titles:
33
+ col_index = self.titles.index(col_title) + 1 # Adding 1 to match gspread indexing
34
+ cell = self.worksheet.find(value, in_column=col_index)
35
+ if cell is None:
36
+ break
37
+ row_number = cell.row
38
+ return row_number, self.read(row_number)
39
+ return None
40
+
41
+ def create_repositories():
42
+ scope = [
43
+ 'https://www.googleapis.com/auth/spreadsheets',
44
+ 'https://www.googleapis.com/auth/drive'
45
+ ]
46
+ creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
47
+ client = gspread.authorize(creds)
48
+ # sheet_url = "https://docs.google.com/spreadsheets/d/17OxKF0iP_aJJ0HCgJkwFsH762EUrtcEIYcPmyiiKnaM"
49
+ sheet_url = "https://docs.google.com/spreadsheets/d/1KzUYgWwbvYXGfyehOTyZCCQf0udZiwVXxaxpmkXEe3E/edit?usp=sharing"
50
+ sheet = client.open_by_url(sheet_url)
51
+
52
+ config_repository = SheetCRUDRepository(sheet.get_worksheet(0))
53
+ log_repository = SheetCRUDRepository(sheet.get_worksheet(1))
54
+ return config_repository, log_repository
55
+
56
+
57
+ conf_repo, log_repo = create_repositories()
58
+
59
+
60
+ import platform,socket,re,uuid,json,psutil,logging
61
+ from datetime import datetime as dt
62
+ from google_sheet import log_repo
63
+
64
+
65
+ version="v1.0.0"
66
+
67
+
68
+ def get_sys_info():
69
+ try:
70
+ info={}
71
+ info['platform']=platform.system()
72
+ info['platform-release']=platform.release()
73
+ info['platform-version']=platform.version()
74
+ info['architecture']=platform.machine()
75
+ info['hostname']=socket.gethostname()
76
+ info['ip-address']=socket.gethostbyname(socket.gethostname())
77
+ info['mac-address']=':'.join(re.findall('..', '%012x' % uuid.getnode()))
78
+ info['processor']=platform.processor()
79
+ info['ram']=str(round(psutil.virtual_memory().total / (1024.0 **3)))+" GB"
80
+ return json.dumps(info)
81
+ except Exception as e:
82
+ logging.exception(e)
83
+
84
+
85
+ class SheetLogger:
86
+ def __init__(self, log_repo):
87
+ self.log_repo = log_repo
88
+
89
+ def log(self, log='', nb='', username=''):
90
+ self.log_repo.create({
91
+ "time": str(dt.now()),
92
+ "notebook_name": nb,
93
+ "kaggle_username": username,
94
+ "log": log,
95
+ "device": str(get_sys_info()),
96
+ "version": version
97
+ })
98
+
99
+ sheet_logger = SheetLogger(log_repo)
100
+
101
+ import json
102
+ import os
103
+ from typing import Callable, List, Union, Dict
104
+
105
+ # fake default account to use kaggle.api.kaggle_api_extended
106
+ os.environ['KAGGLE_USERNAME']=''
107
+ os.environ['KAGGLE_KEY']=''
108
+
109
+ from kaggle.api.kaggle_api_extended import KaggleApi
110
+ from kaggle.rest import ApiException
111
+ import shutil
112
+ import time
113
+ import threading
114
+ import copy
115
+ from logger import sheet_logger
116
+
117
+
118
+ def get_api():
119
+ api = KaggleApi()
120
+ api.authenticate()
121
+ return api
122
+
123
+
124
+ class KaggleApiWrapper(KaggleApi):
125
+ """
126
+ Override KaggleApi.read_config_environment to use username and secret without environment variables
127
+ """
128
+
129
+ def __init__(self, username, secret):
130
+ super().__init__()
131
+ self.username = username
132
+ self.secret = secret
133
+
134
+ def read_config_environment(self, config_data=None, quiet=False):
135
+ config = super().read_config_environment(config_data, quiet)
136
+ config['username'] = self.username
137
+ config['key'] = self.secret
138
+
139
+ return config_data
140
+
141
+ def __del__(self):
142
+ # todo: fix bug when delete api
143
+ pass
144
+
145
+
146
+ class KaggleNotebook:
147
+ def __init__(self, api: KaggleApi, kernel_slug: str, container_path: str = "./tmp"):
148
+ """
149
+ :param api: KaggleApi
150
+ :param kernel_slug: Notebook id, you can find it in the url of the notebook.
151
+ For example, `username/notebook-name-123456`
152
+ :param container_path: Path to the local folder where the notebook will be downloaded
153
+ """
154
+ self.api = api
155
+ self.kernel_slug = kernel_slug
156
+ self.container_path = container_path
157
+
158
+ def status(self) -> str or None:
159
+ """
160
+ :return:
161
+ "running"
162
+ "cancelAcknowledged"
163
+ "queued": waiting for run
164
+ "error": when raise exception in notebook
165
+ Throw exception when failed
166
+ """
167
+ res = self.api.kernels_status(self.kernel_slug)
168
+ print(f"Status: {res}")
169
+ if res is None:
170
+ return None
171
+ return res['status']
172
+
173
+ def _get_local_nb_path(self) -> str:
174
+ return os.path.join(self.container_path, self.kernel_slug)
175
+
176
+ def pull(self, path=None) -> str or None:
177
+ """
178
+
179
+ :param path:
180
+ :return:
181
+ :raises: ApiException if notebook not found or not share to user
182
+ """
183
+ self._clean()
184
+ path = path or self._get_local_nb_path()
185
+ metadata_path = os.path.join(path, "kernel-metadata.json")
186
+ res = self.api.kernels_pull(self.kernel_slug, path=path, metadata=True, quiet=False)
187
+ if not os.path.exists(metadata_path):
188
+ print(f"Warn: Not found {metadata_path}. Clean {path}")
189
+ self._clean()
190
+ return None
191
+ return res
192
+
193
+ def push(self, path=None) -> str or None:
194
+ status = self.status()
195
+ if status in ['queued', 'running']:
196
+ print("Warn: Notebook is " + status + ". Skip push notebook!")
197
+ return None
198
+
199
+ self.api.kernels_push(path or self._get_local_nb_path())
200
+ time.sleep(1)
201
+ status = self.status()
202
+ return status
203
+
204
+ def _clean(self) -> None:
205
+ if os.path.exists(self._get_local_nb_path()):
206
+ shutil.rmtree(self._get_local_nb_path())
207
+
208
+ def get_metadata(self, path=None):
209
+ path = path or self._get_local_nb_path()
210
+ metadata_path = os.path.join(path, "kernel-metadata.json")
211
+ if not os.path.exists(metadata_path):
212
+ return None
213
+ return json.loads(open(metadata_path).read())
214
+
215
+ def check_nb_permission(self) -> Union[tuple[bool], tuple[bool, None]]:
216
+ try:
217
+ status = self.status()
218
+ if status is None:
219
+ return False, status
220
+ return True, status
221
+ except ApiException as e:
222
+ print(f"Error: {e.status} {e.reason} with notebook {self.kernel_slug}")
223
+ return False, None
224
+
225
+ def check_datasets_permission(self) -> bool:
226
+ meta = self.get_metadata()
227
+ if meta is None:
228
+ print("Warn: cannot get metadata. Pull and try again?")
229
+ dataset_sources = meta['dataset_sources']
230
+ for dataset in dataset_sources:
231
+ try:
232
+ self.api.dataset_status(dataset)
233
+ except ApiException as e:
234
+ print(f"Error: {e.status} {e.reason} with dataset {dataset} in notebook {self.kernel_slug}")
235
+ return False
236
+ return True
237
+
238
+
239
+ class AccountTransactionManager:
240
+ def __init__(self, acc_secret_dict: dict=None):
241
+ """
242
+ :param acc_secret_dict: {username: secret}
243
+ """
244
+ self.acc_secret_dict = acc_secret_dict
245
+ if self.acc_secret_dict is None:
246
+ self.acc_secret_dict = {}
247
+ # self.api_dict = {username: KaggleApiWrapper(username, secret) for username, secret in acc_secret_dict.items()}
248
+ # lock for each account to avoid concurrent use api
249
+ self.lock_dict = {username: False for username in self.acc_secret_dict.keys()}
250
+ self.state_lock = threading.Lock()
251
+
252
+ def _get_api(self, username: str) -> KaggleApiWrapper:
253
+ # return self.api_dict[username]
254
+ return KaggleApiWrapper(username, self.acc_secret_dict[username])
255
+
256
+ def _get_lock(self, username: str) -> bool:
257
+ return self.lock_dict[username]
258
+
259
+ def _set_lock(self, username: str, lock: bool) -> None:
260
+ self.lock_dict[username] = lock
261
+
262
+ def add_account(self, username, secret):
263
+ if username not in self.acc_secret_dict.keys():
264
+ self.state_lock.acquire()
265
+ self.acc_secret_dict[username] = secret
266
+ self.lock_dict[username] = False
267
+ self.state_lock.release()
268
+
269
+ def remove_account(self, username):
270
+ if username in self.acc_secret_dict.keys():
271
+ self.state_lock.acquire()
272
+ del self.acc_secret_dict[username]
273
+ del self.lock_dict[username]
274
+ self.state_lock.release()
275
+ else:
276
+ print(f"Warn: try to remove account not in the list: {username}, list: {self.acc_secret_dict.keys()}")
277
+
278
+ def get_unlocked_api_unblocking(self, username_list: List[str]) -> tuple[KaggleApiWrapper, Callable[[], None]]:
279
+ """
280
+ :param username_list: list of username
281
+ :return: (api, release) where release is a function to release api
282
+ """
283
+ while True:
284
+ print("get_unlocked_api_unblocking" + str(username_list))
285
+ for username in username_list:
286
+ self.state_lock.acquire()
287
+ if not self._get_lock(username):
288
+ self._set_lock(username, True)
289
+ api = self._get_api(username)
290
+
291
+ def release():
292
+ self.state_lock.acquire()
293
+ self._set_lock(username, False)
294
+ api.__del__()
295
+ self.state_lock.release()
296
+
297
+ self.state_lock.release()
298
+ return api, release
299
+ self.state_lock.release()
300
+ time.sleep(1)
301
+
302
+
303
+ class NbJob:
304
+ def __init__(self, acc_dict: dict, nb_slug: str, rerun_stt: List[str] = None, not_rerun_stt: List[str] = None):
305
+ """
306
+
307
+ :param acc_dict:
308
+ :param nb_slug:
309
+ :param rerun_stt:
310
+ :param not_rerun_stt: If notebook status in this list, do not rerun it. (Note: do not add "queued", "running")
311
+ """
312
+ self.rerun_stt = rerun_stt
313
+ if self.rerun_stt is None:
314
+ self.rerun_stt = ['complete']
315
+ self.not_rerun_stt = not_rerun_stt
316
+
317
+ if self.not_rerun_stt is None:
318
+ self.not_rerun_stt = ['queued', 'running', 'cancelAcknowledged']
319
+ assert "queued" in self.not_rerun_stt
320
+ assert "running" in self.not_rerun_stt
321
+
322
+ self.acc_dict = acc_dict
323
+ self.nb_slug = nb_slug
324
+
325
+ def get_acc_dict(self):
326
+ return self.acc_dict
327
+
328
+ def get_username_list(self):
329
+ return list(self.acc_dict.keys())
330
+
331
+ def is_valid_with_acc(self, api):
332
+ notebook = KaggleNotebook(api, self.nb_slug)
333
+ try:
334
+ notebook.pull()
335
+ except ApiException as e:
336
+ return False
337
+ stt, _ = notebook.check_nb_permission()
338
+ if not stt:
339
+ return False
340
+ stt = notebook.check_datasets_permission()
341
+ if not stt:
342
+ return False
343
+ return True
344
+
345
+ def is_valid(self):
346
+ for username in self.acc_dict.keys():
347
+ secrets = self.acc_dict[username]
348
+ api = KaggleApiWrapper(username=username, secret=secrets)
349
+ api.authenticate()
350
+ if not self.is_valid_with_acc(api):
351
+ return False
352
+ return True
353
+
354
+ def acc_check_and_rerun_if_need(self, api: KaggleApi) -> bool:
355
+ """
356
+ :return:
357
+ True if rerun success or notebook is running
358
+ False user does not have enough gpu quotas
359
+ :raises
360
+ Exception if setup error
361
+ """
362
+ notebook = KaggleNotebook(api, self.nb_slug, "./tmp") # todo: change hardcode container_path here
363
+
364
+ notebook.pull()
365
+ assert notebook.check_datasets_permission(), f"User {api} does not have permission on datasets of notebook {self.nb_slug}"
366
+ success, status1 = notebook.check_nb_permission()
367
+ assert success, f"User {api} does not have permission on notebook {self.nb_slug}" # todo: using api.username
368
+
369
+ if status1 in self.rerun_stt:
370
+ status2 = notebook.push()
371
+ time.sleep(10)
372
+ status3 = notebook.status()
373
+
374
+ # if 3 times same stt -> acc out of quota
375
+ if status1 == status2 == status3:
376
+ sheet_logger.log(username=api.username, nb=self.nb_slug, log="Try but no effect. Seem account to be out of quota")
377
+ return False
378
+ if status3 in self.not_rerun_stt:
379
+ sheet_logger.log(username=api.username, nb=self.nb_slug, log=f"Notebook is in ignore status list {self.not_rerun_stt}, do nothing!")
380
+ return True
381
+ if status3 not in ["queued", "running"]:
382
+ # return False # todo: check when user is out of quota
383
+ print(f"Error: status is {status3}")
384
+ raise Exception("Setup exception")
385
+ sheet_logger.log(username=api.username, nb=self.nb_slug,
386
+ log=f"Schedule notebook successfully. Current status is '{status3}'")
387
+ return True
388
+
389
+ sheet_logger.log(username=api.username, nb=self.nb_slug, log=f"Notebook status is '{status1}' is not in {self.rerun_stt}, do nothing!")
390
+ return True
391
+
392
+ @staticmethod
393
+ def from_dict(obj: dict):
394
+ return NbJob(acc_dict=obj['accounts'], nb_slug=obj['slug'], rerun_stt=obj.get('rerun_status'), not_rerun_stt=obj.get('not_rerun_stt'))
395
+
396
+
397
+ class KernelRerunService:
398
+ def __init__(self):
399
+ self.jobs: Dict[str, NbJob] = {}
400
+ self.acc_manager = AccountTransactionManager()
401
+ self.username2jobid = {}
402
+ self.jobid2username = {}
403
+
404
+ def add_job(self, nb_job: NbJob):
405
+ if nb_job.nb_slug in self.jobs.keys():
406
+ print("Warn: nb_job already in job list")
407
+ return
408
+ self.jobs[nb_job.nb_slug] = nb_job
409
+ self.jobid2username[nb_job.nb_slug] = nb_job.get_username_list()
410
+ for username in nb_job.get_username_list():
411
+ if username not in self.username2jobid.keys():
412
+ self.username2jobid[username] = []
413
+ self.acc_manager.add_account(username, nb_job.acc_dict[username])
414
+ self.username2jobid[username].append(nb_job.nb_slug)
415
+
416
+ def remove_job(self, nb_job):
417
+ if nb_job.nb_slug not in self.jobs.keys():
418
+ print("Warn: try to remove nb_job not in list")
419
+ return
420
+ username_list = self.jobid2username[nb_job.nb_slug]
421
+ username_list = [username for username in username_list if len(self.username2jobid[username]) == 1]
422
+
423
+ for username in username_list:
424
+ del self.username2jobid[username]
425
+ self.acc_manager.remove_account(username)
426
+ del self.jobs[nb_job.nb_slug]
427
+ del self.jobid2username[nb_job.nb_slug]
428
+
429
+ def validate_all(self):
430
+ for username in self.acc_manager.acc_secret_dict.keys():
431
+ api, release = self.acc_manager.get_unlocked_api_unblocking([username])
432
+ api.authenticate()
433
+ print(f"Using username: {api.username}")
434
+
435
+ for job in self.jobs.values():
436
+ if username in job.get_username_list():
437
+ print(f"Validate user: {username}, job: {job.nb_slug}")
438
+ if not job.is_valid_with_acc(api):
439
+ print(f"Error: not valid")
440
+ a = f"Setup error: {username} does not have permission on notebook {job.nb_slug} or related datasets"
441
+ raise Exception(a)
442
+ release()
443
+ return True
444
+
445
+ def status_all(self):
446
+ for job in self.jobs.values():
447
+ print(f"Job: {job.nb_slug}")
448
+ api, release = self.acc_manager.get_unlocked_api_unblocking(job.get_username_list())
449
+ api.authenticate()
450
+ print(f"Using username: {api.username}")
451
+ notebook = KaggleNotebook(api, job.nb_slug)
452
+ print(f"Notebook: {notebook.kernel_slug}")
453
+ print(notebook.status())
454
+ release()
455
+
456
+ def run(self, nb_job: NbJob):
457
+ username_list = copy.copy(nb_job.get_username_list())
458
+ while len(username_list) > 0:
459
+ api, release = self.acc_manager.get_unlocked_api_unblocking(username_list)
460
+ api.authenticate()
461
+ print(f"Using username: {api.username}")
462
+
463
+ try:
464
+ result = nb_job.acc_check_and_rerun_if_need(api)
465
+ if result:
466
+ return True
467
+ except Exception as e:
468
+ print(e)
469
+ release()
470
+ break
471
+
472
+ if api.username in username_list:
473
+ username_list.remove(api.username)
474
+ release()
475
+ else:
476
+ release()
477
+ raise Exception("")
478
+ return False
479
+
480
+ def run_all(self):
481
+ for job in self.jobs.values():
482
+ success = self.run(job)
483
+ print(f"Job: {job.nb_slug} {success}")
484
+
485
+
486
+
487
+ import json
488
+
489
+ from kaggle_service import KernelRerunService, NbJob
490
+ from logger import sheet_logger
491
+
492
+
493
+ if __name__ == "__main__":
494
+ configs = []
495
+ try:
496
+ for i in range(2, 1000):
497
+ rs = conf_repo.read(i)
498
+ if not rs:
499
+ break
500
+ cfg = json.loads(rs['config'])
501
+ configs.append(cfg)
502
+ print(cfg)
503
+ except Exception as e:
504
+ sheet_logger.log(log="Get config failed!!")
505
+
506
+ service = KernelRerunService()
507
+ for config in configs:
508
+ service.add_job(NbJob.from_dict(config))
509
+
510
+ try:
511
+ service.validate_all()
512
+ service.status_all()
513
+ service.run_all()
514
+ except Exception as e:
515
+ sheet_logger.log(log=str(e))
516
+
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ kaggle
2
+ gspread
3
+ oauth2client
test.ipynb ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "id": "initial_id",
7
+ "metadata": {
8
+ "collapsed": true,
9
+ "ExecuteTime": {
10
+ "end_time": "2023-11-05T00:47:48.131663100Z",
11
+ "start_time": "2023-11-05T00:47:35.527891600Z"
12
+ }
13
+ },
14
+ "outputs": [
15
+ {
16
+ "name": "stdout",
17
+ "output_type": "stream",
18
+ "text": [
19
+ "Collecting kaggle\r\n",
20
+ " Downloading kaggle-1.5.16.tar.gz (83 kB)\r\n",
21
+ "\u001B[2K \u001B[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001B[0m \u001B[32m83.6/83.6 kB\u001B[0m \u001B[31m444.7 kB/s\u001B[0m eta \u001B[36m0:00:00\u001B[0m0:01\u001B[0m00:01\u001B[0m\r\n",
22
+ "\u001B[?25h Preparing metadata (setup.py) ... \u001B[?25ldone\r\n",
23
+ "\u001B[?25hRequirement already satisfied: six>=1.10 in /home/kryo/miniconda3/envs/vlsp2023-tts-api/lib/python3.10/site-packages (from kaggle) (1.16.0)\r\n",
24
+ "Requirement already satisfied: certifi in /home/kryo/miniconda3/envs/vlsp2023-tts-api/lib/python3.10/site-packages (from kaggle) (2023.7.22)\r\n",
25
+ "Requirement already satisfied: python-dateutil in /home/kryo/miniconda3/envs/vlsp2023-tts-api/lib/python3.10/site-packages (from kaggle) (2.8.2)\r\n",
26
+ "Requirement already satisfied: requests in /home/kryo/miniconda3/envs/vlsp2023-tts-api/lib/python3.10/site-packages (from kaggle) (2.31.0)\r\n",
27
+ "Collecting tqdm (from kaggle)\r\n",
28
+ " Downloading tqdm-4.66.1-py3-none-any.whl.metadata (57 kB)\r\n",
29
+ "\u001B[2K \u001B[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001B[0m \u001B[32m57.6/57.6 kB\u001B[0m \u001B[31m332.3 kB/s\u001B[0m eta \u001B[36m0:00:00\u001B[0m \u001B[36m0:00:01\u001B[0m\r\n",
30
+ "\u001B[?25hCollecting python-slugify (from kaggle)\r\n",
31
+ " Downloading python_slugify-8.0.1-py2.py3-none-any.whl (9.7 kB)\r\n",
32
+ "Requirement already satisfied: urllib3 in /home/kryo/miniconda3/envs/vlsp2023-tts-api/lib/python3.10/site-packages (from kaggle) (2.0.7)\r\n",
33
+ "Requirement already satisfied: bleach in /home/kryo/miniconda3/envs/vlsp2023-tts-api/lib/python3.10/site-packages (from kaggle) (6.1.0)\r\n",
34
+ "Requirement already satisfied: webencodings in /home/kryo/miniconda3/envs/vlsp2023-tts-api/lib/python3.10/site-packages (from bleach->kaggle) (0.5.1)\r\n",
35
+ "Collecting text-unidecode>=1.3 (from python-slugify->kaggle)\r\n",
36
+ " Downloading text_unidecode-1.3-py2.py3-none-any.whl (78 kB)\r\n",
37
+ "\u001B[2K \u001B[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001B[0m \u001B[32m78.2/78.2 kB\u001B[0m \u001B[31m944.9 kB/s\u001B[0m eta \u001B[36m0:00:00\u001B[0ma \u001B[36m0:00:01\u001B[0m\r\n",
38
+ "\u001B[?25hRequirement already satisfied: charset-normalizer<4,>=2 in /home/kryo/miniconda3/envs/vlsp2023-tts-api/lib/python3.10/site-packages (from requests->kaggle) (3.3.1)\r\n",
39
+ "Requirement already satisfied: idna<4,>=2.5 in /home/kryo/miniconda3/envs/vlsp2023-tts-api/lib/python3.10/site-packages (from requests->kaggle) (3.4)\r\n",
40
+ "Downloading tqdm-4.66.1-py3-none-any.whl (78 kB)\r\n",
41
+ "\u001B[2K \u001B[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001B[0m \u001B[32m78.3/78.3 kB\u001B[0m \u001B[31m748.5 kB/s\u001B[0m eta \u001B[36m0:00:00\u001B[0m \u001B[36m0:00:01\u001B[0m\r\n",
42
+ "\u001B[?25hBuilding wheels for collected packages: kaggle\r\n",
43
+ " Building wheel for kaggle (setup.py) ... \u001B[?25ldone\r\n",
44
+ "\u001B[?25h Created wheel for kaggle: filename=kaggle-1.5.16-py3-none-any.whl size=110683 sha256=fbd426d35c51820adb030ee423c20d997221fd1cdb7093a4b6af3afa94d170f3\r\n",
45
+ " Stored in directory: /home/kryo/.cache/pip/wheels/43/4b/fb/736478af5e8004810081a06259f9aa2f7c3329fc5d03c2c412\r\n",
46
+ "Successfully built kaggle\r\n",
47
+ "Installing collected packages: text-unidecode, tqdm, python-slugify, kaggle\r\n",
48
+ "Successfully installed kaggle-1.5.16 python-slugify-8.0.1 text-unidecode-1.3 tqdm-4.66.1\r\n"
49
+ ]
50
+ }
51
+ ],
52
+ "source": [
53
+ "!pip install kaggle"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "execution_count": null,
59
+ "outputs": [],
60
+ "source": [],
61
+ "metadata": {
62
+ "collapsed": false
63
+ },
64
+ "id": "55f5e4a1d2ec2ecc"
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "execution_count": 4,
69
+ "outputs": [
70
+ {
71
+ "name": "stdout",
72
+ "output_type": "stream",
73
+ "text": [
74
+ "\u001B[31mERROR: Could not find a version that satisfies the requirement kaggle_api_extended (from versions: none)\u001B[0m\u001B[31m\r\n",
75
+ "\u001B[0m\u001B[31mERROR: No matching distribution found for kaggle_api_extended\u001B[0m\u001B[31m\r\n",
76
+ "\u001B[0m"
77
+ ]
78
+ }
79
+ ],
80
+ "source": [],
81
+ "metadata": {
82
+ "collapsed": false,
83
+ "ExecuteTime": {
84
+ "end_time": "2023-11-05T00:51:45.918622100Z",
85
+ "start_time": "2023-11-05T00:51:45.022051100Z"
86
+ }
87
+ },
88
+ "id": "28cea8fd0c172fff"
89
+ },
90
+ {
91
+ "cell_type": "markdown",
92
+ "source": [
93
+ "## merge files"
94
+ ],
95
+ "metadata": {
96
+ "collapsed": false
97
+ },
98
+ "id": "fd44ed9dee4275cf"
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "execution_count": 6,
103
+ "outputs": [
104
+ {
105
+ "name": "stdout",
106
+ "output_type": "stream",
107
+ "text": [
108
+ "Files merged successfully!\n"
109
+ ]
110
+ }
111
+ ],
112
+ "source": [
113
+ "import shutil\n",
114
+ "from pathlib import Path\n",
115
+ "try:\n",
116
+ " with open(Path('merged_file.py'), 'wb') as destination_file:\n",
117
+ " with open(Path('google_sheet.py'), 'rb') as file1:\n",
118
+ " shutil.copyfileobj(file1, destination_file)\n",
119
+ " with open(Path('logger.py'), 'rb') as file2:\n",
120
+ " shutil.copyfileobj(file2, destination_file)\n",
121
+ " with open(Path('kaggle_service.py'), 'rb') as file3:\n",
122
+ " shutil.copyfileobj(file3, destination_file)\n",
123
+ " with open(Path('main.py'), 'rb') as file4:\n",
124
+ " shutil.copyfileobj(file4, destination_file)\n",
125
+ " print(\"Files merged successfully!\")\n",
126
+ "except :\n",
127
+ " raise Exception(\"Cannot merge files!\")"
128
+ ],
129
+ "metadata": {
130
+ "collapsed": false,
131
+ "ExecuteTime": {
132
+ "end_time": "2023-11-05T02:15:34.843461500Z",
133
+ "start_time": "2023-11-05T02:15:34.781001200Z"
134
+ }
135
+ },
136
+ "id": "2568f49413e2057c"
137
+ }
138
+ ],
139
+ "metadata": {
140
+ "kernelspec": {
141
+ "display_name": "Python 3",
142
+ "language": "python",
143
+ "name": "python3"
144
+ },
145
+ "language_info": {
146
+ "codemirror_mode": {
147
+ "name": "ipython",
148
+ "version": 2
149
+ },
150
+ "file_extension": ".py",
151
+ "mimetype": "text/x-python",
152
+ "name": "python",
153
+ "nbconvert_exporter": "python",
154
+ "pygments_lexer": "ipython2",
155
+ "version": "2.7.6"
156
+ }
157
+ },
158
+ "nbformat": 4,
159
+ "nbformat_minor": 5
160
+ }