-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathkaggle_api_extended.py
More file actions
7864 lines (6791 loc) · 327 KB
/
Copy pathkaggle_api_extended.py
File metadata and controls
7864 lines (6791 loc) · 327 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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
# Copyright 2024 Kaggle Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# coding=utf-8
from __future__ import print_function
import csv
from datetime import datetime, timezone
from enum import Enum
import io
import json # Needed by mypy.
import logging
import math
import os
from pathlib import Path
import re # Needed by mypy.
import shutil
import sys
import tarfile
import tempfile
import time
import zipfile
from dateutil.relativedelta import relativedelta
from os.path import expanduser
from random import random
import bleach
import mimetypes
import requests
import urllib3.exceptions as urllib3_exceptions
from requests import RequestException
from kaggle.models.kaggle_models_extended import ResumableUploadResult, File
from requests.adapters import HTTPAdapter
from slugify import slugify
from tqdm import tqdm
from urllib3.util.retry import Retry
from google.protobuf import field_mask_pb2
from packaging.version import parse
import kaggle
from kagglesdk import get_access_token_from_env, KaggleClient, KaggleCredentials, KaggleEnv, KaggleOAuth # type: ignore[attr-defined]
from kagglesdk.admin.types.inbox_file_service import CreateInboxFileRequest
from kagglesdk.blobs.types.blob_api_service import ApiStartBlobUploadRequest, ApiStartBlobUploadResponse, ApiBlobType
from kagglesdk.benchmarks.types.benchmark_enums import BenchmarkTaskRunState, BenchmarkTaskVersionCreationState
from kagglesdk.benchmarks.types.benchmark_tasks_api_service import (
ApiCreateBenchmarkTaskRequest,
ApiListBenchmarkTasksRequest,
ApiGetBenchmarkTaskRequest,
ApiGetBenchmarkTaskRunLogsRequest,
ApiListBenchmarkTaskRunsRequest,
ApiBenchmarkTaskSlug,
ApiBatchScheduleBenchmarkTaskRunsRequest,
ApiDownloadBenchmarkTaskRunOutputRequest,
ApiPublishBenchmarkTaskRequest,
)
from kagglesdk.benchmarks.types.benchmark_types import BenchmarkTaskOptions
from kagglesdk.benchmarks.types.benchmarks_api_service import ApiListBenchmarkModelsRequest
from kagglesdk.competitions.types.competition_api_service import (
ApiListCompetitionsRequest,
ApiCreateCodeSubmissionRequest,
ApiCreateSubmissionResponse,
ApiStartSubmissionUploadRequest,
ApiCreateSubmissionRequest,
ApiSubmission,
ApiListSubmissionsRequest,
ApiListDataFilesResponse,
ApiListDataFilesRequest,
ApiDownloadDataFileRequest,
ApiDownloadDataFilesRequest,
ApiDownloadLeaderboardRequest,
ApiLeaderboardSubmission,
ApiGetLeaderboardRequest,
ApiDataFile,
ApiCreateCodeSubmissionResponse,
ApiListCompetitionsResponse,
ApiListSubmissionEpisodesRequest,
ApiListSubmissionEpisodesResponse,
ApiGetEpisodeReplayRequest,
ApiGetEpisodeAgentLogsRequest,
ApiListCompetitionPagesRequest,
ApiListCompetitionPagesResponse,
ApiListCompetitionTopicsRequest,
ApiListCompetitionTopicsResponse,
ApiListTopicMessagesRequest,
ApiListTopicMessagesResponse,
)
from kagglesdk.discussions.types.discussions_api_service import (
ApiDiscussionComment,
ApiDiscussionForum,
ApiDiscussionTopic,
ApiGetTopicRequest,
ApiGetTopicResponse,
ApiListCommentsRequest,
ApiListCommentsResponse,
ApiListForumsRequest,
ApiListForumsResponse,
ApiListTopicsRequest,
ApiListTopicsResponse,
)
from kagglesdk.discussions.types.discussions_enums import (
CommentListSortBy,
TopicListCategory,
TopicListGroup,
TopicListSortBy,
)
from kagglesdk.competitions.types.competition_enums import (
CompetitionListTab,
HostSegment,
CompetitionSortBy,
SubmissionGroup,
SubmissionSortBy,
)
from kagglesdk.common.types.cropped_image_upload import CroppedImageUpload, CroppedImageRectangle
from kagglesdk.datasets.types.dataset_api_service import (
ApiListDatasetsRequest,
ApiListDatasetFilesRequest,
ApiGetDatasetRequest,
ApiGetDatasetStatusRequest,
ApiDownloadDatasetRequest,
ApiCreateDatasetRequest,
ApiCreateDatasetVersionRequestBody,
ApiCreateDatasetVersionByIdRequest,
ApiCreateDatasetVersionRequest,
ApiDatasetNewFile,
ApiUpdateDatasetMetadataRequest,
ApiGetDatasetMetadataRequest,
ApiDatasetFile,
ApiDataset,
ApiCreateDatasetResponse,
ApiDatasetColumn,
ApiDeleteDatasetRequest,
)
from kagglesdk.datasets.types.dataset_enums import (
DatasetSelectionGroup,
DatasetSortBy,
DatasetFileTypeGroup,
DatasetLicenseGroup,
)
from kagglesdk.datasets.types.dataset_types import DatasetSettings, SettingsLicense, DatasetCollaborator
from kagglesdk.kaggle_object import KaggleObject
from kagglesdk.kernels.types.kernels_api_service import (
ApiListKernelsRequest,
ApiListKernelFilesRequest,
ApiSaveKernelRequest,
ApiGetKernelRequest,
ApiListKernelSessionOutputRequest,
ApiGetKernelSessionStatusRequest,
ApiSaveKernelResponse,
ApiKernelMetadata,
ApiDeleteKernelRequest,
ApiGetAcceleratorQuotaStatisticsRequest,
)
from kagglesdk.kernels.types.kernels_enums import KernelWorkerStatus, KernelsListSortType, KernelsListViewType
from kagglesdk.models.types.model_api_service import (
ApiListModelsRequest,
ApiCreateModelRequest,
ApiGetModelRequest,
ApiDeleteModelRequest,
ApiUpdateModelRequest,
ApiGetModelInstanceRequest,
ApiCreateModelInstanceRequest,
ApiCreateModelInstanceRequestBody,
ApiListModelInstanceVersionFilesRequest,
ApiUpdateModelInstanceRequest,
ApiDeleteModelInstanceRequest,
ApiCreateModelInstanceVersionRequest,
ApiCreateModelInstanceVersionRequestBody,
ApiDownloadModelInstanceVersionRequest,
ApiDeleteModelInstanceVersionRequest,
ApiModel,
ApiCreateModelResponse,
ApiDeleteModelResponse,
ApiModelInstance,
ApiListModelInstanceVersionFilesResponse,
ApiListModelInstanceVersionsRequest,
ApiListModelInstanceVersionsResponse,
ApiListModelInstancesRequest,
ApiListModelInstancesResponse,
)
from kagglesdk.models.types.model_enums import ListModelsOrderBy, ModelInstanceType, ModelFramework
from kagglesdk.models.types.model_proxy_api_service import ApiCreateDefaultModelProxyTokenRequest
from kagglesdk.models.types.model_types import Owner
from kagglesdk.security.types.oauth_service import IntrospectTokenRequest
from ..models.upload_file import UploadFile
import kagglesdk.kaggle_client
from enum import EnumMeta
from requests.exceptions import HTTPError
from requests.models import Response
from typing import Callable, cast, Dict, List, Mapping, Optional, Tuple, Union, TypeVar, Iterable
T = TypeVar("T")
BENCHMARKS_SYNTAX_REF = """\
# kaggle-benchmarks Task Syntax Reference
- Installation: `pip install kaggle-benchmarks`
- [Quick Start](https://github.com/Kaggle/kaggle-benchmarks/blob/ci/quick_start.md)
- [Cookbook](https://github.com/Kaggle/kaggle-benchmarks/blob/ci/cookbook.md)
## Decorator & Signature
```python
@kbench.task(name="task_name", description="...", version=1)
def my_task(llm, param1: str, param2: int) -> ReturnType:
...
```
- First param is always `llm` (model under test).
- Additional params passed via `.run()` or `.evaluate()`.
- `name` defaults to function name; `description` defaults to docstring.
- **Important:** The `name` is normalized to a URL-safe slug (e.g. `"My Task"` becomes `my-task`).
This slug must match the task name used with `kaggle b t push <task-slug> -f <file>`.
## Return Type Annotations (controls leaderboard rendering)
| Annotation | Meaning |
|---|---|
| `None` / omitted | Pass/Fail — graded solely by assertions |
| `-> bool` | Binary pass/fail |
| `-> int` / `-> float` | Numerical score |
| `-> tuple[int, int]` | (passed, total) count |
| `-> tuple[float, float]` | (value, confidence_interval) |
| `-> dict` | Structured result dict |
## LLM Interaction
```python
response = llm.prompt("question") # returns str
obj = llm.prompt("question", schema=MyDataclass) # structured output
response = llm.prompt("q", image=images.from_url(url)) # with image
response = llm.prompt("q", video=videos.from_url(yt_url)) # with video
response = llm.prompt("q", audio=audios.from_path(path)) # with audio
response = llm.prompt("q", tools=[my_func]) # tool calling (needs api="genai")
llm.send(msg) # adds message without triggering response
llm.respond() # gets response continuing existing conversation
kbench.user.send(x) # adds user message (text/image/etc.) to chat history
```
## Chat Context Management
```python
with kbench.chats.new("name"): # isolated chat context
response = llm.prompt("...") # only this chat's history is sent
```
Use `kbench.chats.new()` in loops to avoid growing context.
For multi-agent: `contexts.enter(chat=agent_chat)`
## Accessing Models
```python
kbench.llm # default model placeholder
kbench.judge_llm # judge model
kbench.llms["google/gemini-2.5-flash"] # specific model by name
```
## Assertions (always include `expectation=` for leaderboard display)
```python
kbench.assertions.assert_equal(expected, actual, expectation="...")
kbench.assertions.assert_true(value, expectation="...")
kbench.assertions.assert_false(value, expectation="...")
kbench.assertions.assert_in(member, container, expectation="...")
kbench.assertions.assert_not_in(member, container, expectation="...")
kbench.assertions.assert_contains_regex(pattern, text, expectation="...")
kbench.assertions.assert_not_contains_regex(pattern, text, expectation="...", flags=0)
kbench.assertions.assert_empty(container, expectation="...")
kbench.assertions.assert_not_empty(container, expectation="...")
kbench.assertions.assert_fail(expectation="...") # unconditional fail
```
## Custom Assertions
```python
from kaggle_benchmarks.assertions import assertion_handler, AssertionResult
@assertion_handler()
def assert_is_positive(value: float, expectation: str) -> AssertionResult:
return AssertionResult(passed=value > 0, expectation=expectation)
```
## Judge-Based Assessment
```python
report = kbench.assertions.assess_response_with_judge(
criteria=("criterion 1", "criterion 2"),
response_text=response,
judge_llm=kbench.judge_llm,
prompt_fn=optional_custom_fn, # (criteria, response_text) -> str
output_schema=OptionalDataclass,
)
for r in report.results:
kbench.assertions.assert_true(r.passed, expectation=f"{r.criterion}: {r.reason}")
```
## Running Tasks
`.run()` or `.evaluate()` MUST be called to generate a run file.
Without invoking one of these, no `.run.json` is produced and nothing is recorded.
```python
# Single run:
run = my_task.run(llm=kbench.llm, param1="val1", param2=42)
# Dataset evaluation (runs task once per row in a DataFrame):
runs = my_task.evaluate(
llm=[kbench.llm], evaluation_data=df, # df columns map to task params
n_jobs=2, timeout=120,
stop_condition=lambda r: len(r) == df.shape[0],
max_attempts=50, retry_delay=15, remove_run_files=True,
)
results_df = runs.as_dataframe()
```
## Multimodal Content Factories
```python
from kaggle_benchmarks.content_types import images, videos, audios
images.from_url(url) | images.from_path(p) | images.from_base64(b64, format="png")
videos.from_url(youtube_url)
audios.from_path(p) | audios.from_url(url) | audios.from_base64(b64, format="mp3")
```
## Token Usage Tracking
```python
with kbench.chats.new("chat") as chat:
llm.prompt("...")
chat.usage.input_tokens / .output_tokens / .input_tokens_cost_nanodollars
```
"""
BENCHMARKS_EXAMPLE_TASK = """\
# Syntax reference: kaggle_benchmarks_reference.md
import kaggle_benchmarks as kbench
@kbench.task(name="What is Kaggle?", description="Does the LLM know what Kaggle is?")
def what_is_kaggle(llm) -> None:
response = llm.prompt("What is Kaggle?")
kbench.assertions.assert_in("platform", response.lower())
what_is_kaggle.run(kbench.llm)
"""
class AuthMethod(Enum):
LEGACY_API_KEY = 0
ACCESS_TOKEN = 1
OAUTH = 2
def __str__(self):
return self.name
class DirectoryArchive(object):
"""
Context manager for handling directory archives.
This class provides a context manager for working with directory archives in various formats.
It manages the lifecycle of the archive, including opening and closing resources as needed.
"""
def __init__(self, fullpath, fmt):
self._fullpath = fullpath
self._format = fmt
self.name = None
self.path = None
def __enter__(self):
self._temp_dir = tempfile.mkdtemp()
_, dir_name = os.path.split(self._fullpath)
self.path = shutil.make_archive(os.path.join(self._temp_dir, dir_name), self._format, self._fullpath)
_, self.name = os.path.split(self.path)
return self
def __exit__(self, *args):
shutil.rmtree(self._temp_dir)
class ResumableUploadContext(object):
"""
Context manager for handling resumable file uploads.
This class manages the context for resumable uploads, allowing multiple files to be uploaded
with the ability to resume interrupted uploads. It manages temporary directories and tracks
the state of each file upload within the context.
"""
def __init__(self, no_resume: bool = False) -> None:
self.no_resume = no_resume
self._temp_dir = os.path.join(tempfile.gettempdir(), ".kaggle/uploads")
self._file_uploads: List["ResumableFileUpload"] = []
def __enter__(self) -> "ResumableUploadContext":
if self.no_resume:
return self
self._create_temp_dir()
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
if self.no_resume:
return
if exc_type is not None:
# Don't delete the upload file info when there is an error
# to give it a chance to retry/resume on the next invocation.
return
for file_upload in self._file_uploads:
file_upload.cleanup()
def get_upload_info_file_path(self, path: str) -> str:
"""Returns the path to the upload info file for a given file.
Args:
path (str): The path to the file for which to get the upload info file path.
Returns:
str: The path to the upload info file.
"""
return os.path.join(self._temp_dir, "%s.json" % path.replace(os.path.sep, "_").replace(":", "_"))
def new_resumable_file_upload(
self, path: str, start_blob_upload_request: ApiStartBlobUploadRequest
) -> "ResumableFileUpload":
file_upload = ResumableFileUpload(path, start_blob_upload_request, self)
self._file_uploads.append(file_upload)
file_upload.load()
return file_upload
def _create_temp_dir(self) -> None:
try:
os.makedirs(self._temp_dir)
except FileExistsError:
pass
class ResumableFileUpload(object):
"""
Represents a single file upload that supports resuming after interruption.
This class manages the state and metadata for uploading a file in a resumable way,
including saving and loading upload progress, handling upload tokens, and managing
temporary files used to track the upload state.
"""
# Reference: https://cloud.google.com/storage/docs/resumable-uploads
# A resumable upload must be completed within a week of being initiated
RESUMABLE_UPLOAD_EXPIRY_SECONDS = 6 * 24 * 3600
def __init__(
self, path: str, start_blob_upload_request: ApiStartBlobUploadRequest, context: ResumableUploadContext
) -> None:
self.path = path
self.start_blob_upload_request = start_blob_upload_request
self.context = context
self.timestamp = int(time.time())
self.start_blob_upload_response: Union[ApiStartBlobUploadResponse, None] = None
self.can_resume = False
self.upload_complete = False
if self.context.no_resume:
return
self._upload_info_file_path = self.context.get_upload_info_file_path(path)
def get_token(self):
"""Retrieves the upload token for a completed upload.
This method returns the token of the blob upload response if the upload is complete.
If the upload is not complete, it returns None.
Returns:
The upload token if the upload is complete, otherwise None.
"""
if self.upload_complete:
return cast(ApiStartBlobUploadResponse, self.start_blob_upload_response).token
return None
def load(self) -> None:
"""Loads a previous upload if it exists and is valid.
This method checks for a previous upload information file and, if it exists,
validates it. If the previous upload is valid, it loads the information
and sets the `can_resume` flag to True.
"""
if self.context.no_resume:
return
self._load_previous_if_any()
def _load_previous_if_any(self) -> bool:
if not os.path.exists(self._upload_info_file_path):
return False
try:
with io.open(self._upload_info_file_path, "r") as f:
previous = ResumableFileUpload.from_dict(json.load(f), self.context)
if self._is_previous_valid(previous):
self.start_blob_upload_response = previous.start_blob_upload_response
self.timestamp = previous.timestamp
self.can_resume = True
return True
except Exception as e:
print("Error while trying to load upload info:", e)
return False
def _is_previous_valid(self, previous):
return (
previous.path == self.path
and previous.start_blob_upload_request == self.start_blob_upload_request
and previous.timestamp > time.time() - ResumableFileUpload.RESUMABLE_UPLOAD_EXPIRY_SECONDS
)
def upload_initiated(self, start_blob_upload_response: ApiStartBlobUploadResponse) -> None:
"""Saves the upload information to a file.
This method is called after an upload has been initiated. It saves the
upload information to a file so that it can be resumed later.
Args:
start_blob_upload_response (ApiStartBlobUploadResponse): The response from the start blob upload request.
Returns:
None:
"""
if self.context.no_resume:
return
self.start_blob_upload_response = start_blob_upload_response
with io.open(self._upload_info_file_path, "w") as f:
json.dump(self.to_dict(), f, indent=True)
def upload_completed(self):
"""Marks the upload as complete.
This method sets the `upload_complete` flag to True and saves the upload
information to a file.
"""
if self.context.no_resume:
return
self.upload_complete = True
self._save()
def _save(self):
with io.open(self._upload_info_file_path, "w") as f:
json.dump(self.to_dict(), f, indent=True)
def cleanup(self):
"""Removes the upload information file.
This method is called to clean up the upload information file after the
upload is complete.
"""
if self.context.no_resume:
return
try:
os.remove(self._upload_info_file_path)
except OSError:
pass
def to_dict(self):
"""Converts the ResumableFileUpload object to a dictionary.
Returns:
A dictionary representation of the ResumableFileUpload object.
"""
return {
"path": self.path,
"start_blob_upload_request": self.start_blob_upload_request.to_dict(),
"timestamp": self.timestamp,
"start_blob_upload_response": (
self.start_blob_upload_response.to_dict() if self.start_blob_upload_response is not None else None
),
"upload_complete": self.upload_complete,
}
@staticmethod
def from_dict(other, context):
"""Creates a ResumableFileUpload object from a dictionary.
Args:
other: A dictionary containing the ResumableFileUpload object's data.
context: The ResumableUploadContext object.
Returns:
A new ResumableFileUpload object.
"""
req = ApiStartBlobUploadRequest()
req.from_dict(other["start_blob_upload_request"])
new = ResumableFileUpload(other["path"], req, context)
new.timestamp = other.get("timestamp")
start_blob_upload_response = other.get("start_blob_upload_response")
if start_blob_upload_response is not None:
rsp = ApiStartBlobUploadResponse()
rsp.from_dict(**start_blob_upload_response)
new.start_blob_upload_response = rsp
new.upload_complete = other.get("upload_complete") or False
return new
def to_str(self):
"""Converts the ResumableFileUpload object to a string.
Returns:
A string representation of the ResumableFileUpload object.
"""
return str(self.to_dict())
def __repr__(self):
return self.to_str()
class FileList(object):
"""
Represents a list of files returned from a Kaggle API response.
This class parses and stores information about files (such as datasets or model files)
returned by the Kaggle API, including handling pagination tokens and error messages.
"""
def __init__(self, init_dict):
self.error_message = ""
files = init_dict["files"]
if files:
for f in files:
if "size" in f:
f["totalBytes"] = f["size"]
self.files = [File(f) for f in files]
else:
self.files = []
token = init_dict["nextPageToken"]
if token:
self.nextPageToken = token
else:
self.nextPageToken = ""
@staticmethod
def from_response(response: ApiListModelInstanceVersionFilesResponse) -> "FileList":
"""Creates a FileList object from an API response.
Args:
response (ApiListModelInstanceVersionFilesResponse): The API response.
Returns:
FileList: A new FileList object.
"""
inst = FileList({"files": [], "nextPageToken": ""})
inst.error_message = ""
files = response.files
if files:
inst.files = [File(f) for f in files]
else:
inst.files = []
token = response.next_page_token
if token:
inst.nextPageToken = token
else:
inst.nextPageToken = ""
return inst
def __repr__(self):
return ""
def print_auth_help() -> None:
"""Print friendly instructions for setting up Kaggle authentication."""
print(
"Authentication required to call the Kaggle API.\n"
"\n"
"First, you will need a Kaggle account. You can sign up at\n"
" https://www.kaggle.com/account/login\n"
"\n"
"Recommended: log in with OAuth via a web-based authorization flow.\n"
"No token to manage; credentials are cached locally for you.\n"
" kaggle auth login\n"
"\n"
"If you'd rather not use OAuth, generate an API token at\n"
' https://www.kaggle.com/settings/api (click "Generate New Token" under "API")\n'
"and supply it to the CLI in one of these ways:\n"
"\n"
" Option A: Environment variable\n"
" export KAGGLE_API_TOKEN=xxxxxxxxxxxxxx # token copied from the settings UI\n"
"\n"
" Option B: API token file\n"
" Save the token to ~/.kaggle/access_token"
)
class KaggleApi:
"""
KaggleApi provides methods for interacting with Kaggle's public API.
This class manages authentication, configuration, and communication with Kaggle endpoints
for datasets, competitions, kernels, models, and more. It supports downloading and uploading
datasets, managing competition submissions, handling kernels (notebooks and scripts), and
querying Kaggle resources.
Configuration is handled via environment variables or a configuration file, and the class
supports both API key and OAuth authentication methods. It validates input parameters for
various Kaggle resource types and manages local paths and proxy settings.
Usage:
api = KaggleApi()
api.authenticate()
api.dataset_download_files('username/dataset-name')
api.competition_submit('submission.csv', 'My submission', 'competition-name')
There are many methods that have the suffix '_cli' in their name, which are intended to be used
only from the command line interface (cli.py). These methods are not part of the public API.
"""
CONFIG_NAME_PROXY = "proxy"
CONFIG_NAME_COMPETITION = "competition"
CONFIG_NAME_PATH = "path"
CONFIG_NAME_USER = "username"
CONFIG_NAME_AUTH_METHOD = "auth_method"
CONFIG_NAME_KEY = "key"
CONFIG_NAME_TOKEN = "token"
CONFIG_NAME_SSL_CA_CERT = "ssl_ca_cert"
HEADER_API_VERSION = "X-Kaggle-ApiVersion"
DATASET_METADATA_FILE = "dataset-metadata.json"
OLD_DATASET_METADATA_FILE = "datapackage.json"
DATASET_COVER_IMAGE_SUPPORTED_EXTENSIONS = [".png", ".jpg", ".jpeg", ".webp"]
DATASET_COVER_IMAGE_FILES = ["dataset-cover-image" + ext for ext in DATASET_COVER_IMAGE_SUPPORTED_EXTENSIONS]
KERNEL_METADATA_FILE = "kernel-metadata.json"
MODEL_METADATA_FILE = "model-metadata.json"
MODEL_INSTANCE_METADATA_FILE = "model-instance-metadata.json"
MAX_NUM_INBOX_FILES_TO_UPLOAD = 1000
MAX_UPLOAD_RESUME_ATTEMPTS = 10
config_dir = os.environ.get("KAGGLE_CONFIG_DIR")
if not config_dir:
config_dir = os.path.join(expanduser("~"), ".kaggle")
# Use ~/.kaggle if it already exists for backwards compatibility,
# otherwise follow XDG base directory specification
if sys.platform.startswith("linux") and not os.path.exists(config_dir):
config_dir = os.path.join(
(os.environ.get("XDG_CONFIG_HOME") or os.path.join(expanduser("~"), ".config")), "kaggle"
)
if not os.path.exists(config_dir):
os.makedirs(config_dir)
config_file = "kaggle.json"
config = os.path.join(config_dir, config_file)
config_values: Dict[str, str] = {}
already_printed_version_warning = False
args: List[str] = []
if os.environ.get("KAGGLE_API_ENVIRONMENT") == "LOCALHOST":
args.append("--local")
verbose = (os.environ.get("VERBOSE") or os.environ.get("VERBOSE_OUTPUT") or "false").lower()
if verbose in ("1", "true", "yes"):
args.append("--verbose")
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Kernels valid types
valid_push_kernel_types = ["script", "notebook"]
valid_push_language_types = ["python", "r", "rmarkdown"]
valid_push_pinning_types = ["original", "latest"]
valid_list_languages = ["all", "python", "r", "sqlite", "julia"]
valid_list_kernel_types = ["all", "script", "notebook"]
valid_list_output_types = ["all", "visualization", "data"]
valid_list_sort_by = [
"hotness",
"commentCount",
"dateCreated",
"dateRun",
"relevance",
"scoreAscending",
"scoreDescending",
"viewCount",
"voteCount",
]
# Competitions valid types
valid_competition_groups = ["general", "entered", "community", "hosted", "unlaunched", "unlaunched_community"]
valid_competition_categories = [
"unspecified",
"featured",
"research",
"recruitment",
"gettingStarted",
"masters",
"playground",
]
valid_competition_sort_by = [
"grouped",
"best",
"prize",
"earliestDeadline",
"latestDeadline",
"numberOfTeams",
"relevance",
"recentlyCreated",
]
# Datasets valid types
valid_dataset_file_types = ["all", "csv", "sqlite", "json", "bigQuery", "parquet"]
valid_dataset_license_names = ["all", "cc", "gpl", "odb", "other"]
valid_dataset_sort_bys = ["hottest", "votes", "updated", "active", "published"]
# Models valid types
valid_model_sort_bys = ["hotness", "downloadCount", "voteCount", "notebookCount", "createTime"]
# Command prefixes that are valid without authentication.
command_prefixes_allowing_anonymous_access = ("datasets download", "datasets files", "auth login")
# Attributes
competition_fields = ["ref", "deadline", "category", "reward", "teamCount", "userHasEntered"]
submission_fields = ["ref", "fileName", "date", "description", "status", "publicScore", "privateScore"]
competition_file_fields = ["name", "totalBytes", "creationDate"]
competition_file_labels = ["name", "size", "creationDate"]
competition_leaderboard_fields = ["teamId", "teamName", "submissionDate", "score"]
dataset_fields = ["ref", "title", "totalBytes", "lastUpdated", "downloadCount", "voteCount", "usabilityRating"]
dataset_labels = ["ref", "title", "size", "lastUpdated", "downloadCount", "voteCount", "usabilityRating"]
dataset_file_fields = ["name", "total_bytes", "creationDate"]
model_fields = ["id", "ref", "title", "subtitle", "author"]
model_all_fields = ["id", "ref", "author", "slug", "title", "subtitle", "isPrivate", "description", "publishTime"]
model_file_fields = ["name", "size", "creationDate"]
model_instance_fields = ["versionNumber", "versionNotes", "creationStatus", "totalUncompressedBytes"]
model_instance_labels = ["version", "notes", "created", "size"]
model_instance_version_fields = ["versionNumber", "variationSlug", "modelTitle", "isPrivate"]
model_instance_version_labels = ["version", "variation", "title", "private"]
episode_fields = ["id", "createTime", "endTime", "state", "type"]
episode_agent_fields = ["submissionId", "index", "reward", "state", "teamName", "teamId"]
competition_page_fields = ["name"]
competition_topic_fields = ["id", "title", "authorName", "commentCount", "votes", "postDate"]
competition_topic_message_fields = ["id", "authorName", "postDate", "votes", "content"]
valid_topic_sort_by = ["hot", "top", "new", "recent", "active", "relevance"]
valid_comment_sort_by = ["hot", "new", "old", "top"]
# Forums / Discussions
forum_fields = ["id", "name", "subtitle"]
forum_topic_fields = ["id", "title", "authorName", "commentCount", "votes", "postDate"]
forum_comment_fields = ["id", "authorName", "postDate", "votes", "content"]
valid_forum_topic_sort_by = ["hot", "top", "new", "recent", "active", "relevance"]
valid_forum_topic_categories = [
"all",
"forums",
"competitions",
"datasets",
"competition_write_ups",
"models",
"benchmarks",
]
valid_forum_topic_groups = ["all", "owned", "upvoted", "bookmarked", "my_activity", "drafts"]
def _is_retriable(self, e: HTTPError) -> bool:
if self._is_rate_limited(e):
return True
return (
issubclass(type(e), ConnectionError)
or issubclass(type(e), urllib3_exceptions.ConnectionError)
or issubclass(type(e), urllib3_exceptions.ConnectTimeoutError)
or issubclass(type(e), urllib3_exceptions.ProtocolError)
or issubclass(type(e), requests.exceptions.ConnectionError)
or issubclass(type(e), requests.exceptions.ConnectTimeout)
)
@staticmethod
def _is_rate_limited(e: Exception) -> bool:
"""Check if an HTTPError represents a 429 Too Many Requests response."""
return (
isinstance(e, HTTPError)
and hasattr(e, "response")
and e.response is not None
and e.response.status_code == 429
)
@staticmethod
def _get_retry_after_delay(response: Response) -> Optional[float]:
"""Parse the Retry-After header from an HTTP response.
Supports both integer seconds and HTTP-date formats per RFC 9110 §10.2.3.
Args:
response: The HTTP response object.
Returns:
The delay in seconds, or None if the header is absent or unparseable.
"""
retry_after = response.headers.get("Retry-After")
if retry_after is None:
return None
# Try integer seconds first
try:
return max(0.0, float(retry_after))
except ValueError:
pass
# Try HTTP-date format (e.g. "Wed, 26 Mar 2026 00:00:00 GMT")
try:
retry_date = datetime.strptime(retry_after, "%a, %d %b %Y %H:%M:%S %Z")
delay = (retry_date - datetime.now(timezone.utc).replace(tzinfo=None)).total_seconds()
return max(0.0, delay)
except (ValueError, TypeError):
pass
return None
def _calculate_backoff_delay(self, attempt, initial_delay_millis, retry_multiplier, randomness_factor):
delay_ms = initial_delay_millis * (retry_multiplier**attempt)
# TODO: int() truncates (random() - 0.5) to 0 for all values in [-0.5, 0.5),
# making jitter always zero. Apply int() to the whole expression instead.
random_wait_ms = int(random() - 0.5) * 2 * delay_ms * randomness_factor
total_delay = (delay_ms + random_wait_ms) / 1000.0
return total_delay
def with_retry(
self,
func: Callable[[KaggleObject], KaggleObject],
max_retries: int = 10,
initial_delay_millis: int = 500,
retry_multiplier: float = 1.7,
randomness_factor: float = 0.5,
) -> Callable[[KaggleObject], KaggleObject]:
def retriable_func(*args):
for i in range(1, max_retries + 1):
try:
return func(*args)
except Exception as e:
if type(e) is HTTPError:
if self._is_retriable(e) and i < max_retries:
# Use Retry-After header for 429 responses when available
if self._is_rate_limited(e):
retry_delay = self._get_retry_after_delay(e.response)
if retry_delay is not None:
total_delay = retry_delay
self.logger.info(
"Rate limited (429). Retry-After: %.1f seconds (attempt %d/%d)",
total_delay,
i,
max_retries,
)
else:
total_delay = self._calculate_backoff_delay(
i, initial_delay_millis, retry_multiplier, randomness_factor
)
self.logger.info(
"Rate limited (429). No valid Retry-After header; "
"backing off %.1f seconds (attempt %d/%d)",
total_delay,
i,
max_retries,
)
else:
total_delay = self._calculate_backoff_delay(
i, initial_delay_millis, retry_multiplier, randomness_factor
)
print("Request failed: %s. Will retry in %2.1f seconds" % (e, total_delay), file=sys.stderr)
time.sleep(total_delay)
continue
raise
return retriable_func
## Authentication
def _load_config(self) -> None:
"""Load configuration from file and environment variables."""
config_values = self.read_config_file(quiet=True)
self.config_values = self.read_config_environment(config_values)
def authenticate(self) -> None:
"""Authenticate the user with the Kaggle API, using either a legacy API key or a Kaggle OAuth token.
Returns:
None:
"""
self._load_config()
if self._authenticate_with_access_token():
return
if self._authenticate_with_legacy_apikey():
return
if self._authenticate_with_oauth_creds():
return
print_auth_help()
exit(1)
def _authenticate_with_legacy_apikey(self) -> bool: