id int64 1 6.07M | name stringlengths 1 295 | code stringlengths 12 426k | language stringclasses 1
value | source_file stringlengths 5 202 | start_line int64 1 158k | end_line int64 1 158k | repo dict |
|---|---|---|---|---|---|---|---|
5,501 | _do_upload_sync | def _do_upload_sync(self, event: RequestUpload) -> None:
job = upload_job.UploadJob(
self._stats,
self._api,
self._file_stream,
self.silent,
event.save_name,
event.path,
event.artifact_id,
event.md5,
event.copied,
event.save_fn,
event.digest,
)
job.run() | python | wandb/filesync/step_upload.py | 316 | 330 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,502 | _do_upload_async | async def _do_upload_async(self, event: RequestUpload) -> None:
"""Upload a file and returns when it's done. Requires `event.save_fn_async`."""
assert event.save_fn_async is not None
job = upload_job.UploadJobAsync(
stats=self._stats,
api=self._api,
file_stream=self._file_stream,
silent=self.silent,
request=event,
save_fn_async=event.save_fn_async,
)
await job.run() | python | wandb/filesync/step_upload.py | 332 | 343 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,503 | _init_artifact | def _init_artifact(self, artifact_id: str) -> None:
self._artifacts[artifact_id] = {
"finalize": False,
"pending_count": 0,
"commit_requested": False,
"pre_commit_callbacks": set(),
"result_futures": set(),
} | python | wandb/filesync/step_upload.py | 345 | 352 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,504 | _maybe_commit_artifact | def _maybe_commit_artifact(self, artifact_id: str) -> None:
artifact_status = self._artifacts[artifact_id]
if (
artifact_status["pending_count"] == 0
and artifact_status["commit_requested"]
):
try:
for pre_callback in artifact_status["pre_commit_callbacks"]:
pre_callback()
if artifact_status["finalize"]:
self._api.commit_artifact(artifact_id)
except Exception as exc:
termerror(
f"Committing artifact failed. Artifact {artifact_id} won't be finalized."
)
termerror(str(exc))
self._fail_artifact_futures(artifact_id, exc)
else:
self._resolve_artifact_futures(artifact_id) | python | wandb/filesync/step_upload.py | 354 | 372 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,505 | _fail_artifact_futures | def _fail_artifact_futures(self, artifact_id: str, exc: BaseException) -> None:
futures = self._artifacts[artifact_id]["result_futures"]
for result_future in futures:
result_future.set_exception(exc)
futures.clear() | python | wandb/filesync/step_upload.py | 374 | 378 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,506 | _resolve_artifact_futures | def _resolve_artifact_futures(self, artifact_id: str) -> None:
futures = self._artifacts[artifact_id]["result_futures"]
for result_future in futures:
result_future.set_result(None)
futures.clear() | python | wandb/filesync/step_upload.py | 380 | 384 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,507 | start | def start(self) -> None:
self._thread.start()
if self._async_executor:
self._async_executor.start() | python | wandb/filesync/step_upload.py | 386 | 389 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,508 | is_alive | def is_alive(self) -> bool:
return self._thread.is_alive() | python | wandb/filesync/step_upload.py | 391 | 392 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,509 | _clamp | def _clamp(x: float, low: float, high: float) -> float:
return max(low, min(x, high)) | python | wandb/filesync/step_prepare.py | 50 | 51 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,510 | gather_batch | def gather_batch(
request_queue: "queue.Queue[Request]",
batch_time: float,
inter_event_time: float,
max_batch_size: int,
clock: Callable[[], float] = time.monotonic,
) -> Tuple[bool, Sequence[RequestPrepare]]:
batch_start_time = clock()
remaining_time = batch_time
first_request = request_queue.get()
if isinstance(first_request, RequestFinish):
return True, []
batch: List[RequestPrepare] = [first_request]
while remaining_time > 0 and len(batch) < max_batch_size:
try:
request = request_queue.get(
timeout=_clamp(
x=inter_event_time,
low=1e-12, # 0 = "block forever", so just use something tiny
high=remaining_time,
),
)
if isinstance(request, RequestFinish):
return True, batch
batch.append(request)
remaining_time = batch_time - (clock() - batch_start_time)
except queue.Empty:
break
return False, batch | python | wandb/filesync/step_prepare.py | 54 | 89 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,511 | __init__ | def __init__(
self,
api: "Api",
batch_time: float,
inter_event_time: float,
max_batch_size: int,
request_queue: Optional["queue.Queue[Request]"] = None,
) -> None:
self._api = api
self._inter_event_time = inter_event_time
self._batch_time = batch_time
self._max_batch_size = max_batch_size
self._request_queue: "queue.Queue[Request]" = request_queue or queue.Queue()
self._thread = threading.Thread(target=self._thread_body)
self._thread.daemon = True | python | wandb/filesync/step_prepare.py | 99 | 113 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,512 | _thread_body | def _thread_body(self) -> None:
while True:
finish, batch = gather_batch(
request_queue=self._request_queue,
batch_time=self._batch_time,
inter_event_time=self._inter_event_time,
max_batch_size=self._max_batch_size,
)
if batch:
prepare_response = self._prepare_batch(batch)
# send responses
for prepare_request in batch:
name = prepare_request.file_spec["name"]
response_file = prepare_response[name]
upload_url = response_file["uploadUrl"]
upload_headers = response_file["uploadHeaders"]
birth_artifact_id = response_file["artifact"]["id"]
response = ResponsePrepare(
upload_url, upload_headers, birth_artifact_id
)
if isinstance(prepare_request.response_channel, queue.Queue):
prepare_request.response_channel.put(response)
else:
loop, future = prepare_request.response_channel
loop.call_soon_threadsafe(future.set_result, response)
if finish:
break | python | wandb/filesync/step_prepare.py | 115 | 142 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,513 | _prepare_batch | def _prepare_batch(
self, batch: Sequence[RequestPrepare]
) -> Mapping[str, "CreateArtifactFilesResponseFile"]:
"""Execute the prepareFiles API call.
Arguments:
batch: List of RequestPrepare objects
Returns:
dict of (save_name: ResponseFile) pairs where ResponseFile is a dict with
an uploadUrl key. The value of the uploadUrl key is None if the file
already exists, or a url string if the file should be uploaded.
"""
return self._api.create_artifact_files([req.file_spec for req in batch]) | python | wandb/filesync/step_prepare.py | 144 | 156 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,514 | prepare_async | def prepare_async(
self, file_spec: "CreateArtifactFileSpecInput"
) -> "asyncio.Future[ResponsePrepare]":
"""Request the backend to prepare a file for upload."""
response: "asyncio.Future[ResponsePrepare]" = asyncio.Future()
self._request_queue.put(
RequestPrepare(file_spec, (asyncio.get_event_loop(), response))
)
return response | python | wandb/filesync/step_prepare.py | 158 | 166 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,515 | prepare_sync | def prepare_sync(
self, file_spec: "CreateArtifactFileSpecInput"
) -> "queue.Queue[ResponsePrepare]":
response_queue: "queue.Queue[ResponsePrepare]" = queue.Queue()
self._request_queue.put(RequestPrepare(file_spec, response_queue))
return response_queue | python | wandb/filesync/step_prepare.py | 169 | 174 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,516 | start | def start(self) -> None:
self._thread.start() | python | wandb/filesync/step_prepare.py | 176 | 177 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,517 | finish | def finish(self) -> None:
self._request_queue.put(RequestFinish()) | python | wandb/filesync/step_prepare.py | 179 | 180 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,518 | is_alive | def is_alive(self) -> bool:
return self._thread.is_alive() | python | wandb/filesync/step_prepare.py | 182 | 183 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,519 | shutdown | def shutdown(self) -> None:
self.finish()
self._thread.join() | python | wandb/filesync/step_prepare.py | 185 | 187 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,520 | to_exception | def to_exception(error: pb.ErrorInfo) -> Optional[Error]:
"""Convert a protobuf error to an exception.
Args:
error: The protobuf error to convert.
Returns:
The corresponding exception.
"""
if not error.SerializeToString():
return None
if error.code in to_exception_map:
return to_exception_map[error.code](error.message)
return Error(error.message) | python | wandb/errors/util.py | 22 | 37 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,521 | from_exception | def from_exception(cls, exc: Error) -> "pb.ErrorInfo":
"""Convert an wandb error to a protobuf error message.
Args:
exc: The exception to convert.
Returns:
The corresponding protobuf error message.
"""
if not isinstance(exc, Error):
raise ValueError("exc must be a subclass of wandb.errors.Error")
code = None
for subclass in type(exc).__mro__:
if subclass in from_exception_map:
code = from_exception_map[subclass]
break
return pb.ErrorInfo(code=code, message=str(exc)) | python | wandb/errors/util.py | 40 | 57 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,522 | termsetup | def termsetup(settings, logger) -> None:
global _silent, _show_info, _show_warnings, _show_errors, _logger
_silent = settings.silent
_show_info = settings.show_info
_show_warnings = settings.show_warnings
_show_errors = settings.show_errors
_logger = logger | python | wandb/errors/term.py | 20 | 26 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,523 | termlog | def termlog(
string: str = "", newline: bool = True, repeat: bool = True, prefix: bool = True
) -> None:
"""Log to standard error with formatting.
Arguments:
string (str, optional): The string to print
newline (bool, optional): Print a newline at the end of the string
repeat (bool, optional): If set to False only prints the string once per process
"""
_log(
string=string,
newline=newline,
repeat=repeat,
prefix=prefix,
silent=not _show_info,
) | python | wandb/errors/term.py | 29 | 45 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,524 | termwarn | def termwarn(string: str, **kwargs: Any) -> None:
string = "\n".join([f"{WARN_STRING} {s}" for s in string.split("\n")])
_log(
string=string,
newline=True,
silent=not _show_warnings,
level=logging.WARNING,
**kwargs,
) | python | wandb/errors/term.py | 48 | 56 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,525 | termerror | def termerror(string: str, **kwargs: Any) -> None:
string = "\n".join([f"{ERROR_STRING} {s}" for s in string.split("\n")])
_log(
string=string,
newline=True,
silent=not _show_errors,
level=logging.ERROR,
**kwargs,
) | python | wandb/errors/term.py | 59 | 67 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,526 | _log | def _log(
string="", newline=True, repeat=True, prefix=True, silent=False, level=logging.INFO
):
global _logger
silent = silent or _silent
if string:
if prefix:
line = "\n".join([f"{LOG_STRING}: {s}" for s in string.split("\n")])
else:
line = string
else:
line = ""
if not repeat and line in PRINTED_MESSAGES:
return
# Repeated line tracking limited to 1k messages
if len(PRINTED_MESSAGES) < 1000:
PRINTED_MESSAGES.add(line)
if silent:
if level == logging.ERROR:
_logger.error(line)
elif level == logging.WARNING:
_logger.warning(line)
else:
_logger.info(line)
else:
click.echo(line, file=sys.stderr, nl=newline) | python | wandb/errors/term.py | 70 | 95 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,527 | __init__ | def __init__(self, message, context: Optional[dict] = None) -> None:
super().__init__(message)
self.message = message
# sentry context capture
if context:
self.context = context | python | wandb/errors/__init__.py | 15 | 20 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,528 | __init__ | def __init__(self, msg, exc=None) -> None:
self.exc = exc
self.message = msg
super().__init__(self.message) | python | wandb/errors/__init__.py | 26 | 29 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,529 | __init__ | def __init__(self, path, synced=None):
self.path = path
self.synced = synced
self.offline = os.path.basename(path).startswith("offline-")
self.datetime = datetime.datetime.strptime(
os.path.basename(path).split("run-")[1].split("-")[0], "%Y%m%d_%H%M%S"
) | python | wandb/sync/sync.py | 27 | 33 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,530 | __str__ | def __str__(self):
return self.path | python | wandb/sync/sync.py | 35 | 36 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,531 | __init__ | def __init__(
self,
sync_list,
project=None,
entity=None,
run_id=None,
view=None,
verbose=None,
mark_synced=None,
app_url=None,
sync_tensorboard=None,
log_path=None,
append=None,
):
threading.Thread.__init__(self)
# mark this process as internal
wandb._set_internal_process(disable=True)
self._sync_list = sync_list
self._project = project
self._entity = entity
self._run_id = run_id
self._view = view
self._verbose = verbose
self._mark_synced = mark_synced
self._app_url = app_url
self._sync_tensorboard = sync_tensorboard
self._log_path = log_path
self._append = append | python | wandb/sync/sync.py | 40 | 67 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,532 | _parse_pb | def _parse_pb(self, data, exit_pb=None):
pb = wandb_internal_pb2.Record()
pb.ParseFromString(data)
record_type = pb.WhichOneof("record_type")
if self._view:
if self._verbose:
print("Record:", pb)
else:
print("Record:", record_type)
return pb, exit_pb, True
if record_type == "run":
if self._run_id:
pb.run.run_id = self._run_id
if self._project:
pb.run.project = self._project
if self._entity:
pb.run.entity = self._entity
pb.control.req_resp = True
elif record_type == "exit":
exit_pb = pb
return pb, exit_pb, True
elif record_type == "final":
assert exit_pb, "final seen without exit"
pb = exit_pb
exit_pb = None
return pb, exit_pb, False | python | wandb/sync/sync.py | 69 | 94 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,533 | _find_tfevent_files | def _find_tfevent_files(self, sync_item):
tb_event_files = 0
tb_logdirs = []
tb_root = None
if self._sync_tensorboard:
if os.path.isdir(sync_item):
files = []
for dirpath, _, _files in os.walk(sync_item):
for f in _files:
if TFEVENT_SUBSTRING in f:
files.append(os.path.join(dirpath, f))
for tfevent in files:
tb_event_files += 1
tb_dir = os.path.dirname(os.path.abspath(tfevent))
if tb_dir not in tb_logdirs:
tb_logdirs.append(tb_dir)
if len(tb_logdirs) > 0:
tb_root = os.path.dirname(os.path.commonprefix(tb_logdirs))
elif TFEVENT_SUBSTRING in sync_item:
tb_root = os.path.dirname(os.path.abspath(sync_item))
tb_logdirs.append(tb_root)
tb_event_files = 1
return tb_event_files, tb_logdirs, tb_root | python | wandb/sync/sync.py | 96 | 119 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,534 | _setup_tensorboard | def _setup_tensorboard(self, tb_root, tb_logdirs, tb_event_files, sync_item):
"""Return true if this sync item can be synced as tensorboard."""
if tb_root is not None:
if tb_event_files > 0 and sync_item.endswith(WANDB_SUFFIX):
wandb.termwarn("Found .wandb file, not streaming tensorboard metrics.")
else:
print(f"Found {tb_event_files} tfevent files in {tb_root}")
if len(tb_logdirs) > 3:
wandb.termwarn(
f"Found {len(tb_logdirs)} directories containing tfevent files. "
"If these represent multiple experiments, sync them "
"individually or pass a list of paths."
)
return True
return False | python | wandb/sync/sync.py | 121 | 135 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,535 | _send_tensorboard | def _send_tensorboard(self, tb_root, tb_logdirs, send_manager):
if self._entity is None:
viewer, server_info = send_manager._api.viewer_server_info()
self._entity = viewer.get("entity")
proto_run = wandb_internal_pb2.RunRecord()
proto_run.run_id = self._run_id or wandb.util.generate_id()
proto_run.project = self._project or wandb.util.auto_project_name(None)
proto_run.entity = self._entity
proto_run.telemetry.feature.sync_tfevents = True
url = "{}/{}/{}/runs/{}".format(
self._app_url,
url_quote(proto_run.entity),
url_quote(proto_run.project),
url_quote(proto_run.run_id),
)
print("Syncing: %s ..." % url)
sys.stdout.flush()
# using a handler here automatically handles the step
# logic, adds summaries to the run, and handles different
# file types (like images)... but we need to remake the send_manager
record_q = queue.Queue()
sender_record_q = queue.Queue()
new_interface = InterfaceQueue(record_q)
context_keeper = context.ContextKeeper()
send_manager = sender.SendManager(
settings=send_manager._settings,
record_q=sender_record_q,
result_q=queue.Queue(),
interface=new_interface,
context_keeper=context_keeper,
)
record = send_manager._interface._make_record(run=proto_run)
settings = wandb.Settings(
root_dir=TMPDIR.name,
run_id=proto_run.run_id,
_start_datetime=datetime.datetime.now(),
_start_time=time.time(),
)
handle_manager = handler.HandleManager(
settings=settings,
record_q=record_q,
result_q=None,
stopped=False,
writer_q=sender_record_q,
interface=new_interface,
context_keeper=context_keeper,
)
filesystem.mkdir_exists_ok(settings.files_dir)
send_manager.send_run(record, file_dir=settings.files_dir)
watcher = tb_watcher.TBWatcher(settings, proto_run, new_interface, True)
for tb in tb_logdirs:
watcher.add(tb, True, tb_root)
sys.stdout.flush()
watcher.finish()
# send all of our records like a boss
progress_step = 0
spinner_states = ["-", "\\", "|", "/"]
line = " Uploading data to wandb\r"
while len(handle_manager) > 0:
data = next(handle_manager)
handle_manager.handle(data)
while len(send_manager) > 0:
data = next(send_manager)
send_manager.send(data)
print_line = spinner_states[progress_step % 4] + line
wandb.termlog(print_line, newline=False, prefix=True)
progress_step += 1
# finish sending any data
while len(send_manager) > 0:
data = next(send_manager)
send_manager.send(data)
sys.stdout.flush()
handle_manager.finish()
send_manager.finish() | python | wandb/sync/sync.py | 137 | 217 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,536 | _robust_scan | def _robust_scan(self, ds):
"""Attempt to scan data, handling incomplete files."""
try:
return ds.scan_data()
except AssertionError as e:
if ds.in_last_block():
wandb.termwarn(
".wandb file is incomplete ({}), be sure to sync this run again once it's finished".format(
e
)
)
return None
else:
raise e | python | wandb/sync/sync.py | 219 | 232 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,537 | run | def run(self):
if self._log_path is not None:
print(f"Find logs at: {self._log_path}")
for sync_item in self._sync_list:
tb_event_files, tb_logdirs, tb_root = self._find_tfevent_files(sync_item)
if os.path.isdir(sync_item):
files = os.listdir(sync_item)
filtered_files = list(filter(lambda f: f.endswith(WANDB_SUFFIX), files))
if tb_root is None and (
check_and_warn_old(files) or len(filtered_files) != 1
):
print(f"Skipping directory: {sync_item}")
continue
if len(filtered_files) > 0:
sync_item = os.path.join(sync_item, filtered_files[0])
sync_tb = self._setup_tensorboard(
tb_root, tb_logdirs, tb_event_files, sync_item
)
# If we're syncing tensorboard, let's use a tmp dir for images etc.
root_dir = TMPDIR.name if sync_tb else os.path.dirname(sync_item)
# When appending we are allowing a possible resume, ie the run
# doesnt have to exist already
resume = "allow" if self._append else None
sm = sender.SendManager.setup(root_dir, resume=resume)
if sync_tb:
self._send_tensorboard(tb_root, tb_logdirs, sm)
continue
ds = datastore.DataStore()
try:
ds.open_for_scan(sync_item)
except AssertionError as e:
print(f".wandb file is empty ({e}), skipping: {sync_item}")
continue
# save exit for final send
exit_pb = None
finished = False
shown = False
while True:
data = self._robust_scan(ds)
if data is None:
break
pb, exit_pb, cont = self._parse_pb(data, exit_pb)
if exit_pb is not None:
finished = True
if cont:
continue
sm.send(pb)
# send any records that were added in previous send
while not sm._record_q.empty():
data = sm._record_q.get(block=True)
sm.send(data)
if pb.control.req_resp:
result = sm._result_q.get(block=True)
result_type = result.WhichOneof("result_type")
if not shown and result_type == "run_result":
r = result.run_result.run
# TODO(jhr): hardcode until we have settings in sync
url = "{}/{}/{}/runs/{}".format(
self._app_url,
url_quote(r.entity),
url_quote(r.project),
url_quote(r.run_id),
)
print("Syncing: %s ... " % url, end="")
sys.stdout.flush()
shown = True
sm.finish()
# Only mark synced if the run actually finished
if self._mark_synced and not self._view and finished:
synced_file = f"{sync_item}{SYNCED_SUFFIX}"
with open(synced_file, "w"):
pass
print("done.") | python | wandb/sync/sync.py | 234 | 311 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,538 | __init__ | def __init__(
self,
project=None,
entity=None,
run_id=None,
mark_synced=None,
app_url=None,
view=None,
verbose=None,
sync_tensorboard=None,
log_path=None,
append=None,
):
self._sync_list = []
self._thread = None
self._project = project
self._entity = entity
self._run_id = run_id
self._mark_synced = mark_synced
self._app_url = app_url
self._view = view
self._verbose = verbose
self._sync_tensorboard = sync_tensorboard
self._log_path = log_path
self._append = append | python | wandb/sync/sync.py | 315 | 339 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,539 | status | def status(self):
pass | python | wandb/sync/sync.py | 341 | 342 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,540 | add | def add(self, p):
self._sync_list.append(os.path.abspath(str(p))) | python | wandb/sync/sync.py | 344 | 345 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,541 | start | def start(self):
# create a thread for each file?
self._thread = SyncThread(
sync_list=self._sync_list,
project=self._project,
entity=self._entity,
run_id=self._run_id,
view=self._view,
verbose=self._verbose,
mark_synced=self._mark_synced,
app_url=self._app_url,
sync_tensorboard=self._sync_tensorboard,
log_path=self._log_path,
append=self._append,
)
self._thread.start() | python | wandb/sync/sync.py | 347 | 362 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,542 | is_done | def is_done(self):
return not self._thread.is_alive() | python | wandb/sync/sync.py | 364 | 365 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,543 | poll | def poll(self):
time.sleep(1)
return False | python | wandb/sync/sync.py | 367 | 369 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,544 | get_runs | def get_runs(
include_offline=None,
include_online=None,
include_synced=None,
include_unsynced=None,
exclude_globs=None,
include_globs=None,
):
# TODO(jhr): grab dir info from settings
base = "wandb"
if os.path.exists(".wandb"):
base = ".wandb"
if not os.path.exists(base):
return ()
all_dirs = os.listdir(base)
dirs = []
if include_offline:
dirs += filter(lambda _d: _d.startswith("offline-run-"), all_dirs)
if include_online:
dirs += filter(lambda _d: _d.startswith("run-"), all_dirs)
# find run file in each dir
fnames = []
dirs.sort()
for d in dirs:
paths = os.listdir(os.path.join(base, d))
if exclude_globs:
paths = set(paths)
for g in exclude_globs:
paths = paths - set(fnmatch.filter(paths, g))
paths = list(paths)
if include_globs:
new_paths = set()
for g in include_globs:
new_paths = new_paths.union(fnmatch.filter(paths, g))
paths = list(new_paths)
for f in paths:
if f.endswith(WANDB_SUFFIX):
fnames.append(os.path.join(base, d, f))
filtered = []
for f in fnames:
dname = os.path.dirname(f)
# TODO(frz): online runs are assumed to be synced, verify from binary log.
if os.path.exists(f"{f}{SYNCED_SUFFIX}") or os.path.basename(dname).startswith(
"run-"
):
if include_synced:
filtered.append(_LocalRun(dname, True))
else:
if include_unsynced:
filtered.append(_LocalRun(dname, False))
return tuple(filtered) | python | wandb/sync/sync.py | 372 | 422 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,545 | get_run_from_path | def get_run_from_path(path):
return _LocalRun(path) | python | wandb/sync/sync.py | 425 | 426 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,546 | heatmap | def heatmap(x_labels, y_labels, matrix_values, show_text=False):
"""
Generates a heatmap.
Arguments:
matrix_values (arr): 2D dataset of shape x_labels * y_labels, containing
heatmap values that can be coerced into an ndarray.
x_labels (list): Named labels for rows (x_axis).
y_labels (list): Named labels for columns (y_axis).
show_text (bool): Show text values in heatmap cells.
Returns:
Nothing. To see plots, go to your W&B run page then expand the 'media' tab
under 'auto visualizations'.
Example:
wandb.log({'heatmap': wandb.plots.HeatMap(x_labels, y_labels,
matrix_values)})
"""
deprecation_notice()
np = util.get_module(
"numpy",
required="roc requires the numpy library, install with `pip install numpy`",
)
scikit = util.get_module(
"sklearn",
required="roc requires the scikit library, install with `pip install scikit-learn`",
)
if test_missing(
x_labels=x_labels, y_labels=y_labels, matrix_values=matrix_values
) and test_types(x_labels=x_labels, y_labels=y_labels, matrix_values=matrix_values):
matrix_values = np.array(matrix_values)
wandb.termlog("Visualizing heatmap.")
def heatmap_table(x_labels, y_labels, matrix_values, show_text):
x_axis = []
y_axis = []
values = []
count = 0
for i, x in enumerate(x_labels):
for j, y in enumerate(y_labels):
x_axis.append(x)
y_axis.append(y)
values.append(matrix_values[j][i])
count += 1
if count >= chart_limit:
wandb.termwarn(
"wandb uses only the first %d datapoints to create the plots."
% wandb.Table.MAX_ROWS
)
break
if show_text:
heatmap_key = "wandb/heatmap/v1"
else:
heatmap_key = "wandb/heatmap_no_text/v1"
return wandb.visualize(
heatmap_key,
wandb.Table(
columns=["x_axis", "y_axis", "values"],
data=[
[x_axis[i], y_axis[i], round(values[i], 2)]
for i in range(len(x_axis))
],
),
)
return heatmap_table(x_labels, y_labels, matrix_values, show_text) | python | wandb/plots/heatmap.py | 13 | 81 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,547 | heatmap_table | def heatmap_table(x_labels, y_labels, matrix_values, show_text):
x_axis = []
y_axis = []
values = []
count = 0
for i, x in enumerate(x_labels):
for j, y in enumerate(y_labels):
x_axis.append(x)
y_axis.append(y)
values.append(matrix_values[j][i])
count += 1
if count >= chart_limit:
wandb.termwarn(
"wandb uses only the first %d datapoints to create the plots."
% wandb.Table.MAX_ROWS
)
break
if show_text:
heatmap_key = "wandb/heatmap/v1"
else:
heatmap_key = "wandb/heatmap_no_text/v1"
return wandb.visualize(
heatmap_key,
wandb.Table(
columns=["x_axis", "y_axis", "values"],
data=[
[x_axis[i], y_axis[i], round(values[i], 2)]
for i in range(len(x_axis))
],
),
) | python | wandb/plots/heatmap.py | 49 | 79 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,548 | precision_recall | def precision_recall(
y_true=None, y_probas=None, labels=None, plot_micro=True, classes_to_plot=None
):
"""
Computes the tradeoff between precision and recall for different thresholds.
A high area under the curve represents both high recall and high precision,
where high precision relates to a low false positive rate, and high recall
relates to a low false negative rate. High scores for both show that the
classifier is returning accurate results (high precision), as well as
returning a majority of all positive results (high recall).
PR curve is useful when the classes are very imbalanced.
Arguments:
y_true (arr): Test set labels.
y_probas (arr): Test set predicted probabilities.
labels (list): Named labels for target varible (y). Makes plots easier to
read by replacing target values with corresponding index.
For example labels= ['dog', 'cat', 'owl'] all 0s are
replaced by 'dog', 1s by 'cat'.
Returns:
Nothing. To see plots, go to your W&B run page then expand the 'media' tab
under 'auto visualizations'.
Example:
wandb.log({'pr': wandb.plots.precision_recall(y_true, y_probas, labels)})
"""
deprecation_notice()
np = util.get_module(
"numpy",
required="roc requires the numpy library, install with `pip install numpy`",
)
preprocessing = util.get_module(
"sklearn.preprocessing",
"roc requires the scikit preprocessing submodule, install with `pip install scikit-learn`",
)
metrics = util.get_module(
"sklearn.metrics",
"roc requires the scikit metrics submodule, install with `pip install scikit-learn`",
)
y_true = np.array(y_true)
y_probas = np.array(y_probas)
if test_missing(y_true=y_true, y_probas=y_probas) and test_types(
y_true=y_true, y_probas=y_probas
):
classes = np.unique(y_true)
probas = y_probas
if classes_to_plot is None:
classes_to_plot = classes
binarized_y_true = preprocessing.label_binarize(y_true, classes=classes)
if len(classes) == 2:
binarized_y_true = np.hstack((1 - binarized_y_true, binarized_y_true))
pr_curves = {}
indices_to_plot = np.in1d(classes, classes_to_plot)
for i, to_plot in enumerate(indices_to_plot):
if to_plot:
average_precision = metrics.average_precision_score(
binarized_y_true[:, i], probas[:, i]
)
precision, recall, _ = metrics.precision_recall_curve(
y_true, probas[:, i], pos_label=classes[i]
)
samples = 20
sample_precision = []
sample_recall = []
for k in range(samples):
sample_precision.append(
precision[int(len(precision) * k / samples)]
)
sample_recall.append(recall[int(len(recall) * k / samples)])
pr_curves[classes[i]] = (sample_precision, sample_recall)
def pr_table(pr_curves):
data = []
count = 0
for i, class_name in enumerate(pr_curves.keys()):
precision, recall = pr_curves[class_name]
for p, r in zip(precision, recall):
# if class_names are ints and labels are set
if labels is not None and (
isinstance(class_name, int)
or isinstance(class_name, np.integer)
):
class_name = labels[class_name]
# if class_names are ints and labels are not set
# or, if class_names have something other than ints
# (string, float, date) - user class_names
data.append([class_name, round(p, 3), round(r, 3)])
count += 1
if count >= chart_limit:
wandb.termwarn(
"wandb uses only the first %d datapoints to create the plots."
% wandb.Table.MAX_ROWS
)
break
return wandb.visualize(
"wandb/pr_curve/v1",
wandb.Table(columns=["class", "precision", "recall"], data=data),
)
return pr_table(pr_curves) | python | wandb/plots/precision_recall.py | 13 | 121 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,549 | pr_table | def pr_table(pr_curves):
data = []
count = 0
for i, class_name in enumerate(pr_curves.keys()):
precision, recall = pr_curves[class_name]
for p, r in zip(precision, recall):
# if class_names are ints and labels are set
if labels is not None and (
isinstance(class_name, int)
or isinstance(class_name, np.integer)
):
class_name = labels[class_name]
# if class_names are ints and labels are not set
# or, if class_names have something other than ints
# (string, float, date) - user class_names
data.append([class_name, round(p, 3), round(r, 3)])
count += 1
if count >= chart_limit:
wandb.termwarn(
"wandb uses only the first %d datapoints to create the plots."
% wandb.Table.MAX_ROWS
)
break
return wandb.visualize(
"wandb/pr_curve/v1",
wandb.Table(columns=["class", "precision", "recall"], data=data),
) | python | wandb/plots/precision_recall.py | 93 | 119 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,550 | roc | def roc(
y_true=None,
y_probas=None,
labels=None,
plot_micro=True,
plot_macro=True,
classes_to_plot=None,
):
"""
Calculates receiver operating characteristic scores and visualizes them as the
ROC curve.
Arguments:
y_true (arr): Test set labels.
y_probas (arr): Test set predicted probabilities.
labels (list): Named labels for target varible (y). Makes plots easier to
read by replacing target values with corresponding index.
For example labels= ['dog', 'cat', 'owl'] all 0s are
replaced by 'dog', 1s by 'cat'.
Returns:
Nothing. To see plots, go to your W&B run page then expand the 'media' tab
under 'auto visualizations'.
Example:
wandb.log({'roc': wandb.plots.ROC(y_true, y_probas, labels)})
"""
deprecation_notice()
np = util.get_module(
"numpy",
required="roc requires the numpy library, install with `pip install numpy`",
)
sklearn = util.get_module(
"sklearn",
required="roc requires the scikit library, install with `pip install scikit-learn`",
)
from sklearn.metrics import auc, roc_curve
if test_missing(y_true=y_true, y_probas=y_probas) and test_types(
y_true=y_true, y_probas=y_probas
):
y_true = np.array(y_true)
y_probas = np.array(y_probas)
classes = np.unique(y_true)
probas = y_probas
if classes_to_plot is None:
classes_to_plot = classes
fpr_dict = dict()
tpr_dict = dict()
indices_to_plot = np.in1d(classes, classes_to_plot)
def roc_table(fpr_dict, tpr_dict, classes, indices_to_plot):
data = []
count = 0
for i, to_plot in enumerate(indices_to_plot):
fpr_dict[i], tpr_dict[i], _ = roc_curve(
y_true, probas[:, i], pos_label=classes[i]
)
if to_plot:
roc_auc = auc(fpr_dict[i], tpr_dict[i])
for j in range(len(fpr_dict[i])):
if labels is not None and (
isinstance(classes[i], int)
or isinstance(classes[0], np.integer)
):
class_dict = labels[classes[i]]
else:
class_dict = classes[i]
fpr = [
class_dict,
round(fpr_dict[i][j], 3),
round(tpr_dict[i][j], 3),
]
data.append(fpr)
count += 1
if count >= chart_limit:
wandb.termwarn(
"wandb uses only the first %d datapoints to create the plots."
% wandb.Table.MAX_ROWS
)
break
return wandb.visualize(
"wandb/roc/v1", wandb.Table(columns=["class", "fpr", "tpr"], data=data)
)
return roc_table(fpr_dict, tpr_dict, classes, indices_to_plot) | python | wandb/plots/roc.py | 13 | 103 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,551 | roc_table | def roc_table(fpr_dict, tpr_dict, classes, indices_to_plot):
data = []
count = 0
for i, to_plot in enumerate(indices_to_plot):
fpr_dict[i], tpr_dict[i], _ = roc_curve(
y_true, probas[:, i], pos_label=classes[i]
)
if to_plot:
roc_auc = auc(fpr_dict[i], tpr_dict[i])
for j in range(len(fpr_dict[i])):
if labels is not None and (
isinstance(classes[i], int)
or isinstance(classes[0], np.integer)
):
class_dict = labels[classes[i]]
else:
class_dict = classes[i]
fpr = [
class_dict,
round(fpr_dict[i][j], 3),
round(tpr_dict[i][j], 3),
]
data.append(fpr)
count += 1
if count >= chart_limit:
wandb.termwarn(
"wandb uses only the first %d datapoints to create the plots."
% wandb.Table.MAX_ROWS
)
break
return wandb.visualize(
"wandb/roc/v1", wandb.Table(columns=["class", "fpr", "tpr"], data=data)
) | python | wandb/plots/roc.py | 68 | 101 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,552 | deprecation_notice | def deprecation_notice() -> None:
deprecate.deprecate(
field_name=deprecate.Deprecated.plots,
warning_message=(
"wandb.plots.* functions are deprecated and will be removed in a future release. "
"Please use wandb.plot.* instead."
),
) | python | wandb/plots/utils.py | 8 | 15 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,553 | test_missing | def test_missing(**kwargs):
np = util.get_module("numpy", required="Logging plots requires numpy")
pd = util.get_module("pandas", required="Logging dataframes requires pandas")
scipy = util.get_module("scipy", required="Logging scipy matrices requires scipy")
test_passed = True
for k, v in kwargs.items():
# Missing/empty params/datapoint arrays
if v is None:
wandb.termerror("%s is None. Please try again." % (k))
test_passed = False
if (k == "X") or (k == "X_test"):
if isinstance(v, scipy.sparse.csr.csr_matrix):
v = v.toarray()
elif isinstance(v, (pd.DataFrame, pd.Series)):
v = v.to_numpy()
elif isinstance(v, list):
v = np.asarray(v)
# Warn the user about missing values
missing = 0
missing = np.count_nonzero(pd.isnull(v))
if missing > 0:
wandb.termwarn("%s contains %d missing values. " % (k, missing))
test_passed = False
# Ensure the dataset contains only integers
non_nums = 0
if v.ndim == 1:
non_nums = sum(
1
for val in v
if (
not isinstance(val, (int, float, complex))
and not isinstance(val, np.number)
)
)
else:
non_nums = sum(
1
for sl in v
for val in sl
if (
not isinstance(val, (int, float, complex))
and not isinstance(val, np.number)
)
)
if non_nums > 0:
wandb.termerror(
"%s contains values that are not numbers. Please vectorize, label encode or one hot encode %s and call the plotting function again."
% (k, k)
)
test_passed = False
return test_passed | python | wandb/plots/utils.py | 19 | 71 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,554 | test_fitted | def test_fitted(model):
np = util.get_module("numpy", required="Logging plots requires numpy")
pd = util.get_module("pandas", required="Logging dataframes requires pandas")
scipy = util.get_module("scipy", required="Logging scipy matrices requires scipy")
scikit_utils = util.get_module(
"sklearn.utils",
required="roc requires the scikit utils submodule, install with `pip install scikit-learn`",
)
scikit_exceptions = util.get_module(
"sklearn.exceptions",
"roc requires the scikit preprocessing submodule, install with `pip install scikit-learn`",
)
try:
model.predict(np.zeros((7, 3)))
except scikit_exceptions.NotFittedError:
wandb.termerror("Please fit the model before passing it in.")
return False
except AttributeError:
# Some clustering models (LDA, PCA, Agglomerative) don't implement ``predict``
try:
scikit_utils.validation.check_is_fitted(
model,
[
"coef_",
"estimator_",
"labels_",
"n_clusters_",
"children_",
"components_",
"n_components_",
"n_iter_",
"n_batch_iter_",
"explained_variance_",
"singular_values_",
"mean_",
],
all_or_any=any,
)
return True
except scikit_exceptions.NotFittedError:
wandb.termerror("Please fit the model before passing it in.")
return False
except Exception:
# Assume it's fitted, since ``NotFittedError`` wasn't raised
return True | python | wandb/plots/utils.py | 74 | 119 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,555 | encode_labels | def encode_labels(df):
pd = util.get_module("pandas", required="Logging dataframes requires pandas")
preprocessing = util.get_module(
"sklearn.preprocessing",
"roc requires the scikit preprocessing submodule, install with `pip install scikit-learn`",
)
le = preprocessing.LabelEncoder()
# apply le on categorical feature columns
categorical_cols = df.select_dtypes(
exclude=["int", "float", "float64", "float32", "int32", "int64"]
).columns
df[categorical_cols] = df[categorical_cols].apply(lambda col: le.fit_transform(col)) | python | wandb/plots/utils.py | 122 | 134 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,556 | test_types | def test_types(**kwargs):
np = util.get_module("numpy", required="Logging plots requires numpy")
pd = util.get_module("pandas", required="Logging dataframes requires pandas")
scipy = util.get_module("scipy", required="Logging scipy matrices requires scipy")
base = util.get_module(
"sklearn.base",
"roc requires the scikit base submodule, install with `pip install scikit-learn`",
)
test_passed = True
for k, v in kwargs.items():
# check for incorrect types
if (
(k == "X")
or (k == "X_test")
or (k == "y")
or (k == "y_test")
or (k == "y_true")
or (k == "y_probas")
or (k == "x_labels")
or (k == "y_labels")
or (k == "matrix_values")
):
# FIXME: do this individually
if not isinstance(
v,
(
Sequence,
Iterable,
np.ndarray,
np.generic,
pd.DataFrame,
pd.Series,
list,
),
):
wandb.termerror("%s is not an array. Please try again." % (k))
test_passed = False
# check for classifier types
if k == "model":
if (not base.is_classifier(v)) and (not base.is_regressor(v)):
wandb.termerror(
"%s is not a classifier or regressor. Please try again." % (k)
)
test_passed = False
elif k == "clf" or k == "binary_clf":
if not (base.is_classifier(v)):
wandb.termerror("%s is not a classifier. Please try again." % (k))
test_passed = False
elif k == "regressor":
if not base.is_regressor(v):
wandb.termerror("%s is not a regressor. Please try again." % (k))
test_passed = False
elif k == "clusterer":
if not (getattr(v, "_estimator_type", None) == "clusterer"):
wandb.termerror("%s is not a clusterer. Please try again." % (k))
test_passed = False
return test_passed | python | wandb/plots/utils.py | 137 | 195 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,557 | explain_text | def explain_text(text, probas, target_names=None):
"""
ExplainText adds support for eli5's LIME based TextExplainer.
Arguments:
text (str): Text to explain
probas (black-box classification pipeline): A function which
takes a list of strings (documents) and returns a matrix
of shape (n_samples, n_classes) with probability values,
i.e. a row per document and a column per output label.
Returns:
Nothing. To see plots, go to your W&B run page.
Example:
wandb.log({'roc': wandb.plots.ExplainText(text, probas)})
"""
deprecation_notice()
eli5 = util.get_module(
"eli5",
required="explain_text requires the eli5 library, install with `pip install eli5`",
)
if test_missing(text=text, probas=probas):
# and test_types(proba=proba)):
wandb.termlog("Visualizing TextExplainer.")
te = eli5.lime.TextExplainer(random_state=42)
te.fit(text, probas)
html = te.show_prediction(target_names=target_names)
return wandb.Html(html.data) | python | wandb/plots/explain_text.py | 11 | 36 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,558 | part_of_speech | def part_of_speech(docs):
"""
Adds support for spaCy's dependency visualizer which shows
part-of-speech tags and syntactic dependencies.
Arguments:
docs (list, Doc, Span): Document(s) to visualize.
Returns:
Nothing. To see plots, go to your W&B run page.
Example:
wandb.log({'part_of_speech': wandb.plots.POS(docs=doc)})
"""
deprecation_notice()
spacy = util.get_module(
"spacy",
required="part_of_speech requires the spacy library, install with `pip install spacy`",
)
en_core_web_md = util.get_module(
"en_core_web_md",
required="part_of_speech requires the en_core_web_md library, install with `python -m spacy download en_core_web_md`",
)
nlp = en_core_web_md.load()
if test_missing(docs=docs):
# and test_types(docs=docs)):
wandb.termlog("Visualizing part of speech.")
options = {
"compact": True,
"color": "#1a1c1f",
"font": "Source Sans Pro",
"collapse_punct": True,
"collapse_phrases": True,
}
html = spacy.displacy.render(
nlp(str(docs)), style="dep", minify=True, options=options, page=True
)
return wandb.Html(html) | python | wandb/plots/part_of_speech.py | 11 | 50 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,559 | named_entity | def named_entity(docs):
"""
Adds support for spaCy's entity visualizer, which highlights named
entities and their labels in a text.
Arguments:
docs (list, Doc, Span): Document(s) to visualize.
Returns:
Nothing. To see plots, go to your W&B run page.
Example:
wandb.log({'NER': wandb.plots.NER(docs=doc)})
"""
deprecation_notice()
spacy = util.get_module(
"spacy",
required="part_of_speech requires the spacy library, install with `pip install spacy`",
)
en_core_web_md = util.get_module(
"en_core_web_md",
required="part_of_speech requires the en_core_web_md library, install with `python -m spacy download en_core_web_md`",
)
nlp = en_core_web_md.load()
if test_missing(docs=docs):
# and test_types(docs=docs)):
wandb.termlog("Visualizing named entity recognition.")
html = spacy.displacy.render(
nlp(str(docs)), style="ent", page=True, minify=True
)
return wandb.Html(html) | python | wandb/plots/named_entity.py | 11 | 43 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,560 | finalize_options | def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = ['graphql', '-vrsx']
self.test_suite = True | python | wandb/vendor/graphql-core-1.1/setup.py | 38 | 41 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,561 | run_tests | def run_tests(self):
#import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.test_args)
sys.exit(errno) | python | wandb/vendor/graphql-core-1.1/setup.py | 43 | 47 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,562 | graphql | def graphql(schema, request_string='', root_value=None, context_value=None,
variable_values=None, operation_name=None, executor=None,
return_promise=False, middleware=None):
try:
if isinstance(request_string, Document):
ast = request_string
else:
source = Source(request_string, 'GraphQL request')
ast = parse(source)
validation_errors = validate(schema, ast)
if validation_errors:
return ExecutionResult(
errors=validation_errors,
invalid=True,
)
return execute(
schema,
ast,
root_value,
context_value,
operation_name=operation_name,
variable_values=variable_values or {},
executor=executor,
return_promise=return_promise,
middleware=middleware,
)
except Exception as e:
return ExecutionResult(
errors=[e],
invalid=True,
) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/graphql.py | 30 | 60 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,563 | assert_valid_name | def assert_valid_name(name):
'''Helper to assert that provided names are valid.'''
assert COMPILED_NAME_PATTERN.match(name), 'Names must match /{}/ but "{}" does not.'.format(NAME_PATTERN, name) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/assert_valid_name.py | 7 | 9 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,564 | suggestion_list | def suggestion_list(inp, options):
'''
Given an invalid input string and a list of valid options, returns a filtered
list of valid options sorted based on their similarity with the input.
'''
options_by_distance = OrderedDict()
input_threshold = len(inp) / 2
for option in options:
distance = lexical_distance(inp, option)
threshold = max(input_threshold, len(option) / 2, 1)
if distance <= threshold:
options_by_distance[option] = distance
return sorted(list(options_by_distance.keys()), key=lambda k: options_by_distance[k]) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/suggestion_list.py | 4 | 18 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,565 | lexical_distance | def lexical_distance(a, b):
'''
Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or a swap of two
adjacent characters.
This distance can be useful for detecting typos in input or sorting
@returns distance in number of edits
'''
d = [[i] for i in range(len(a) + 1)] or []
d_len = len(d) or 1
for i in range(d_len):
for j in range(1, len(b) + 1):
if i == 0:
d[i].append(j)
else:
d[i].append(0)
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
d[i][j] = min(
d[i - 1][j] + 1,
d[i][j - 1] + 1,
d[i - 1][j - 1] + cost
)
if (i > 1 and j < 1 and
a[i - 1] == b[j - 2] and
a[i - 2] == b[j - 1]):
d[i][j] = min(d[i][j], d[i - 2][j - 2] + cost)
return d[len(a)][len(b)] | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/suggestion_list.py | 21 | 56 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,566 | ast_from_value | def ast_from_value(value, type=None):
if isinstance(type, GraphQLNonNull):
return ast_from_value(value, type.of_type)
if value is None:
return None
if isinstance(value, list):
item_type = type.of_type if isinstance(type, GraphQLList) else None
return ast.ListValue([ast_from_value(item, item_type) for item in value])
elif isinstance(type, GraphQLList):
return ast_from_value(value, type.of_type)
if isinstance(value, bool):
return ast.BooleanValue(value)
if isinstance(value, (int, float)):
string_num = str(value)
int_value = int(value)
is_int_value = string_num.isdigit()
if is_int_value or (int_value == value and value < sys.maxsize):
if type == GraphQLFloat:
return ast.FloatValue(str(float(value)))
return ast.IntValue(str(int(value)))
return ast.FloatValue(string_num)
if isinstance(value, str):
if isinstance(type, GraphQLEnumType) and re.match(r'^[_a-zA-Z][_a-zA-Z0-9]*$', value):
return ast.EnumValue(value)
return ast.StringValue(json.dumps(value)[1:-1])
assert isinstance(value, dict)
fields = []
is_graph_ql_input_object_type = isinstance(type, GraphQLInputObjectType)
for field_name, field_value in value.items():
field_type = None
if is_graph_ql_input_object_type:
field_def = type.fields.get(field_name)
field_type = field_def and field_def.type
field_value = ast_from_value(field_value, field_type)
if field_value:
fields.append(ast.ObjectField(
ast.Name(field_name),
field_value
))
return ast.ObjectValue(fields) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_from_value.py | 11 | 65 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,567 | is_valid_literal_value | def is_valid_literal_value(type, value_ast):
if isinstance(type, GraphQLNonNull):
of_type = type.of_type
if not value_ast:
return [u'Expected "{}", found null.'.format(type)]
return is_valid_literal_value(of_type, value_ast)
if not value_ast:
return _empty_list
if isinstance(value_ast, ast.Variable):
return _empty_list
if isinstance(type, GraphQLList):
item_type = type.of_type
if isinstance(value_ast, ast.ListValue):
errors = []
for i, item_ast in enumerate(value_ast.values):
item_errors = is_valid_literal_value(item_type, item_ast)
for error in item_errors:
errors.append(u'In element #{}: {}'.format(i, error))
return errors
return is_valid_literal_value(item_type, value_ast)
if isinstance(type, GraphQLInputObjectType):
if not isinstance(value_ast, ast.ObjectValue):
return [u'Expected "{}", found not an object.'.format(type)]
fields = type.fields
field_asts = value_ast.fields
errors = []
for provided_field_ast in field_asts:
if provided_field_ast.name.value not in fields:
errors.append(u'In field "{}": Unknown field.'.format(provided_field_ast.name.value))
field_ast_map = {field_ast.name.value: field_ast for field_ast in field_asts}
def get_field_ast_value(field_name):
if field_name in field_ast_map:
return field_ast_map[field_name].value
for field_name, field in fields.items():
subfield_errors = is_valid_literal_value(field.type, get_field_ast_value(field_name))
errors.extend(u'In field "{}": {}'.format(field_name, e) for e in subfield_errors)
return errors
assert isinstance(type, (GraphQLScalarType, GraphQLEnumType)), 'Must be input type'
parse_result = type.parse_literal(value_ast)
if parse_result is None:
return [u'Expected type "{}", found {}.'.format(type.name, print_ast(value_ast))]
return _empty_list | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_literal_value.py | 9 | 67 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,568 | get_field_ast_value | def get_field_ast_value(field_name):
if field_name in field_ast_map:
return field_ast_map[field_name].value | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_literal_value.py | 51 | 53 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,569 | pop | def pop(lst):
if lst:
lst.pop() | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 9 | 11 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,570 | __init__ | def __init__(self, schema, get_field_def_fn=get_field_def):
self._schema = schema
self._type_stack = []
self._parent_type_stack = []
self._input_type_stack = []
self._field_def_stack = []
self._directive = None
self._argument = None
self._get_field_def_fn = get_field_def_fn | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 19 | 27 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,571 | get_type | def get_type(self):
if self._type_stack:
return self._type_stack[-1] | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 29 | 31 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,572 | get_parent_type | def get_parent_type(self):
if self._parent_type_stack:
return self._parent_type_stack[-1] | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 33 | 35 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,573 | get_input_type | def get_input_type(self):
if self._input_type_stack:
return self._input_type_stack[-1] | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 37 | 39 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,574 | get_field_def | def get_field_def(self):
if self._field_def_stack:
return self._field_def_stack[-1] | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 41 | 43 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,575 | get_directive | def get_directive(self):
return self._directive | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 45 | 46 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,576 | get_argument | def get_argument(self):
return self._argument | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 48 | 49 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,577 | leave | def leave(self, node):
method = self._get_leave_handler(type(node))
if method:
return method(self) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 51 | 54 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,578 | enter | def enter(self, node):
method = self._get_enter_handler(type(node))
if method:
return method(self, node) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 56 | 59 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,579 | enter_SelectionSet | def enter_SelectionSet(self, node):
named_type = get_named_type(self.get_type())
composite_type = None
if is_composite_type(named_type):
composite_type = named_type
self._parent_type_stack.append(composite_type) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 61 | 66 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,580 | enter_Field | def enter_Field(self, node):
parent_type = self.get_parent_type()
field_def = None
if parent_type:
field_def = self._get_field_def_fn(self._schema, parent_type, node)
self._field_def_stack.append(field_def)
self._type_stack.append(field_def and field_def.type) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 68 | 74 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,581 | enter_Directive | def enter_Directive(self, node):
self._directive = self._schema.get_directive(node.name.value) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 76 | 77 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,582 | enter_OperationDefinition | def enter_OperationDefinition(self, node):
definition_type = None
if node.operation == 'query':
definition_type = self._schema.get_query_type()
elif node.operation == 'mutation':
definition_type = self._schema.get_mutation_type()
self._type_stack.append(definition_type) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 79 | 86 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,583 | enter_InlineFragment | def enter_InlineFragment(self, node):
type_condition_ast = node.type_condition
type = type_from_ast(self._schema, type_condition_ast) if type_condition_ast else self.get_type()
self._type_stack.append(type) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 88 | 91 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,584 | enter_VariableDefinition | def enter_VariableDefinition(self, node):
self._input_type_stack.append(type_from_ast(self._schema, node.type)) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 95 | 96 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,585 | enter_Argument | def enter_Argument(self, node):
arg_def = None
arg_type = None
field_or_directive = self.get_directive() or self.get_field_def()
if field_or_directive:
arg_def = field_or_directive.args.get(node.name.value)
if arg_def:
arg_type = arg_def.type
self._argument = arg_def
self._input_type_stack.append(arg_type) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 98 | 107 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,586 | enter_ListValue | def enter_ListValue(self, node):
list_type = get_nullable_type(self.get_input_type())
self._input_type_stack.append(
list_type.of_type if isinstance(list_type, GraphQLList) else None
) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 109 | 113 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,587 | enter_ObjectField | def enter_ObjectField(self, node):
object_type = get_named_type(self.get_input_type())
field_type = None
if isinstance(object_type, GraphQLInputObjectType):
input_field = object_type.fields.get(node.name.value)
field_type = input_field.type if input_field else None
self._input_type_stack.append(field_type) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 115 | 121 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,588 | leave_SelectionSet | def leave_SelectionSet(self):
pop(self._parent_type_stack) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 123 | 124 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,589 | leave_Field | def leave_Field(self):
pop(self._field_def_stack)
pop(self._type_stack) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 126 | 128 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,590 | leave_Directive | def leave_Directive(self):
self._directive = None | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 130 | 131 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,591 | leave_OperationDefinition | def leave_OperationDefinition(self):
pop(self._type_stack) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 133 | 134 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,592 | leave_VariableDefinition | def leave_VariableDefinition(self):
pop(self._input_type_stack) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 139 | 140 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,593 | leave_Argument | def leave_Argument(self):
self._argument = None
pop(self._input_type_stack) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 142 | 144 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,594 | leave_ListType | def leave_ListType(self):
pop(self._input_type_stack) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_info.py | 146 | 147 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,595 | is_valid_value | def is_valid_value(value, type):
"""Given a type and any value, return True if that value is valid."""
if isinstance(type, GraphQLNonNull):
of_type = type.of_type
if value is None:
return [u'Expected "{}", found null.'.format(type)]
return is_valid_value(value, of_type)
if value is None:
return _empty_list
if isinstance(type, GraphQLList):
item_type = type.of_type
if not isinstance(value, str) and isinstance(value, Iterable):
errors = []
for i, item in enumerate(value):
item_errors = is_valid_value(item, item_type)
for error in item_errors:
errors.append(u'In element #{}: {}'.format(i, error))
return errors
else:
return is_valid_value(value, item_type)
if isinstance(type, GraphQLInputObjectType):
if not isinstance(value, Mapping):
return [u'Expected "{}", found not an object.'.format(type)]
fields = type.fields
errors = []
for provided_field in sorted(value.keys()):
if provided_field not in fields:
errors.append(u'In field "{}": Unknown field.'.format(provided_field))
for field_name, field in fields.items():
subfield_errors = is_valid_value(value.get(field_name), field.type)
errors.extend(u'In field "{}": {}'.format(field_name, e) for e in subfield_errors)
return errors
assert isinstance(type, (GraphQLScalarType, GraphQLEnumType)), \
'Must be input type'
# Scalar/Enum input checks to ensure the type can parse the value to
# a non-null value.
parse_result = type.parse_value(value)
if parse_result is None:
return [u'Expected type "{}", found {}.'.format(type, json.dumps(value))]
return _empty_list | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/is_valid_value.py | 14 | 66 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,596 | get_field_def | def get_field_def(schema, parent_type, field_ast):
"""Not exactly the same as the executor's definition of get_field_def, in this
statically evaluated environment we do not always have an Object type,
and need to handle Interface and Union types."""
name = field_ast.name.value
if name == '__schema' and schema.get_query_type() == parent_type:
return SchemaMetaFieldDef
elif name == '__type' and schema.get_query_type() == parent_type:
return TypeMetaFieldDef
elif name == '__typename' and \
isinstance(parent_type, (
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLUnionType,
)):
return TypeNameMetaFieldDef
elif isinstance(parent_type, (GraphQLObjectType, GraphQLInterfaceType)):
return parent_type.fields.get(name) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_field_def.py | 7 | 27 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,597 | value_from_ast | def value_from_ast(value_ast, type, variables=None):
"""Given a type and a value AST node known to match this type, build a
runtime value."""
if isinstance(type, GraphQLNonNull):
# Note: we're not checking that the result of coerceValueAST is non-null.
# We're assuming that this query has been validated and the value used here is of the correct type.
return value_from_ast(value_ast, type.of_type, variables)
if not value_ast:
return None
if isinstance(value_ast, ast.Variable):
variable_name = value_ast.name.value
if not variables or variable_name not in variables:
return None
# Note: we're not doing any checking that this variable is correct. We're assuming that this query
# has been validated and the variable usage here is of the correct type.
return variables[variable_name]
if isinstance(type, GraphQLList):
item_type = type.of_type
if isinstance(value_ast, ast.ListValue):
return [value_from_ast(item_ast, item_type, variables)
for item_ast in value_ast.values]
else:
return [value_from_ast(value_ast, item_type, variables)]
if isinstance(type, GraphQLInputObjectType):
fields = type.fields
if not isinstance(value_ast, ast.ObjectValue):
return None
field_asts = {}
for field in value_ast.fields:
field_asts[field.name.value] = field
obj = {}
for field_name, field in fields.items():
field_ast = field_asts.get(field_name)
field_value_ast = None
if field_ast:
field_value_ast = field_ast.value
field_value = value_from_ast(
field_value_ast, field.type, variables
)
if field_value is None:
field_value = field.default_value
if field_value is not None:
# We use out_name as the output name for the
# dict if exists
obj[field.out_name or field_name] = field_value
return obj
assert isinstance(type, (GraphQLScalarType, GraphQLEnumType)), \
'Must be input type'
return type.parse_literal(value_ast) | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/value_from_ast.py | 6 | 69 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,598 | get_operation_ast | def get_operation_ast(document_ast, operation_name=None):
operation = None
for definition in document_ast.definitions:
if isinstance(definition, ast.OperationDefinition):
if not operation_name:
# If no operation name is provided, only return an Operation if it is the only one present in the
# document. This means that if we've encountered a second operation as we were iterating over the
# definitions in the document, there are more than one Operation defined, and we should return None.
if operation:
return None
operation = definition
elif definition.name and definition.name.value == operation_name:
return definition
return operation | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/get_operation_ast.py | 4 | 21 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,599 | is_equal_type | def is_equal_type(type_a, type_b):
if type_a is type_b:
return True
if isinstance(type_a, GraphQLNonNull) and isinstance(type_b, GraphQLNonNull):
return is_equal_type(type_a.of_type, type_b.of_type)
if isinstance(type_a, GraphQLList) and isinstance(type_b, GraphQLList):
return is_equal_type(type_a.of_type, type_b.of_type)
return False | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_comparators.py | 6 | 16 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
5,600 | is_type_sub_type_of | def is_type_sub_type_of(schema, maybe_subtype, super_type):
if maybe_subtype is super_type:
return True
if isinstance(super_type, GraphQLNonNull):
if isinstance(maybe_subtype, GraphQLNonNull):
return is_type_sub_type_of(schema, maybe_subtype.of_type, super_type.of_type)
return False
elif isinstance(maybe_subtype, GraphQLNonNull):
return is_type_sub_type_of(schema, maybe_subtype.of_type, super_type)
if isinstance(super_type, GraphQLList):
if isinstance(maybe_subtype, GraphQLList):
return is_type_sub_type_of(schema, maybe_subtype.of_type, super_type.of_type)
return False
elif isinstance(maybe_subtype, GraphQLList):
return False
if is_abstract_type(super_type) and isinstance(
maybe_subtype, GraphQLObjectType) and schema.is_possible_type(
super_type, maybe_subtype):
return True
return False | python | wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_comparators.py | 19 | 42 | {
"name": "Git-abouvier/wandb",
"url": "https://github.com/Git-abouvier/wandb.git",
"license": "MIT",
"stars": 0,
"forks": 0
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.