index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5,374 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/data/imaug/text_image_aug/augment.py | 23,24 | 1,124 | tia_distort | 24,68 | 24,68 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | img_h, img_w = src.shape[:2]
cut = img_w // segment
thresh = cut // 3
src_pts = list()
dst_pts = list()
src_pts.append([0, 0])
src_pts.append([img_w, 0])
src_pts.append([img_w, img_h])
src_pts.append([0, img_h])
dst_pts.append([np.random.randint(thresh), np.random.randint(thr... | img_h, img_w = src.shape[:2]
cut = img_w // segment
thresh = cut // 3
src_pts = list()
dst_pts = list()
src_pts.append([0, 0])
src_pts.append([img_w, 0])
src_pts.append([img_w, img_h])
src_pts.append([0, img_h])
dst_pts.append([np.random.randint(thresh), np.random.randint(thr... | 107 | 909 | 554 | 1,463 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | |
5,376 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/data/imaug/vqa/augment.py | 22,23 | 1,35 | order_by_tbyx | 23,35 | 23,35 | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | res = sorted(ocr_info, key=lambda r: (r["bbox"][1], r["bbox"][0]))
for i in range(len(res) - 1):
for j in range(i, 0, -1):
if abs(res[j + 1]["bbox"][1] - res[j]["bbox"][1]) < 20 and (
res[j + 1]["bbox"][0] < res[j]["bbox"][0]
):
tmp = deepcopy(res[... | res = sorted(ocr_info, key=lambda r: (r["bbox"][1], r["bbox"][0]))
for i in range(len(res) - 1):
for j in range(i, 0, -1):
if abs(res[j + 1]["bbox"][1] - res[j]["bbox"][1]) < 20 and (
res[j + 1]["bbox"][0] < res[j]["bbox"][0]
):
tmp = deepcopy(res[... | 52 | 213 | 192 | 405 | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | |
5,377 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/data/imaug/vqa/token/vqa_token_chunk.py | 129,130 | 52,135 | reformat | VQAReTokenChunk | 130,135 | 130,135 | class VQAReTokenChunk(object):
def __init__(
self, max_seq_len=512, entities_labels=None, infer_mode=False, **kwargs
):
self.max_seq_len = max_seq_len
self.entities_labels = (
{"HEADER": 0, "QUESTION": 1, "ANSWER": 2}
if entities_labels is None
else en... | class VQAReTokenChunk(object):
def __init__(
self, max_seq_len=512, entities_labels=None, infer_mode=False, **kwargs
):
self.max_seq_len = max_seq_len
self.entities_labels = (
{"HEADER": 0, "QUESTION": 1, "ANSWER": 2}
if entities_labels is None
else en... | new_data = defaultdict(list)
for item in data:
for k, v in item.items():
new_data[k].append(v)
return new_data
| new_data = defaultdict(list)
for item in data:
for k, v in item.items():
new_data[k].append(v)
return new_data
| 15 | 825 | 52 | 877 | # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... |
5,378 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/data/imaug/vqa/token/vqa_token_relation.py | 71,72 | 16,77 | get_relation_span | VQAReTokenRelation | 72,77 | 72,77 | class VQAReTokenRelation(object):
def __init__(self, **kwargs):
pass
def __call__(self, data):
"""
build relations
"""
entities = data["entities"]
relations = data["relations"]
id2label = data.pop("id2label")
empty_entity = data.pop("empty_entity"... | class VQAReTokenRelation(object):
def __init__(self, **kwargs):
pass
def __call__(self, data):
"""
build relations
"""
entities = data["entities"]
relations = data["relations"]
id2label = data.pop("id2label")
empty_entity = data.pop("empty_entity"... | bound = []
for entity_index in [rel["head"], rel["tail"]]:
bound.append(entities[entity_index]["start"])
bound.append(entities[entity_index]["end"])
return min(bound), max(bound)
| bound = []
for entity_index in [rel["head"], rel["tail"]]:
bound.append(entities[entity_index]["start"])
bound.append(entities[entity_index]["end"])
return min(bound), max(bound)
| 13 | 493 | 72 | 565 | # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... |
5,379 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/metrics/cls_metric.py | 36,37 | 16,49 | get_metric | ClsMetric | 42,46 | 37,46 | class ClsMetric(object):
def __init__(self, main_indicator="acc", **kwargs):
self.main_indicator = main_indicator
self.eps = 1e-5
self.reset()
def __call__(self, pred_label, *args, **kwargs):
preds, labels = pred_label
correct_num = 0
all_num = 0
for (pre... | class ClsMetric(object):
def __init__(self, main_indicator="acc", **kwargs):
self.main_indicator = main_indicator
self.eps = 1e-5
self.reset()
def __call__(self, pred_label, *args, **kwargs):
preds, labels = pred_label
correct_num = 0
all_num = 0
for (pre... | acc = self.correct_num / (self.all_num + self.eps)
self.reset()
return {"acc": acc}
| """
return metrics {
'acc': 0
}
"""
acc = self.correct_num / (self.all_num + self.eps)
self.reset()
return {"acc": acc}
| 11 | 257 | 40 | 297 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... |
5,380 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/metrics/ct_metric.py | 45,46 | 26,52 | get_metric | CTMetric | 49,52 | 46,52 | class CTMetric(object):
def __init__(self, main_indicator, delimiter="\t", **kwargs):
self.delimiter = delimiter
self.main_indicator = main_indicator
self.reset()
def reset(self):
self.results = [] # clear results
def __call__(self, preds, batch, **kwargs):
# NOTE:... | class CTMetric(object):
def __init__(self, main_indicator, delimiter="\t", **kwargs):
self.delimiter = delimiter
self.main_indicator = main_indicator
self.reset()
def reset(self):
self.results = [] # clear results
def __call__(self, preds, batch, **kwargs):
# NOTE:... | metrics = combine_results(self.results, rec_flag=False)
self.reset()
return metrics
| """
Input format: y0,x0, ..... yn,xn. Each detection is separated by the end of line token ('\n')'
"""
metrics = combine_results(self.results, rec_flag=False)
self.reset()
return metrics
| 7 | 266 | 31 | 297 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... |
5,381 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/metrics/det_metric.py | 144,145 | 74,154 | reset | DetFCEMetric | 145,154 | 145,154 | class DetFCEMetric(object):
def __init__(self, main_indicator="hmean", **kwargs):
self.evaluator = DetectionIoUEvaluator()
self.main_indicator = main_indicator
self.reset()
def __call__(self, preds, batch, **kwargs):
"""
batch: a list produced by dataloaders.
... | class DetFCEMetric(object):
def __init__(self, main_indicator="hmean", **kwargs):
self.evaluator = DetectionIoUEvaluator()
self.main_indicator = main_indicator
self.reset()
def __call__(self, preds, batch, **kwargs):
"""
batch: a list produced by dataloaders.
... | self.results = {
0.3: [],
0.4: [],
0.5: [],
0.6: [],
0.7: [],
0.8: [],
0.9: [],
} # clear results
| self.results = {
0.3: [],
0.4: [],
0.5: [],
0.6: [],
0.7: [],
0.8: [],
0.9: [],
} # clear results
| 21 | 933 | 72 | 1,005 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... |
5,382 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/metrics/det_metric.py | 70,71 | 24,74 | reset | DetMetric | 71,74 | 71,74 | class DetMetric(object):
def __init__(self, main_indicator="hmean", **kwargs):
self.evaluator = DetectionIoUEvaluator()
self.main_indicator = main_indicator
self.reset()
def __call__(self, preds, batch, **kwargs):
"""
batch: a list produced by dataloaders.
im... | class DetMetric(object):
def __init__(self, main_indicator="hmean", **kwargs):
self.evaluator = DetectionIoUEvaluator()
self.main_indicator = main_indicator
self.reset()
def __call__(self, preds, batch, **kwargs):
"""
batch: a list produced by dataloaders.
im... | self.results = [] # clear results
| self.results = [] # clear results
| 6 | 540 | 16 | 556 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... |
5,383 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/metrics/distillation_metric.py | 52,53 | 26,73 | get_metric | DistillationMetric | 59,70 | 53,70 | class DistillationMetric(object):
def __init__(self, key=None, base_metric_name=None, main_indicator=None, **kwargs):
self.main_indicator = main_indicator
self.key = key
self.main_indicator = main_indicator
self.base_metric_name = base_metric_name
self.kwargs = kwargs
... | class DistillationMetric(object):
def __init__(self, key=None, base_metric_name=None, main_indicator=None, **kwargs):
self.main_indicator = main_indicator
self.key = key
self.main_indicator = main_indicator
self.base_metric_name = base_metric_name
self.kwargs = kwargs
... | output = dict()
for key in self.metrics:
metric = self.metrics[key].get_metric()
# main indicator
if key == self.key:
output.update(metric)
else:
for sub_key in metric:
output["{}_{}".format(key, sub_key)... | """
return metrics {
'acc': 0,
'norm_edit_dis': 0,
}
"""
output = dict()
for key in self.metrics:
metric = self.metrics[key].get_metric()
# main indicator
if key == self.key:
output.... | 29 | 375 | 105 | 480 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... |
5,384 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/metrics/e2e_metric.py | 82,83 | 25,89 | get_metric | E2EMetric | 83,87 | 83,87 | class E2EMetric(object):
def __init__(
self,
mode,
gt_mat_dir,
character_dict_path,
main_indicator="f_score_e2e",
**kwargs
):
self.mode = mode
self.gt_mat_dir = gt_mat_dir
self.label_list = get_dict(character_dict_path)
self.max_ind... | class E2EMetric(object):
def __init__(
self,
mode,
gt_mat_dir,
character_dict_path,
main_indicator="f_score_e2e",
**kwargs
):
self.mode = mode
self.gt_mat_dir = gt_mat_dir
self.label_list = get_dict(character_dict_path)
self.max_ind... | metrics = combine_results(self.results)
self.reset()
return metrics
| metrics = combine_results(self.results)
self.reset()
return metrics
| 6 | 682 | 27 | 709 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... |
5,386 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/metrics/table_metric.py | 99,100 | 73,162 | prepare_bbox_metric_input | TableMetric | 100,128 | 100,128 | class TableMetric(object):
def __init__(
self,
main_indicator="acc",
compute_bbox_metric=False,
box_format="xyxy",
del_thead_tbody=False,
**kwargs
):
"""
@param sub_metrics: configs of sub_metric
@param main_matric: main_matric for save be... | class TableMetric(object):
def __init__(
self,
main_indicator="acc",
compute_bbox_metric=False,
box_format="xyxy",
del_thead_tbody=False,
**kwargs
):
"""
@param sub_metrics: configs of sub_metric
@param main_matric: main_matric for save be... | pred_bbox_batch_list = []
gt_ignore_tags_batch_list = []
gt_bbox_batch_list = []
preds, labels = pred_label
batch_num = len(preds["bbox_batch_list"])
for batch_idx in range(batch_num):
# pred
pred_bbox_list = [
self.format_box(pred... | pred_bbox_batch_list = []
gt_ignore_tags_batch_list = []
gt_bbox_batch_list = []
preds, labels = pred_label
batch_num = len(preds["bbox_batch_list"])
for batch_idx in range(batch_num):
# pred
pred_bbox_list = [
self.format_box(pred... | 57 | 768 | 365 | 1,133 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... |
5,387 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/metrics/table_metric.py | 65,66 | 18,73 | reset | TableStructureMetric | 66,73 | 66,73 | class TableStructureMetric(object):
def __init__(self, main_indicator="acc", eps=1e-6, del_thead_tbody=False, **kwargs):
self.main_indicator = main_indicator
self.eps = eps
self.del_thead_tbody = del_thead_tbody
self.reset()
def __call__(self, pred_label, batch=None, *args, **kw... | class TableStructureMetric(object):
def __init__(self, main_indicator="acc", eps=1e-6, del_thead_tbody=False, **kwargs):
self.main_indicator = main_indicator
self.eps = eps
self.del_thead_tbody = del_thead_tbody
self.reset()
def __call__(self, pred_label, batch=None, *args, **kw... | self.correct_num = 0
self.all_num = 0
self.len_acc_num = 0
self.token_nums = 0
self.anys_dict = dict()
| self.correct_num = 0
self.all_num = 0
self.len_acc_num = 0
self.token_nums = 0
self.anys_dict = dict()
| 15 | 497 | 58 | 555 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... |
5,388 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/postprocess/locality_aware_nms.py | 89,90 | 1,199 | nms | 93,106 | 90,106 | """
Locality aware nms.
This code is refered from: https://github.com/songdejia/EAST/blob/master/locality_aware_nms.py
"""
import numpy as np
from shapely.geometry import Polygon
def intersection(g, p):
"""
Intersection.
"""
g = Polygon(g[:8].reshape((4, 2)))
p = Polygon(p[:8].reshape((4, 2)))
... | """
Locality aware nms.
This code is refered from: https://github.com/songdejia/EAST/blob/master/locality_aware_nms.py
"""
import numpy as np
from shapely.geometry import Polygon
def intersection(g, p):
"""
Intersection.
"""
g = Polygon(g[:8].reshape((4, 2)))
p = Polygon(p[:8].reshape((4, 2)))
... | order = np.argsort(S[:, 8])[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
ovr = np.array([intersection(S[i], S[t]) for t in order[1:]])
inds = np.where(ovr <= thres)[0]
order = order[inds + 1]
return keep
| """
nms.
"""
order = np.argsort(S[:, 8])[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
ovr = np.array([intersection(S[i], S[t]) for t in order[1:]])
inds = np.where(ovr <= thres)[0]
order = order[inds + 1]
return keep
| 35 | 1,764 | 127 | 1,891 | """
Locality aware nms.
This code is refered from: https://github.com/songdejia/EAST/blob/master/locality_aware_nms.py
"""
import numpy as np
from shapely.geometry import Polygon
def intersection(g, p):
"""
Intersection.
"""
g = Polygon(g[:8].reshape((4, 2)))
p = Polygon(p[:8].reshape((4, 2)))
... | """
Locality aware nms.
This code is refered from: https://github.com/songdejia/EAST/blob/master/locality_aware_nms.py
"""
import numpy as np
from shapely.geometry import Polygon
def intersection(g, p):
"""
Intersection.
"""
g = Polygon(g[:8].reshape((4, 2)))
p = Polygon(p[:8].reshape((4, 2)))
... | |
5,391 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/utils/e2e_metric/polygon_fast.py | 62,63 | 1,85 | area_of_intersection | 63,68 | 63,68 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | p1 = Polygon(np.stack([det_x, det_y], axis=1)).buffer(0)
p2 = Polygon(np.stack([gt_x, gt_y], axis=1)).buffer(0)
return float(p1.intersection(p2).area)
| p1 = Polygon(np.stack([det_x, det_y], axis=1)).buffer(0)
p2 = Polygon(np.stack([gt_x, gt_y], axis=1)).buffer(0)
return float(p1.intersection(p2).area)
| 12 | 1,056 | 80 | 1,136 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | |
5,392 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/utils/gen_label.py | 29,30 | 1,83 | gen_det_label | 30,53 | 30,53 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | with open(out_label, "w") as out_file:
for label_file in os.listdir(input_dir):
img_path = os.path.join(root_path, label_file[3:-4] + ".jpg")
label = []
with open(
os.path.join(input_dir, label_file), "r", encoding="utf-8-sig"
) as f:
... | with open(out_label, "w") as out_file:
for label_file in os.listdir(input_dir):
img_path = os.path.join(root_path, label_file[3:-4] + ".jpg")
label = []
with open(
os.path.join(input_dir, label_file), "r", encoding="utf-8-sig"
) as f:
... | 79 | 629 | 299 | 928 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | |
5,393 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/utils/loggers/loggers.py | 9,10 | 4,20 | log_metrics | Loggers | 10,13 | 10,13 | class Loggers(object):
def __init__(self, loggers):
super().__init__()
self.loggers = loggers
def log_metrics(self, metrics, prefix=None, step=None):
FILL_FUNC_BODY def log_model(self, is_best, prefix, metadata=None):
for logger in self.loggers:
logger.log_model(is_best=i... | class Loggers(object):
def __init__(self, loggers):
super().__init__()
self.loggers = loggers
def log_metrics(self, metrics, prefix=None, step=None):
FILL_FUNC_BODY def log_model(self, is_best, prefix, metadata=None):
for logger in self.loggers:
logger.log_model(is_best=i... | for logger in self.loggers:
logger.log_metrics(metrics, prefix=prefix, step=step)
| for logger in self.loggers:
logger.log_metrics(metrics, prefix=prefix, step=step)
| 7 | 143 | 34 | 177 | from .wandb_logger import WandbLogger
class Loggers(object):
def __init__(self, loggers):
super().__init__()
self.loggers = loggers
def log_metrics(self, metrics, prefix=None, step=None):
FILL_FUNC_BODY def log_model(self, is_best, prefix, metadata=None):
for logger in self.loggers... | from .wandb_logger import WandbLogger
class Loggers(object):
def __init__(self, loggers):
super().__init__()
self.loggers = loggers
def log_metrics(self, metrics, prefix=None, step=None):
FILL_FUNC_BODY def log_model(self, is_best, prefix, metadata=None):
for logger in self.loggers... |
5,394 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/utils/poly_nms.py | 127,128 | 1,147 | poly_nms | 128,147 | 128,147 | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | assert isinstance(polygons, list)
polygons = np.array(sorted(polygons, key=lambda x: x[-1]))
keep_poly = []
index = [i for i in range(polygons.shape[0])]
while len(index) > 0:
keep_poly.append(polygons[index[-1]].tolist())
A = polygons[index[-1]][:-1]
index = np.delete(ind... | assert isinstance(polygons, list)
polygons = np.array(sorted(polygons, key=lambda x: x[-1]))
keep_poly = []
index = [i for i in range(polygons.shape[0])]
while len(index) > 0:
keep_poly.append(polygons[index[-1]].tolist())
A = polygons[index[-1]][:-1]
index = np.delete(ind... | 56 | 1,120 | 246 | 1,366 | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | |
5,395 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/utils/stats.py | 37,38 | 1,71 | Time | 38,41 | 38,41 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
| return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
| 3 | 679 | 37 | 716 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | |
5,396 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/utils/stats.py | 30,31 | 22,37 | add_value | SmoothedValue | 31,33 | 31,33 | class SmoothedValue(object):
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self, window_size):
self.deque = collections.deque(maxlen=window_size)
def add_value(self, value):
FILL_FUNC_BODY def get_median_va... | class SmoothedValue(object):
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self, window_size):
self.deque = collections.deque(maxlen=window_size)
def add_value(self, value):
FILL_FUNC_BODY def get_median_va... | self.deque.append(value)
| self.deque.append(value)
| 1 | 120 | 14 | 134 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... |
5,397 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppocr/utils/stats.py | 48,49 | 41,71 | update | TrainingStats | 49,54 | 49,54 | class TrainingStats(object):
def __init__(self, window_size, stats_keys):
self.window_size = window_size
self.smoothed_losses_and_metrics = {
key: SmoothedValue(window_size) for key in stats_keys
}
def update(self, stats):
FILL_FUNC_BODY def get(self, extras=None):
... | class TrainingStats(object):
def __init__(self, window_size, stats_keys):
self.window_size = window_size
self.smoothed_losses_and_metrics = {
key: SmoothedValue(window_size) for key in stats_keys
}
def update(self, stats):
FILL_FUNC_BODY def get(self, extras=None):
... | for k, v in stats.items():
if k not in self.smoothed_losses_and_metrics:
self.smoothed_losses_and_metrics[k] = SmoothedValue(self.window_size)
self.smoothed_losses_and_metrics[k].add_value(v)
| for k, v in stats.items():
if k not in self.smoothed_losses_and_metrics:
self.smoothed_losses_and_metrics[k] = SmoothedValue(self.window_size)
self.smoothed_losses_and_metrics[k].add_value(v)
| 14 | 272 | 91 | 363 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... |
5,398 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppstructure/kie/tools/trans_funsd_label.py | 31,32 | 1,167 | get_outer_poly | 32,39 | 32,39 | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | x1 = min([bbox[0] for bbox in bbox_list])
y1 = min([bbox[1] for bbox in bbox_list])
x2 = max([bbox[2] for bbox in bbox_list])
y2 = max([bbox[3] for bbox in bbox_list])
return [[x1, y1], [x2, y1], [x2, y2], [x1, y2]]
| x1 = min([bbox[0] for bbox in bbox_list])
y1 = min([bbox[1] for bbox in bbox_list])
x2 = max([bbox[2] for bbox in bbox_list])
y2 = max([bbox[3] for bbox in bbox_list])
return [[x1, y1], [x2, y1], [x2, y2], [x1, y2]]
| 37 | 1,846 | 124 | 1,970 | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | |
5,399 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppstructure/kie/tools/trans_xfun_data.py | 51,52 | 1,65 | parser_args | 52,63 | 52,63 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | import argparse
parser = argparse.ArgumentParser(description="args for paddleserving")
parser.add_argument(
"--ori_gt_path", type=str, required=True, help="origin xfun gt path"
)
parser.add_argument("--output_path", type=str, required=True, help="path to save")
args = parser.parse_args(... | import argparse
parser = argparse.ArgumentParser(description="args for paddleserving")
parser.add_argument(
"--ori_gt_path", type=str, required=True, help="origin xfun gt path"
)
parser.add_argument("--output_path", type=str, required=True, help="path to save")
args = parser.parse_args(... | 27 | 546 | 120 | 666 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | |
5,400 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppstructure/table/convert_label2html.py | 40,41 | 1,103 | gen_html | 44,60 | 41,60 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | html_code = img["html"]["structure"]["tokens"].copy()
to_insert = [i for i, tag in enumerate(html_code) if tag in ("<td>", ">")]
for i, cell in zip(to_insert[::-1], img["html"]["cells"][::-1]):
if cell["tokens"]:
text = "".join(cell["tokens"])
# skip empty text
sp... | """
Formats HTML code from tokenized annotation of img
"""
html_code = img["html"]["structure"]["tokens"].copy()
to_insert = [i for i, tag in enumerate(html_code) if tag in ("<td>", ">")]
for i, cell in zip(to_insert[::-1], img["html"]["cells"][::-1]):
if cell["tokens"]:
text... | 61 | 786 | 270 | 1,056 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | |
5,402 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppstructure/table/matcher.py | 103,104 | 57,204 | get_pred_html | TableMatch | 104,148 | 104,148 | class TableMatch:
def __init__(self, filter_ocr_result=False, use_master=False):
self.filter_ocr_result = filter_ocr_result
self.use_master = use_master
def __call__(self, structure_res, dt_boxes, rec_res):
pred_structures, pred_bboxes = structure_res
if self.filter_ocr_result:
... | class TableMatch:
def __init__(self, filter_ocr_result=False, use_master=False):
self.filter_ocr_result = filter_ocr_result
self.use_master = use_master
def __call__(self, structure_res, dt_boxes, rec_res):
pred_structures, pred_bboxes = structure_res
if self.filter_ocr_result:
... | end_html = []
td_index = 0
for tag in pred_structures:
if "</td>" in tag:
if "<td></td>" == tag:
end_html.extend("<td>")
if td_index in matched_index.keys():
b_with = False
if (
... | end_html = []
td_index = 0
for tag in pred_structures:
if "</td>" in tag:
if "<td></td>" == tag:
end_html.extend("<td>")
if td_index in matched_index.keys():
b_with = False
if (
... | 120 | 1,225 | 487 | 1,712 | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... | # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... |
5,405 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppstructure/table/table_metric/parallel.py | 5,6 | 1,56 | parallel_process | 19,56 | 6,56 | from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
def parallel_process(array, function, n_jobs=16, use_kwargs=False, front_num=0):
FILL_FUNC_BODY | from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
def parallel_process(array, function, n_jobs=16, use_kwargs=False, front_num=0):
"""
A parallel version of the map function with a progress bar.
Args:
array (array-like): An array to iterate over.
functi... | # We run the first few iterations serially to catch bugs
if front_num > 0:
front = [
function(**a) if use_kwargs else function(a) for a in array[:front_num]
]
else:
front = []
# If we set n_jobs to 1, just run a list comprehension. This is useful for benchmarking and ... | """
A parallel version of the map function with a progress bar.
Args:
array (array-like): An array to iterate over.
function (function): A python function to apply to the elements of array
n_jobs (int, default=16): The number of cores to use
use_kwargs (boolean, default=False... | 156 | 231 | 429 | 660 | from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
def parallel_process(array, function, n_jobs=16, use_kwargs=False, front_num=0):
FILL_FUNC_BODY | from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
def parallel_process(array, function, n_jobs=16, use_kwargs=False, front_num=0):
"""
A parallel version of the map function with a progress bar.
Args:
array (array-like): An array to iterate over.
functi... | |
5,407 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppstructure/table/tablepyxl/style.py | 198,199 | 182,220 | style | Element | 202,208 | 199,208 | class Element(object):
"""
Our base class for representing an html element along with a cascading style.
The element is created along with a parent so that the StyleDict that we store
can point to the parent's StyleDict.
"""
def __init__(self, element, parent=None):
self.element = eleme... | class Element(object):
"""
Our base class for representing an html element along with a cascading style.
The element is created along with a parent so that the StyleDict that we store
can point to the parent's StyleDict.
"""
def __init__(self, element, parent=None):
self.element = eleme... | if not self._style_cache:
self._style_cache = style_dict_to_named_style(
self.style_dict, number_format=self.number_format
)
return self._style_cache
| """
Turn the css styles for this element into an openpyxl NamedStyle.
"""
if not self._style_cache:
self._style_cache = style_dict_to_named_style(
self.style_dict, number_format=self.number_format
)
return self._style_cache
| 11 | 309 | 63 | 372 | # This is where we handle translating css styles into openpyxl styles
# and cascading those from parent to child in the dom.
try:
from openpyxl.cell import cell
from openpyxl.styles import (
Font,
Alignment,
PatternFill,
NamedStyle,
Border,
Side,
Color,
... | # This is where we handle translating css styles into openpyxl styles
# and cascading those from parent to child in the dom.
try:
from openpyxl.cell import cell
from openpyxl.styles import (
Font,
Alignment,
PatternFill,
NamedStyle,
Border,
Side,
Color,
... |
5,408 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppstructure/table/tablepyxl/style.py | 162,163 | 128,182 | get | StyleDict | 163,168 | 163,168 | class StyleDict(dict):
"""
It's like a dictionary, but it looks for items in the parent dictionary
"""
def __init__(self, *args, **kwargs):
self.parent = kwargs.pop("parent", None)
super(StyleDict, self).__init__(*args, **kwargs)
def __getitem__(self, item):
if item in self... | class StyleDict(dict):
"""
It's like a dictionary, but it looks for items in the parent dictionary
"""
def __init__(self, *args, **kwargs):
self.parent = kwargs.pop("parent", None)
super(StyleDict, self).__init__(*args, **kwargs)
def __getitem__(self, item):
if item in self... | try:
return self[k]
except KeyError:
return d
| try:
return self[k]
except KeyError:
return d
| 7 | 479 | 27 | 506 | # This is where we handle translating css styles into openpyxl styles
# and cascading those from parent to child in the dom.
try:
from openpyxl.cell import cell
from openpyxl.styles import (
Font,
Alignment,
PatternFill,
NamedStyle,
Border,
Side,
Color,
... | # This is where we handle translating css styles into openpyxl styles
# and cascading those from parent to child in the dom.
try:
from openpyxl.cell import cell
from openpyxl.styles import (
Font,
Alignment,
PatternFill,
NamedStyle,
Border,
Side,
Color,
... |
5,409 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/ppstructure/table/tablepyxl/style.py | 328,329 | 290,350 | get_number_format | TableCell | 329,345 | 329,345 | class TableCell(Element):
"""
This class maps to the `<td>` element of the html table.
"""
CELL_TYPES = {
"TYPE_STRING",
"TYPE_FORMULA",
"TYPE_NUMERIC",
"TYPE_BOOL",
"TYPE_CURRENCY",
"TYPE_PERCENTAGE",
"TYPE_NULL",
"TYPE_INLINE",
"... | class TableCell(Element):
"""
This class maps to the `<td>` element of the html table.
"""
CELL_TYPES = {
"TYPE_STRING",
"TYPE_FORMULA",
"TYPE_NUMERIC",
"TYPE_BOOL",
"TYPE_CURRENCY",
"TYPE_PERCENTAGE",
"TYPE_NULL",
"TYPE_INLINE",
"... | if "TYPE_CURRENCY" in self.element.get("class", "").split():
return FORMAT_CURRENCY_USD_SIMPLE
if "TYPE_INTEGER" in self.element.get("class", "").split():
return "#,##0"
if "TYPE_PERCENTAGE" in self.element.get("class", "").split():
return FORMAT_PERCENTAGE
... | if "TYPE_CURRENCY" in self.element.get("class", "").split():
return FORMAT_CURRENCY_USD_SIMPLE
if "TYPE_INTEGER" in self.element.get("class", "").split():
return "#,##0"
if "TYPE_PERCENTAGE" in self.element.get("class", "").split():
return FORMAT_PERCENTAGE
... | 41 | 458 | 217 | 675 | # This is where we handle translating css styles into openpyxl styles
# and cascading those from parent to child in the dom.
try:
from openpyxl.cell import cell
from openpyxl.styles import (
Font,
Alignment,
PatternFill,
NamedStyle,
Border,
Side,
Color,
... | # This is where we handle translating css styles into openpyxl styles
# and cascading those from parent to child in the dom.
try:
from openpyxl.cell import cell
from openpyxl.styles import (
Font,
Alignment,
PatternFill,
NamedStyle,
Border,
Side,
Color,
... |
5,410 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/setup.py | 30,31 | 1,81 | load_requirements | 31,42 | 31,42 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | if file_list is None:
file_list = ["requirements.txt"]
if isinstance(file_list, str):
file_list = [file_list]
requirements = []
for file in file_list:
with open(file, encoding="utf-8-sig") as f:
requirements.extend(f.readlines())
return requirements
| if file_list is None:
file_list = ["requirements.txt"]
if isinstance(file_list, str):
file_list = [file_list]
requirements = []
for file in file_list:
with open(file, encoding="utf-8-sig") as f:
requirements.extend(f.readlines())
return requirements
| 28 | 819 | 105 | 924 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | |
5,411 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/tools/end2end/convert_ppocr_label.py | 27,28 | 1,104 | convert_label | 28,90 | 28,90 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | if not os.path.exists(label_dir):
raise ValueError(f"The file {label_dir} does not exist!")
assert label_dir != save_dir, "hahahhaha"
label_file = open(label_dir, "r")
data = label_file.readlines()
gt_dict = {}
for line in data:
try:
tmp = line.split("\t")
... | if not os.path.exists(label_dir):
raise ValueError(f"The file {label_dir} does not exist!")
assert label_dir != save_dir, "hahahhaha"
label_file = open(label_dir, "r")
data = label_file.readlines()
gt_dict = {}
for line in data:
try:
tmp = line.split("\t")
... | 187 | 421 | 669 | 1,090 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | |
5,412 | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR | /home/hieuvd/dung_repo/raw/stars_01/PaddlePaddle_PaddleOCR/PaddleOCR/tools/end2end/draw_html.py | 23,24 | 1,73 | init_args | 24,31 | 24,31 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | parser = argparse.ArgumentParser()
parser.add_argument("--image_dir", type=str, default="")
parser.add_argument("--save_html_path", type=str, default="./default.html")
parser.add_argument("--width", type=int, default=640)
return parser
| parser = argparse.ArgumentParser()
parser.add_argument("--image_dir", type=str, default="")
parser.add_argument("--save_html_path", type=str, default="./default.html")
parser.add_argument("--width", type=int, default=640)
return parser
| 14 | 655 | 92 | 747 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | |
5,568 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/scripts/generate-lower-bounds.py | 48,49 | 1,83 | generate_lower_bounds | 49,78 | 49,78 | #!/usr/bin/env python3
"""
This helper script compiles all of our lower version bounds on all base dependencies
from our `requirements.txt` file into a new file which is printed to stdout. In this
new requirements file all dependencies are pinned to their lowest allowed versions.
We use this new requirements file to t... | #!/usr/bin/env python3
"""
This helper script compiles all of our lower version bounds on all base dependencies
from our `requirements.txt` file into a new file which is printed to stdout. In this
new requirements file all dependencies are pinned to their lowest allowed versions.
We use this new requirements file to t... | for line in input_file:
output_line = ""
# Split the package name and versions from the conditional section
requirement_package, _, requirement_condition = line.partition(";")
# Parse the package name and lower bound
lower_bound_match = LOWER_BOUND_RE.match(requirement_pack... | for line in input_file:
output_line = ""
# Split the package name and versions from the conditional section
requirement_package, _, requirement_condition = line.partition(";")
# Parse the package name and lower bound
lower_bound_match = LOWER_BOUND_RE.match(requirement_pack... | 85 | 524 | 282 | 806 | #!/usr/bin/env python3
"""
This helper script compiles all of our lower version bounds on all base dependencies
from our `requirements.txt` file into a new file which is printed to stdout. In this
new requirements file all dependencies are pinned to their lowest allowed versions.
We use this new requirements file to t... | #!/usr/bin/env python3
"""
This helper script compiles all of our lower version bounds on all base dependencies
from our `requirements.txt` file into a new file which is printed to stdout. In this
new requirements file all dependencies are pinned to their lowest allowed versions.
We use this new requirements file to t... | |
5,570 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/scripts/generate_integration_package_tests_matrix.py | 19,20 | 1,53 | get_changed_packages | 20,37 | 20,37 | import json
import subprocess
import sys
from typing import Dict, List, Set
PYTHON_VERSIONS = [
"3.8",
"3.9",
"3.10",
"3.11",
"3.12",
]
SKIP_VERSIONS = {
"prefect-ray": ["3.8", "3.12"],
}
def get_changed_packages(commit_range: str) -> List[str]:
FILL_FUNC_BODYdef generate_matrix(packages: Li... | import json
import subprocess
import sys
from typing import Dict, List, Set
PYTHON_VERSIONS = [
"3.8",
"3.9",
"3.10",
"3.11",
"3.12",
]
SKIP_VERSIONS = {
"prefect-ray": ["3.8", "3.12"],
}
def get_changed_packages(commit_range: str) -> List[str]:
FILL_FUNC_BODYdef generate_matrix(packages: Li... | # Get the list of changed files in the specified commit range
result = subprocess.run(
["git", "diff", "--name-only", commit_range],
capture_output=True,
text=True,
check=True,
)
changed_files = result.stdout.split()
# Filter for src/integrations directories
packa... | # Get the list of changed files in the specified commit range
result = subprocess.run(
["git", "diff", "--name-only", commit_range],
capture_output=True,
text=True,
check=True,
)
changed_files = result.stdout.split()
# Filter for src/integrations directories
packa... | 57 | 334 | 180 | 514 | import json
import subprocess
import sys
from typing import Dict, List, Set
PYTHON_VERSIONS = [
"3.8",
"3.9",
"3.10",
"3.11",
"3.12",
]
SKIP_VERSIONS = {
"prefect-ray": ["3.8", "3.12"],
}
def get_changed_packages(commit_range: str) -> List[str]:
FILL_FUNC_BODYdef generate_matrix(packages: Li... | import json
import subprocess
import sys
from typing import Dict, List, Set
PYTHON_VERSIONS = [
"3.8",
"3.9",
"3.10",
"3.11",
"3.12",
]
SKIP_VERSIONS = {
"prefect-ray": ["3.8", "3.12"],
}
def get_changed_packages(commit_range: str) -> List[str]:
FILL_FUNC_BODYdef generate_matrix(packages: Li... | |
5,571 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/integrations/prefect-dbt/prefect_dbt/cli/configs/bigquery.py | 74,75 | 26,154 | get_configs | BigQueryTargetConfigs | 81,154 | 75,154 | class BigQueryTargetConfigs(BaseTargetConfigs):
"""
Target configs contain credentials and
settings, specific to BigQuery.
To find valid keys, head to the [BigQuery Profile](
https://docs.getdbt.com/reference/warehouse-profiles/bigquery-profile)
page.
Attributes:
credentials: The cr... | class BigQueryTargetConfigs(BaseTargetConfigs):
"""
Target configs contain credentials and
settings, specific to BigQuery.
To find valid keys, head to the [BigQuery Profile](
https://docs.getdbt.com/reference/warehouse-profiles/bigquery-profile)
page.
Attributes:
credentials: The cr... | # since GcpCredentials will always define a project
self_copy = self.copy()
if self_copy.project is not None:
self_copy.credentials.project = None
all_configs_json = self._populate_configs_json(
{}, self_copy.__fields__, model=self_copy
)
# decoup... | """
Returns the dbt configs specific to BigQuery profile.
Returns:
A configs JSON.
"""
# since GcpCredentials will always define a project
self_copy = self.copy()
if self_copy.project is not None:
self_copy.credentials.project = None
... | 216 | 669 | 891 | 1,560 | """Module containing models for BigQuery configs"""
from typing import Any, Dict, Optional
from google.auth.transport.requests import Request
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from pydantic import VERSION as PYDANTIC_VERSION
if PYDANTIC_VERSION.startsw... | """Module containing models for BigQuery configs"""
from typing import Any, Dict, Optional
from google.auth.transport.requests import Request
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from pydantic import VERSION as PYDANTIC_VERSION
if PYDANTIC_VERSION.startsw... |
5,572 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/integrations/prefect-dbt/prefect_dbt/cli/configs/postgres.py | 77,78 | 22,125 | get_configs | PostgresTargetConfigs | 84,125 | 78,125 | class PostgresTargetConfigs(BaseTargetConfigs):
"""
Target configs contain credentials and
settings, specific to Postgres.
To find valid keys, head to the [Postgres Profile](
https://docs.getdbt.com/reference/warehouse-profiles/postgres-profile)
page.
Attributes:
credentials: The cr... | class PostgresTargetConfigs(BaseTargetConfigs):
"""
Target configs contain credentials and
settings, specific to Postgres.
To find valid keys, head to the [Postgres Profile](
https://docs.getdbt.com/reference/warehouse-profiles/postgres-profile)
page.
Attributes:
credentials: The cr... | if isinstance(self.credentials, DatabaseCredentials):
warnings.warn(
"Using DatabaseCredentials is deprecated and will be removed "
"on May 7th, 2023, use SqlAlchemyConnector instead.",
DeprecationWarning,
)
all_configs_json = super... | """
Returns the dbt configs specific to Postgres profile.
Returns:
A configs JSON.
"""
if isinstance(self.credentials, DatabaseCredentials):
warnings.warn(
"Using DatabaseCredentials is deprecated and will be removed "
"on ... | 123 | 734 | 454 | 1,188 | """Module containing models for Postgres configs"""
import warnings
from typing import Any, Dict, Union
from pydantic import VERSION as PYDANTIC_VERSION
if PYDANTIC_VERSION.startswith("2."):
from pydantic.v1 import Field
else:
from pydantic import Field
from typing_extensions import Literal
from prefect_dbt... | """Module containing models for Postgres configs"""
import warnings
from typing import Any, Dict, Union
from pydantic import VERSION as PYDANTIC_VERSION
if PYDANTIC_VERSION.startswith("2."):
from pydantic.v1 import Field
else:
from pydantic import Field
from typing_extensions import Literal
from prefect_dbt... |
5,573 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/integrations/prefect-dbt/prefect_dbt/cli/configs/snowflake.py | 84,85 | 24,132 | get_configs | SnowflakeTargetConfigs | 91,132 | 85,132 | class SnowflakeTargetConfigs(BaseTargetConfigs):
"""
Target configs contain credentials and
settings, specific to Snowflake.
To find valid keys, head to the [Snowflake Profile](
https://docs.getdbt.com/reference/warehouse-profiles/snowflake-profile)
page.
Attributes:
connector: The ... | class SnowflakeTargetConfigs(BaseTargetConfigs):
"""
Target configs contain credentials and
settings, specific to Snowflake.
To find valid keys, head to the [Snowflake Profile](
https://docs.getdbt.com/reference/warehouse-profiles/snowflake-profile)
page.
Attributes:
connector: The ... | all_configs_json = super().get_configs()
# decouple prefect-snowflake from prefect-dbt
# by mapping all the keys dbt snowflake accepts
# https://docs.getdbt.com/reference/warehouse-setups/snowflake-setup
rename_keys = {
# dbt
"type": "type",
"... | """
Returns the dbt configs specific to Snowflake profile.
Returns:
A configs JSON.
"""
all_configs_json = super().get_configs()
# decouple prefect-snowflake from prefect-dbt
# by mapping all the keys dbt snowflake accepts
# https://docs.getd... | 126 | 739 | 510 | 1,249 | """Module containing models for Snowflake configs"""
from typing import Any, Dict, Optional
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from pydantic import VERSION as PYDANTIC_VERSION
if PYDANTIC_VERSION.startswith("2."):
from pydantic.v1 import Field
else:
... | """Module containing models for Snowflake configs"""
from typing import Any, Dict, Optional
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from pydantic import VERSION as PYDANTIC_VERSION
if PYDANTIC_VERSION.startswith("2."):
from pydantic.v1 import Field
else:
... |
5,574 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/integrations/prefect-gcp/prefect_gcp/utilities.py | 6,7 | 1,30 | slugify_name | 23,30 | 7,30 | from typing import Optional
from slugify import slugify
def slugify_name(name: str, max_length: int = 30) -> Optional[str]:
FILL_FUNC_BODY | from typing import Optional
from slugify import slugify
def slugify_name(name: str, max_length: int = 30) -> Optional[str]:
"""
Slugify text for use as a name.
Keeps only alphanumeric characters and dashes, and caps the length
of the slug at 30 chars.
The 30 character length allows room to add ... | slug = slugify(
name,
max_length=max_length,
regex_pattern=r"[^a-zA-Z0-9-]+",
)
return slug if slug else None
| """
Slugify text for use as a name.
Keeps only alphanumeric characters and dashes, and caps the length
of the slug at 30 chars.
The 30 character length allows room to add a uuid for generating a unique
name for the job while keeping the total length of a name below 63 characters,
which is ... | 13 | 194 | 67 | 261 | from typing import Optional
from slugify import slugify
def slugify_name(name: str, max_length: int = 30) -> Optional[str]:
FILL_FUNC_BODY | from typing import Optional
from slugify import slugify
def slugify_name(name: str, max_length: int = 30) -> Optional[str]:
"""
Slugify text for use as a name.
Keeps only alphanumeric characters and dashes, and caps the length
of the slug at 30 chars.
The 30 character length allows room to add ... | |
5,575 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/integrations/prefect-github/prefect_github/utils.py | 25,26 | 1,67 | initialize_return_fields_defaults | 31,49 | 26,49 | """Utilities to assist with using generated collections."""
import json
import re
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Union
SNAKE_CASE_REGEX1 = re.compile("(.)([A-Z][a-z]+)")
SNAKE_CASE_REGEX2 = re.compile("([a-z0-9])([A-Z])")
def camel_to_snake_case(string: s... | """Utilities to assist with using generated collections."""
import json
import re
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Union
SNAKE_CASE_REGEX1 = re.compile("(.)([A-Z][a-z]+)")
SNAKE_CASE_REGEX2 = re.compile("([a-z0-9])([A-Z])")
def camel_to_snake_case(string: s... | with open(config_path, "r") as f:
config = json.load(f)
return_fields_defaults = defaultdict(lambda: [])
for op_type, sub_op_types in config.items():
for sub_op_type in sub_op_types:
if isinstance(sub_op_type, str):
return_fields_defaults[(op_type,)].append(
... | """
Reads config_path to parse out the desired default fields to return.
Args:
config_path: The path to the config file.
"""
with open(config_path, "r") as f:
config = json.load(f)
return_fields_defaults = defaultdict(lambda: [])
for op_type, sub_op_types in config.items():
... | 45 | 475 | 244 | 719 | """Utilities to assist with using generated collections."""
import json
import re
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Union
SNAKE_CASE_REGEX1 = re.compile("(.)([A-Z][a-z]+)")
SNAKE_CASE_REGEX2 = re.compile("([a-z0-9])([A-Z])")
def camel_to_snake_case(string: s... | """Utilities to assist with using generated collections."""
import json
import re
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Union
SNAKE_CASE_REGEX1 = re.compile("(.)([A-Z][a-z]+)")
SNAKE_CASE_REGEX2 = re.compile("([a-z0-9])([A-Z])")
def camel_to_snake_case(string: s... | |
5,576 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/_logging.py | 9,10 | 4,23 | isEnabledFor | SafeLogger | 10,16 | 10,16 | class SafeLogger(logging.Logger):
"""
A logger with extensions for safe emission of logs in our concurrency tooling.
"""
def isEnabledFor(self, level: int):
FILL_FUNC_BODY def getChild(self, suffix: str):
logger = super().getChild(suffix)
logger.__class__ = SafeLogger
return ... | class SafeLogger(logging.Logger):
"""
A logger with extensions for safe emission of logs in our concurrency tooling.
"""
def isEnabledFor(self, level: int):
FILL_FUNC_BODY def getChild(self, suffix: str):
logger = super().getChild(suffix)
logger.__class__ = SafeLogger
return ... | # Override `logger.isEnabledFor` to avoid taking a logging lock which can cause
# deadlocks during complex concurrency handling
from prefect.settings import PREFECT_LOGGING_INTERNAL_LEVEL
return level >= logging._nameToLevel[PREFECT_LOGGING_INTERNAL_LEVEL.value()]
| # Override `logger.isEnabledFor` to avoid taking a logging lock which can cause
# deadlocks during complex concurrency handling
from prefect.settings import PREFECT_LOGGING_INTERNAL_LEVEL
return level >= logging._nameToLevel[PREFECT_LOGGING_INTERNAL_LEVEL.value()]
| 26 | 111 | 90 | 201 | import logging
class SafeLogger(logging.Logger):
"""
A logger with extensions for safe emission of logs in our concurrency tooling.
"""
def isEnabledFor(self, level: int):
FILL_FUNC_BODY def getChild(self, suffix: str):
logger = super().getChild(suffix)
logger.__class__ = SafeLogge... | import logging
class SafeLogger(logging.Logger):
"""
A logger with extensions for safe emission of logs in our concurrency tooling.
"""
def isEnabledFor(self, level: int):
FILL_FUNC_BODY def getChild(self, suffix: str):
logger = super().getChild(suffix)
logger.__class__ = SafeLogge... |
5,578 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/concurrency/api.py | 93,98 | 51,133 | call_soon_in_loop_thread | _base | 103,109 | 98,109 | class _base(abc.ABC):
@abc.abstractstaticmethod
def wait_for_call_in_loop_thread(
__call: Union[Callable[[], T], Call[T]],
timeout: Optional[float] = None,
done_callbacks: Optional[Iterable[Call]] = None,
) -> T:
"""
Schedule a function in the global worker thread and... | class _base(abc.ABC):
@abc.abstractstaticmethod
def wait_for_call_in_loop_thread(
__call: Union[Callable[[], T], Call[T]],
timeout: Optional[float] = None,
done_callbacks: Optional[Iterable[Call]] = None,
) -> T:
"""
Schedule a function in the global worker thread and... | call = _cast_to_call(__call)
runner = get_global_loop()
call.set_timeout(timeout)
runner.submit(call)
return call
| """
Schedule a call for execution in the global event loop thread.
Returns the submitted call.
"""
call = _cast_to_call(__call)
runner = get_global_loop()
call.set_timeout(timeout)
runner.submit(call)
return call
| 10 | 665 | 52 | 717 | """
Primary developer-facing API for concurrency management.
"""
import abc
import asyncio
import concurrent.futures
import contextlib
import threading
from typing import (
Awaitable,
Callable,
ContextManager,
Iterable,
Optional,
TypeVar,
Union,
)
from typing_extensions import ParamSpec
f... | """
Primary developer-facing API for concurrency management.
"""
import abc
import asyncio
import concurrent.futures
import contextlib
import threading
from typing import (
Awaitable,
Callable,
ContextManager,
Iterable,
Optional,
TypeVar,
Union,
)
from typing_extensions import ParamSpec
f... |
5,579 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/concurrency/api.py | 166,172 | 133,198 | call_soon_in_waiting_thread | from_async | 172,182 | 172,182 | class from_async(_base):
@staticmethod
async def wait_for_call_in_loop_thread(
__call: Union[Callable[[], Awaitable[T]], Call[Awaitable[T]]],
timeout: Optional[float] = None,
done_callbacks: Optional[Iterable[Call]] = None,
contexts: Optional[Iterable[ContextManager]] = None,
... | class from_async(_base):
@staticmethod
async def wait_for_call_in_loop_thread(
__call: Union[Callable[[], Awaitable[T]], Call[Awaitable[T]]],
timeout: Optional[float] = None,
done_callbacks: Optional[Iterable[Call]] = None,
contexts: Optional[Iterable[ContextManager]] = None,
... | call = _cast_to_call(__call)
parent_call = get_current_call()
waiter = get_waiter_for_thread(thread, parent_call)
if waiter is None:
raise RuntimeError(f"No waiter found for thread {thread}.")
call.set_timeout(timeout)
waiter.submit(call)
return call
... | call = _cast_to_call(__call)
parent_call = get_current_call()
waiter = get_waiter_for_thread(thread, parent_call)
if waiter is None:
raise RuntimeError(f"No waiter found for thread {thread}.")
call.set_timeout(timeout)
waiter.submit(call)
return call
... | 25 | 652 | 106 | 758 | """
Primary developer-facing API for concurrency management.
"""
import abc
import asyncio
import concurrent.futures
import contextlib
import threading
from typing import (
Awaitable,
Callable,
ContextManager,
Iterable,
Optional,
TypeVar,
Union,
)
from typing_extensions import ParamSpec
f... | """
Primary developer-facing API for concurrency management.
"""
import abc
import asyncio
import concurrent.futures
import contextlib
import threading
from typing import (
Awaitable,
Callable,
ContextManager,
Iterable,
Optional,
TypeVar,
Union,
)
from typing_extensions import ParamSpec
f... |
5,580 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/concurrency/api.py | 220,226 | 198,269 | wait_for_call_in_new_thread | from_sync | 226,234 | 226,234 | class from_sync(_base):
@staticmethod
def wait_for_call_in_loop_thread(
__call: Union[
Callable[[], Awaitable[T]],
Union[Callable[[], Awaitable[T]], Call[Awaitable[T]]],
],
timeout: Optional[float] = None,
done_callbacks: Optional[Iterable[Call]] = None,
... | class from_sync(_base):
@staticmethod
def wait_for_call_in_loop_thread(
__call: Union[
Callable[[], Awaitable[T]],
Union[Callable[[], Awaitable[T]], Call[Awaitable[T]]],
],
timeout: Optional[float] = None,
done_callbacks: Optional[Iterable[Call]] = None,
... | call = _cast_to_call(__call)
waiter = SyncWaiter(call=call)
for callback in done_callbacks or []:
waiter.add_done_callback(callback)
_base.call_soon_in_new_thread(call, timeout=timeout)
waiter.wait()
return call.result()
| call = _cast_to_call(__call)
waiter = SyncWaiter(call=call)
for callback in done_callbacks or []:
waiter.add_done_callback(callback)
_base.call_soon_in_new_thread(call, timeout=timeout)
waiter.wait()
return call.result()
| 18 | 703 | 96 | 799 | """
Primary developer-facing API for concurrency management.
"""
import abc
import asyncio
import concurrent.futures
import contextlib
import threading
from typing import (
Awaitable,
Callable,
ContextManager,
Iterable,
Optional,
TypeVar,
Union,
)
from typing_extensions import ParamSpec
f... | """
Primary developer-facing API for concurrency management.
"""
import abc
import asyncio
import concurrent.futures
import contextlib
import threading
from typing import (
Awaitable,
Callable,
ContextManager,
Iterable,
Optional,
TypeVar,
Union,
)
from typing_extensions import ParamSpec
f... |
5,583 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/concurrency/calls.py | 101,102 | 67,219 | add_cancel_callback | Future | 108,118 | 102,118 | class Future(concurrent.futures.Future):
"""
Extension of `concurrent.futures.Future` with support for cancellation of running
futures.
Used by `Call`.
"""
def __init__(self, name: Optional[str] = None) -> None:
super().__init__()
self._cancel_scope = None
self._deadlin... | class Future(concurrent.futures.Future):
"""
Extension of `concurrent.futures.Future` with support for cancellation of running
futures.
Used by `Call`.
"""
def __init__(self, name: Optional[str] = None) -> None:
super().__init__()
self._cancel_scope = None
self._deadlin... | # If we were to invoke cancel callbacks the same as "done" callbacks, we
# would not propagate chained cancellation in waiters in time to actually
# interrupt calls.
if self._cancel_scope:
# Add callback to current cancel scope if it exists
self._cancel_scope.add_... | """
Add a callback to be enforced on cancellation.
Unlike "done" callbacks, this callback will be invoked _before_ the future is
cancelled. If added after the future is cancelled, nothing will happen.
"""
# If we were to invoke cancel callbacks the same as "done" callbac... | 50 | 1,304 | 116 | 1,420 | """
Implementation of the `Call` data structure for transport of deferred function calls
and low-level management of call execution.
"""
import abc
import asyncio
import concurrent.futures
import contextlib
import contextvars
import dataclasses
import inspect
import threading
import weakref
from concurrent.futures._ba... | """
Implementation of the `Call` data structure for transport of deferred function calls
and low-level management of call execution.
"""
import abc
import asyncio
import concurrent.futures
import contextlib
import contextvars
import dataclasses
import inspect
import threading
import weakref
from concurrent.futures._ba... |
5,584 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/concurrency/event_loop.py | 48,54 | 1,98 | call_soon_in_loop | 61,84 | 54,84 | """
Thread-safe utilities for working with asynchronous event loops.
"""
import asyncio
import concurrent.futures
import functools
from typing import Awaitable, Callable, Coroutine, Optional, TypeVar
from typing_extensions import ParamSpec
P = ParamSpec("P")
T = TypeVar("T")
def get_running_loop() -> Optional[asyn... | """
Thread-safe utilities for working with asynchronous event loops.
"""
import asyncio
import concurrent.futures
import functools
from typing import Awaitable, Callable, Coroutine, Optional, TypeVar
from typing_extensions import ParamSpec
P = ParamSpec("P")
T = TypeVar("T")
def get_running_loop() -> Optional[asyn... | future = concurrent.futures.Future()
@functools.wraps(__fn)
def wrapper() -> None:
try:
result = __fn(*args, **kwargs)
except BaseException as exc:
future.set_exception(exc)
if not isinstance(exc, Exception):
raise
else:
... | """
Run a synchronous call in an event loop's thread from another thread.
This function is non-blocking and safe to call from an asynchronous context.
Returns a future that can be used to retrieve the result of the call.
"""
future = concurrent.futures.Future()
@functools.wraps(__fn)
... | 61 | 604 | 212 | 816 | """
Thread-safe utilities for working with asynchronous event loops.
"""
import asyncio
import concurrent.futures
import functools
from typing import Awaitable, Callable, Coroutine, Optional, TypeVar
from typing_extensions import ParamSpec
P = ParamSpec("P")
T = TypeVar("T")
def get_running_loop() -> Optional[asyn... | """
Thread-safe utilities for working with asynchronous event loops.
"""
import asyncio
import concurrent.futures
import functools
from typing import Awaitable, Callable, Coroutine, Optional, TypeVar
from typing_extensions import ParamSpec
P = ParamSpec("P")
T = TypeVar("T")
def get_running_loop() -> Optional[asyn... | |
5,585 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/concurrency/inspection.py | 66,67 | 1,102 | repr_frame | 68,75 | 67,75 | """
Utilities for inspection of stack frames and threads.
"""
import dis
import linecache
import sys
import threading
from types import FrameType
from typing import List
"""
The following functions are derived from dask/distributed which is licensed under the
BSD 3-Clause License.
Copyright (c) 2015, Anaconda, Inc.... | """
Utilities for inspection of stack frames and threads.
"""
import dis
import linecache
import sys
import threading
from types import FrameType
from typing import List
"""
The following functions are derived from dask/distributed which is licensed under the
BSD 3-Clause License.
Copyright (c) 2015, Anaconda, Inc.... | co = frame.f_code
f_lineno = _f_lineno(frame)
text = f' File "{co.co_filename}", line {f_lineno}, in {co.co_name}'
line = linecache.getline(co.co_filename, f_lineno, frame.f_globals).lstrip()
return text + "\n\t" + line
| """Render a frame as a line for inclusion into a text traceback"""
co = frame.f_code
f_lineno = _f_lineno(frame)
text = f' File "{co.co_filename}", line {f_lineno}, in {co.co_name}'
line = linecache.getline(co.co_filename, f_lineno, frame.f_globals).lstrip()
return text + "\n\t" + line
| 26 | 1,001 | 108 | 1,109 | """
Utilities for inspection of stack frames and threads.
"""
import dis
import linecache
import sys
import threading
from types import FrameType
from typing import List
"""
The following functions are derived from dask/distributed which is licensed under the
BSD 3-Clause License.
Copyright (c) 2015, Anaconda, Inc.... | """
Utilities for inspection of stack frames and threads.
"""
import dis
import linecache
import sys
import threading
from types import FrameType
from typing import List
"""
The following functions are derived from dask/distributed which is licensed under the
BSD 3-Clause License.
Copyright (c) 2015, Anaconda, Inc.... | |
5,586 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/concurrency/primitives.py | 57,58 | 16,79 | wait | Event | 64,79 | 58,79 | class Event:
"""
A thread-safe async event.
Unlike `asyncio.Event` this implementation does not bind to a loop on creation. This
matches the behavior of `asyncio.Event` in Python 3.10+, but differs from earlier
versions.
This event also does not support a `clear()` operation. This matches the ... | class Event:
"""
A thread-safe async event.
Unlike `asyncio.Event` this implementation does not bind to a loop on creation. This
matches the behavior of `asyncio.Event` in Python 3.10+, but differs from earlier
versions.
This event also does not support a `clear()` operation. This matches the ... | # Taking a sync lock in an async context is generally not recommended, but this
# lock should only ever be held very briefly and we need to prevent race
# conditions during between `set()` and `wait()`
with self._lock:
if self._value:
return True
... | """
Block until the internal flag is true.
If the internal flag is true on entry, return True immediately.
Otherwise, block until another `set()` is called, then return True.
"""
# Taking a sync lock in an async context is generally not recommended, but this
# lo... | 54 | 471 | 142 | 613 | """
Thread-safe async synchronization primitives.
"""
import asyncio
import collections
import threading
from typing import TypeVar
from typing_extensions import Literal
from prefect._internal.concurrency.event_loop import call_soon_in_loop
T = TypeVar("T")
class Event:
"""
A thread-safe async event.
... | """
Thread-safe async synchronization primitives.
"""
import asyncio
import collections
import threading
from typing import TypeVar
from typing_extensions import Literal
from prefect._internal.concurrency.event_loop import call_soon_in_loop
T = TypeVar("T")
class Event:
"""
A thread-safe async event.
... |
5,588 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/concurrency/services.py | 342,343 | 273,353 | _handle | BatchedQueueService | 343,345 | 343,345 | class BatchedQueueService(QueueService[T]):
"""
A queue service that handles a batch of items instead of a single item at a time.
Items will be processed when the batch reaches the configured `_max_batch_size`
or after an interval of `_min_interval` seconds (if set).
"""
_max_batch_size: int
... | class BatchedQueueService(QueueService[T]):
"""
A queue service that handles a batch of items instead of a single item at a time.
Items will be processed when the batch reaches the configured `_max_batch_size`
or after an interval of `_min_interval` seconds (if set).
"""
_max_batch_size: int
... | assert False, "`_handle` should never be called for batched queue services"
| assert False, "`_handle` should never be called for batched queue services"
| 11 | 607 | 23 | 630 | import abc
import asyncio
import atexit
import concurrent.futures
import contextlib
import logging
import queue
import sys
import threading
from typing import Awaitable, Dict, Generic, List, Optional, Type, TypeVar, Union
from typing_extensions import Self
from prefect._internal.concurrency import logger
from prefect... | import abc
import asyncio
import atexit
import concurrent.futures
import contextlib
import logging
import queue
import sys
import threading
from typing import Awaitable, Dict, Generic, List, Optional, Type, TypeVar, Union
from typing_extensions import Self
from prefect._internal.concurrency import logger
from prefect... |
5,591 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/concurrency/threads.py | 204,205 | 117,236 | _run_until_shutdown | EventLoopThread | 205,220 | 205,220 | class EventLoopThread(Portal):
"""
A portal to a worker running on a thread with an event loop.
"""
def __init__(
self,
name: str = "EventLoopThread",
daemon: bool = False,
run_once: bool = False,
):
self.thread = threading.Thread(
name=name, daem... | class EventLoopThread(Portal):
"""
A portal to a worker running on a thread with an event loop.
"""
def __init__(
self,
name: str = "EventLoopThread",
daemon: bool = False,
run_once: bool = False,
):
self.thread = threading.Thread(
name=name, daem... | try:
self._loop = asyncio.get_running_loop()
self._ready_future.set_result(True)
except Exception as exc:
self._ready_future.set_exception(exc)
return
await self._shutdown_event.wait()
for call in self._on_shutdown:
await self... | try:
self._loop = asyncio.get_running_loop()
self._ready_future.set_result(True)
except Exception as exc:
self._ready_future.set_exception(exc)
return
await self._shutdown_event.wait()
for call in self._on_shutdown:
await self... | 35 | 834 | 145 | 979 | """
Utilities for managing worker threads.
"""
import asyncio
import atexit
import concurrent.futures
import itertools
import queue
import threading
from typing import List, Optional
from prefect._internal.concurrency import logger
from prefect._internal.concurrency.calls import Call, Portal
from prefect._internal.con... | """
Utilities for managing worker threads.
"""
import asyncio
import atexit
import concurrent.futures
import itertools
import queue
import threading
from typing import List, Optional
from prefect._internal.concurrency import logger
from prefect._internal.concurrency.calls import Call, Portal
from prefect._internal.con... |
5,592 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/concurrency/threads.py | 53,54 | 19,117 | submit | WorkerThread | 54,75 | 54,75 | class WorkerThread(Portal):
"""
A portal to a worker running on a thread.
"""
# Used for unique thread names by default
_counter = itertools.count().__next__
def __init__(
self, name: Optional[str] = None, daemon: bool = False, run_once: bool = False
):
name = name or f"Wor... | class WorkerThread(Portal):
"""
A portal to a worker running on a thread.
"""
# Used for unique thread names by default
_counter = itertools.count().__next__
def __init__(
self, name: Optional[str] = None, daemon: bool = False, run_once: bool = False
):
name = name or f"Wor... | if self._submitted_count > 0 and self._run_once:
raise RuntimeError(
"Worker configured to only run once. A call has already been submitted."
)
# Start on first submission if not started
if not self._started:
self.start()
# Track the ... | if self._submitted_count > 0 and self._run_once:
raise RuntimeError(
"Worker configured to only run once. A call has already been submitted."
)
# Start on first submission if not started
if not self._started:
self.start()
# Track the ... | 59 | 591 | 181 | 772 | """
Utilities for managing worker threads.
"""
import asyncio
import atexit
import concurrent.futures
import itertools
import queue
import threading
from typing import List, Optional
from prefect._internal.concurrency import logger
from prefect._internal.concurrency.calls import Call, Portal
from prefect._internal.con... | """
Utilities for managing worker threads.
"""
import asyncio
import atexit
import concurrent.futures
import itertools
import queue
import threading
from typing import List, Optional
from prefect._internal.concurrency import logger
from prefect._internal.concurrency.calls import Call, Portal
from prefect._internal.con... |
5,593 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/annotations/pendulum.py | 32,35 | 15,68 | validate_from_str | _PendulumDateTimeAnnotation | 35,37 | 35,37 | class _PendulumDateTimeAnnotation:
_pendulum_type: t.Type[
t.Union[pendulum.DateTime, pendulum.Date, pendulum.Time]
] = pendulum.DateTime
_pendulum_types_to_schemas = {
pendulum.DateTime: core_schema.datetime_schema(),
pendulum.Date: core_schema.date_schema(),
pendulum.Durat... | class _PendulumDateTimeAnnotation:
_pendulum_type: t.Type[
t.Union[pendulum.DateTime, pendulum.Date, pendulum.Time]
] = pendulum.DateTime
_pendulum_types_to_schemas = {
pendulum.DateTime: core_schema.datetime_schema(),
pendulum.Date: core_schema.date_schema(),
pendulum.Durat... | return pendulum.parse(value)
| return pendulum.parse(value)
| 2 | 547 | 14 | 561 | """
This file contains compat code to handle pendulum.DateTime objects during jsonschema
generation and validation.
"""
import typing as t
import pendulum
from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler
from pydantic.json_schema import JsonSchemaValue
from pydantic_core import core_schema
from typin... | """
This file contains compat code to handle pendulum.DateTime objects during jsonschema
generation and validation.
"""
import typing as t
import pendulum
from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler
from pydantic.json_schema import JsonSchemaValue
from pydantic_core import core_schema
from typin... |
5,594 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/schemas.py | 11,14 | 5,15 | is_instance_schema | GenerateEmptySchemaForUserClasses | 14,15 | 14,15 | class GenerateEmptySchemaForUserClasses(GenerateJsonSchema):
"""
This custom schema overrides the default pydantic is-instance schema
behavior to simply return an empty dict for user-defined classes
"""
def is_instance_schema(
self, schema: core_schema.IsInstanceSchema
) -> JsonSchemaVa... | class GenerateEmptySchemaForUserClasses(GenerateJsonSchema):
"""
This custom schema overrides the default pydantic is-instance schema
behavior to simply return an empty dict for user-defined classes
"""
def is_instance_schema(
self, schema: core_schema.IsInstanceSchema
) -> JsonSchemaVa... | return {}
| return {}
| 2 | 93 | 5 | 98 | from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
from pydantic_core import core_schema
class GenerateEmptySchemaForUserClasses(GenerateJsonSchema):
"""
This custom schema overrides the default pydantic is-instance schema
behavior to simply return an empty dict for user-defined classes
... | from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
from pydantic_core import core_schema
class GenerateEmptySchemaForUserClasses(GenerateJsonSchema):
"""
This custom schema overrides the default pydantic is-instance schema
behavior to simply return an empty dict for user-defined classes
... |
5,595 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_construct.py | 11,16 | 1,57 | model_construct | 28,34 | 16,34 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_construct(
model: typing.Type[T],
_fields_set: typing.Optional[typing.Set[str]] = No... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_construct(
model: typing.Type[T],
_fields_set: typing.Optional[typing.Set[str]] = No... | if USE_V2_MODELS:
return model.model_construct(_fields_set=_fields_set, **values)
else:
return getattr(model, "construct")(**values)
| """Creates a new instance of the `model` class with validated data.
Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Args:
_fields_set: The set of field names accepted fo... | 9 | 501 | 59 | 560 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_construct(
model: typing.Type[T],
_fields_set: typing.Optional[typing.Set[str]] = No... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_construct(
model: typing.Type[T],
_fields_set: typing.Optional[typing.Set[str]] = No... | |
5,596 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_construct.py | 35,41 | 34,56 | model_construct | ModelConstructMixin | 53,56 | 41,56 | class ModelConstructMixin(BaseModel):
@classmethod
def model_construct(
cls: typing.Type["Self"],
_fields_set: typing.Optional[typing.Set[str]] = None,
**values: typing.Any,
) -> "Self":
FILL_FUNC_BODY | class ModelConstructMixin(BaseModel):
@classmethod
def model_construct(
cls: typing.Type["Self"],
_fields_set: typing.Optional[typing.Set[str]] = None,
**values: typing.Any,
) -> "Self":
"""Creates a new instance of the `model` class with validated data.
Creates a ne... | return model_construct(cls, _fields_set=_fields_set, **values)
| """Creates a new instance of the `model` class with validated data.
Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
Default values are respected, but no other validation is performed.
Args:
_fields_set: The set of fie... | 4 | 211 | 27 | 238 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_construct(
model: typing.Type[T],
_fields_set: typing.Optional[typing.Set[str]] = No... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_construct(
model: typing.Type[T],
_fields_set: typing.Optional[typing.Set[str]] = No... |
5,597 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_copy.py | 11,17 | 1,56 | model_copy | 28,34 | 17,34 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_copy( # type: ignore[no-redef]
model_instance: T,
*,
update: typing.Optional[ty... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_copy( # type: ignore[no-redef]
model_instance: T,
*,
update: typing.Optional[ty... | if USE_V2_MODELS:
return model_instance.model_copy(update=update, deep=deep)
else:
return getattr(model_instance, "copy")(update=update, deep=deep)
| """
Returns a copy of the model.
Args:
update: Values to change/add in the new model. Note: the data is not validated
before creating the new model. You should trust this data.
deep: Set to `True` to make a deep copy of the model.
Returns:
New model instance.
""... | 10 | 414 | 64 | 478 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_copy( # type: ignore[no-redef]
model_instance: T,
*,
update: typing.Optional[ty... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_copy( # type: ignore[no-redef]
model_instance: T,
*,
update: typing.Optional[ty... | |
5,598 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_copy.py | 35,41 | 34,55 | model_copy | ModelCopyMixin | 52,55 | 41,55 | class ModelCopyMixin(BaseModel):
def model_copy(
self: "Self",
*,
update: typing.Optional[typing.Dict[str, typing.Any]] = None,
deep: bool = False,
) -> "Self":
FILL_FUNC_BODY | class ModelCopyMixin(BaseModel):
def model_copy(
self: "Self",
*,
update: typing.Optional[typing.Dict[str, typing.Any]] = None,
deep: bool = False,
) -> "Self":
"""
Returns a copy of the model.
Args:
update: Values to change/add in the new mod... | return model_copy(self, update=update, deep=deep)
| """
Returns a copy of the model.
Args:
update: Values to change/add in the new model. Note: the data is not validated
before creating the new model. You should trust this data.
deep: Set to `True` to make a deep copy of the model.
Returns:
... | 4 | 164 | 22 | 186 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_copy( # type: ignore[no-redef]
model_instance: T,
*,
update: typing.Optional[ty... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_copy( # type: ignore[no-redef]
model_instance: T,
*,
update: typing.Optional[ty... |
5,599 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_dump.py | 16,29 | 1,137 | model_dump | 50,87 | 29,87 | import typing
import warnings as python_warnings
from pydantic_core import from_json
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import I... | import typing
import warnings as python_warnings
from pydantic_core import from_json
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import I... | if USE_V2_MODELS and hasattr(model_instance, "model_dump"):
return model_instance.model_dump(
mode=mode,
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
ex... | """
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
Args:
mode: The mode in which `to_python` should run.
If mode is 'json', the output will only contain JSON serializable types.
If mode is 'python', the output may... | 46 | 1,128 | 352 | 1,480 | import typing
import warnings as python_warnings
from pydantic_core import from_json
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import I... | import typing
import warnings as python_warnings
from pydantic_core import from_json
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import I... | |
5,600 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_dump.py | 88,101 | 87,136 | model_dump | ModelDumpMixin | 122,136 | 101,136 | class ModelDumpMixin(BaseModel):
def model_dump(
self: "Self",
*,
mode: typing.Union[typing.Literal["json", "python"], str] = "python",
include: "IncEx" = None,
exclude: "IncEx" = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defau... | class ModelDumpMixin(BaseModel):
def model_dump(
self: "Self",
*,
mode: typing.Union[typing.Literal["json", "python"], str] = "python",
include: "IncEx" = None,
exclude: "IncEx" = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defau... | return model_dump(
self,
mode=mode,
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
round_trip=round_trip,
... | """
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
Args:
mode: The mode in which `to_python` should run.
If mode is 'json', the output will only contain JSON serializable types.
If mode is ... | 13 | 454 | 113 | 567 | import typing
import warnings as python_warnings
from pydantic_core import from_json
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import I... | import typing
import warnings as python_warnings
from pydantic_core import from_json
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import I... |
5,601 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_dump_json.py | 14,27 | 1,113 | model_dump_json | 44,67 | 27,67 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import IncEx
T = typing.TypeVar("T", bound="BaseModel")
def model_dump_json(... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import IncEx
T = typing.TypeVar("T", bound="BaseModel")
def model_dump_json(... | if USE_V2_MODELS:
return model_instance.model_dump_json(
indent=indent,
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
... | """
Generate a JSON representation of the model, optionally specifying which fields to include or exclude.
Args:
indent: If provided, the number of spaces to indent the JSON output.
include: A list of fields to include in the output.
exclude: A list of fields to exclude from the out... | 25 | 923 | 215 | 1,138 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import IncEx
T = typing.TypeVar("T", bound="BaseModel")
def model_dump_json(... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import IncEx
T = typing.TypeVar("T", bound="BaseModel")
def model_dump_json(... | |
5,602 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_dump_json.py | 68,81 | 67,112 | model_dump_json | ModelDumpJsonMixin | 98,112 | 81,112 | class ModelDumpJsonMixin(BaseModel):
def model_dump_json(
self: "Self",
*,
indent: typing.Optional[int] = None,
include: "IncEx" = None,
exclude: "IncEx" = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
... | class ModelDumpJsonMixin(BaseModel):
def model_dump_json(
self: "Self",
*,
indent: typing.Optional[int] = None,
include: "IncEx" = None,
exclude: "IncEx" = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
... | return model_dump_json(
self,
indent=indent,
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
round_trip=roun... | """
Generate a JSON representation of the model, optionally specifying which fields to include or exclude.
Args:
indent: If provided, the number of spaces to indent the JSON output.
include: A list of fields to include in the output.
exclude: A list of fields... | 13 | 364 | 116 | 480 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import IncEx
T = typing.TypeVar("T", bound="BaseModel")
def model_dump_json(... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import IncEx
T = typing.TypeVar("T", bound="BaseModel")
def model_dump_json(... |
5,603 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_fields.py | 24,26 | 17,40 | frozen | _FieldInfo | 26,30 | 26,30 | class _FieldInfo(BaseModel):
model_field: typing.Any
@property
def annotation(self) -> typing.Any:
return getattr(self.model_field, "outer_type_")
@property
def frozen(self) -> bool:
FILL_FUNC_BODY @property
def... | class _FieldInfo(BaseModel):
model_field: typing.Any
@property
def annotation(self) -> typing.Any:
return getattr(self.model_field, "outer_type_")
@property
def frozen(self) -> bool:
FILL_FUNC_BODY @property
def... | return not operator.attrgetter("field_info.allow_mutation")(
self.model_field
)
| return not operator.attrgetter("field_info.allow_mutation")(
self.model_field
)
| 5 | 192 | 35 | 227 | import operator
import typing
from prefect._internal.pydantic._base_model import BaseModel, FieldInfo
from prefect._internal.pydantic._flags import HAS_PYDANTIC_V2, USE_PYDANTIC_V2
T = typing.TypeVar("T")
if HAS_PYDANTIC_V2 and USE_PYDANTIC_V2:
class ModelFieldMixin(BaseModel): # type: ignore [no-redef]
... | import operator
import typing
from prefect._internal.pydantic._base_model import BaseModel, FieldInfo
from prefect._internal.pydantic._flags import HAS_PYDANTIC_V2, USE_PYDANTIC_V2
T = typing.TypeVar("T")
if HAS_PYDANTIC_V2 and USE_PYDANTIC_V2:
class ModelFieldMixin(BaseModel): # type: ignore [no-redef]
... |
5,604 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_fields_set.py | 7,8 | 1,30 | model_fields_set | 11,17 | 8,17 | import typing
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
def model_fields_set(model_instance: "BaseModel") -> typing.Set[str]:
FILL_FUNC_BODYclass ModelFieldsSetMixin(BaseModel):
@property
def model_fields_set(self) -> typing.Set[s... | import typing
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
def model_fields_set(model_instance: "BaseModel") -> typing.Set[str]:
"""
Returns a set of the model's fields.
"""
FILL_FUNC_BODYclass ModelFieldsSetMixin(BaseModel):
... | if USE_V2_MODELS:
return getattr(model_instance, "__pydantic_fields_set__")
else:
return getattr(model_instance, "__fields_set__")
| """
Returns a set of the model's fields.
"""
if USE_V2_MODELS:
return getattr(model_instance, "__pydantic_fields_set__")
else:
return getattr(model_instance, "__fields_set__")
| 9 | 214 | 61 | 275 | import typing
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
def model_fields_set(model_instance: "BaseModel") -> typing.Set[str]:
FILL_FUNC_BODYclass ModelFieldsSetMixin(BaseModel):
@property
def model_fields_set(self) -> typing.Set[s... | import typing
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
def model_fields_set(model_instance: "BaseModel") -> typing.Set[str]:
"""
Returns a set of the model's fields.
"""
FILL_FUNC_BODYclass ModelFieldsSetMixin(BaseModel):
... | |
5,605 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_fields_set.py | 18,20 | 17,29 | model_fields_set | ModelFieldsSetMixin | 26,29 | 20,29 | class ModelFieldsSetMixin(BaseModel):
@property
def model_fields_set(self) -> typing.Set[str]:
FILL_FUNC_BODY | class ModelFieldsSetMixin(BaseModel):
@property
def model_fields_set(self) -> typing.Set[str]:
"""Returns the set of fields that have been explicitly set on this model instance.
Returns:
A set of strings representing the fields that have been set,
i.e. that were not ... | return model_fields_set(self)
| """Returns the set of fields that have been explicitly set on this model instance.
Returns:
A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
"""
return model_fields_set(self)
| 2 | 97 | 16 | 113 | import typing
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
def model_fields_set(model_instance: "BaseModel") -> typing.Set[str]:
"""
Returns a set of the model's fields.
"""
if USE_V2_MODELS:
return getattr(model_inst... | import typing
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
def model_fields_set(model_instance: "BaseModel") -> typing.Set[str]:
"""
Returns a set of the model's fields.
"""
if USE_V2_MODELS:
return getattr(model_inst... |
5,606 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_json_schema.py | 16,23 | 1,83 | model_json_schema | 36,52 | 23,52 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import JsonSchemaMode
from prefect._internal.pydantic._types import DEFAULT_RE... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import JsonSchemaMode
from prefect._internal.pydantic._types import DEFAULT_RE... | if USE_V2_MODELS:
return model.model_json_schema(
by_alias=by_alias,
ref_template=ref_template,
mode=mode,
# We've changed the type of schema_generator of 'schema_generator' to 'typing.Any',
# which is will throw an error if its None. So, we've to ... | """
Generates a JSON schema for a model class.
Args:
by_alias: Whether to use attribute aliases or not.
ref_template: The reference template.
schema_generator: To override the logic used to generate the JSON schema, as a subclass of
`GenerateJsonSchema` with your desired... | 52 | 604 | 179 | 783 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import JsonSchemaMode
from prefect._internal.pydantic._types import DEFAULT_RE... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import JsonSchemaMode
from prefect._internal.pydantic._types import DEFAULT_RE... | |
5,607 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_json_schema.py | 53,61 | 52,82 | model_json_schema | ModelJsonSchemaMixin | 74,82 | 61,82 | class ModelJsonSchemaMixin(BaseModel):
@classmethod
def model_json_schema(
cls: typing.Type["Self"],
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: typing.Any = None,
mode: "JsonSchemaMode" = "validation",
) -> typing.Dict[str, typi... | class ModelJsonSchemaMixin(BaseModel):
@classmethod
def model_json_schema(
cls: typing.Type["Self"],
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: typing.Any = None,
mode: "JsonSchemaMode" = "validation",
) -> typing.Dict[str, typi... | return model_json_schema(
cls,
by_alias=by_alias,
ref_template=ref_template,
mode=mode,
)
| """
Generates a JSON schema for a model class.
Args:
by_alias: Whether to use attribute aliases or not.
ref_template: The reference template.
schema_generator: To override the logic used to generate the JSON schema, as a subclass of
`GenerateJ... | 7 | 226 | 53 | 279 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import JsonSchemaMode
from prefect._internal.pydantic._types import DEFAULT_RE... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
if typing.TYPE_CHECKING:
from prefect._internal.pydantic._types import JsonSchemaMode
from prefect._internal.pydantic._types import DEFAULT_RE... |
5,608 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_rebuild.py | 11,19 | 1,81 | model_rebuild | 34,46 | 19,46 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_rebuild(
model_instance: typing.Type[T],
*,
force: bool = False,
raise_error... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_rebuild(
model_instance: typing.Type[T],
*,
force: bool = False,
raise_error... |
if USE_V2_MODELS:
return model_instance.model_rebuild(
force=force,
raise_errors=raise_errors,
_parent_namespace_depth=_parent_namespace_depth,
_types_namespace=_types_namespace,
)
else:
return getattr(model_instance, "update_forward_refs"... | """Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
the initial attempt to build the schema, and automatic rebuilding fails.
Args:
force: Whether to force the rebuilding of the model sche... | 13 | 743 | 108 | 851 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_rebuild(
model_instance: typing.Type[T],
*,
force: bool = False,
raise_error... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_rebuild(
model_instance: typing.Type[T],
*,
force: bool = False,
raise_error... | |
5,609 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_rebuild.py | 47,56 | 46,80 | model_rebuild | ModelRebuildMixin | 71,80 | 56,80 | class ModelRebuildMixin(BaseModel):
@classmethod
def model_rebuild(
cls: typing.Type["Self"],
*,
force: bool = False,
raise_errors: bool = True,
_parent_namespace_depth: int = 2,
_types_namespace: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> typi... | class ModelRebuildMixin(BaseModel):
@classmethod
def model_rebuild(
cls: typing.Type["Self"],
*,
force: bool = False,
raise_errors: bool = True,
_parent_namespace_depth: int = 2,
_types_namespace: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> typi... | return model_rebuild(
cls,
force=force,
raise_errors=raise_errors,
_parent_namespace_depth=_parent_namespace_depth,
_types_namespace=_types_namespace,
)
| """Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
the initial attempt to build the schema, and automatic rebuilding fails.
Args:
force: Whether to force the rebuildi... | 8 | 311 | 71 | 382 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_rebuild(
model_instance: typing.Type[T],
*,
force: bool = False,
raise_error... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_rebuild(
model_instance: typing.Type[T],
*,
force: bool = False,
raise_error... |
5,610 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_validate.py | 11,19 | 1,76 | model_validate | 34,45 | 19,45 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate(
model_instance: typing.Type[T],
obj: typing.Any,
*,
strict: typing... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate(
model_instance: typing.Type[T],
obj: typing.Any,
*,
strict: typing... | if USE_V2_MODELS:
return model_instance.model_validate(
obj,
strict=strict,
from_attributes=from_attributes,
context=context,
)
else:
return getattr(model_instance, "parse_obj")(obj)
| """
Validate a pydantic model instance.
Args:
obj: The object to validate.
strict: Whether to enforce types strictly.
from_attributes: Whether to extract data from object attributes.
context: Additional context to pass to the validator.
Raises:
ValidationError: ... | 13 | 520 | 86 | 606 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate(
model_instance: typing.Type[T],
obj: typing.Any,
*,
strict: typing... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate(
model_instance: typing.Type[T],
obj: typing.Any,
*,
strict: typing... | |
5,611 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_validate.py | 46,55 | 45,75 | model_validate | ModelValidateMixin | 70,75 | 55,75 | class ModelValidateMixin(BaseModel):
@classmethod
def model_validate(
cls: typing.Type["Self"],
obj: typing.Any,
*,
strict: typing.Optional[bool] = False,
from_attributes: typing.Optional[bool] = False,
context: typing.Optional[typing.Dict[str, typing.Any]] = None... | class ModelValidateMixin(BaseModel):
@classmethod
def model_validate(
cls: typing.Type["Self"],
obj: typing.Any,
*,
strict: typing.Optional[bool] = False,
from_attributes: typing.Optional[bool] = False,
context: typing.Optional[typing.Dict[str, typing.Any]] = None... | return model_validate(
cls, obj, strict=strict, from_attributes=from_attributes, context=context
)
| """
Validate a pydantic model instance.
Args:
obj: The object to validate.
strict: Whether to enforce types strictly.
from_attributes: Whether to extract data from object attributes.
context: Additional context to pass to the validator.
R... | 8 | 218 | 39 | 257 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate(
model_instance: typing.Type[T],
obj: typing.Any,
*,
strict: typing... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate(
model_instance: typing.Type[T],
obj: typing.Any,
*,
strict: typing... |
5,612 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_validate_json.py | 11,18 | 1,69 | model_validate_json | 32,42 | 18,42 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate_json(
model: typing.Type[T],
json_data: typing.Union[str, bytes, bytearray]... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate_json(
model: typing.Type[T],
json_data: typing.Union[str, bytes, bytearray]... | if USE_V2_MODELS:
return model.model_validate_json(
json_data,
strict=strict,
context=context,
)
else:
return getattr(model, "parse_raw")(json_data)
| """
Validate the given JSON data against the Pydantic model.
Args:
json_data: The JSON data to validate.
strict: Whether to enforce types strictly.
context: Extra variables to pass to the validator.
Returns:
The validated Pydantic model.
Raises:
ValueError:... | 12 | 508 | 77 | 585 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate_json(
model: typing.Type[T],
json_data: typing.Union[str, bytes, bytearray]... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate_json(
model: typing.Type[T],
json_data: typing.Union[str, bytes, bytearray]... | |
5,613 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_validate_json.py | 43,51 | 42,68 | model_validate_json | ModelValidateJsonMixin | 65,68 | 51,68 | class ModelValidateJsonMixin(BaseModel):
@classmethod
def model_validate_json(
cls: typing.Type["Self"],
json_data: typing.Union[str, bytes, bytearray],
*,
strict: typing.Optional[bool] = False,
context: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> "Self... | class ModelValidateJsonMixin(BaseModel):
@classmethod
def model_validate_json(
cls: typing.Type["Self"],
json_data: typing.Union[str, bytes, bytearray],
*,
strict: typing.Optional[bool] = False,
context: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> "Self... | return model_validate_json(cls, json_data, strict=strict, context=context)
| """
Validate the given JSON data against the Pydantic model.
Args:
json_data: The JSON data to validate.
strict: Whether to enforce types strictly.
context: Extra variables to pass to the validator.
Returns:
The validated Pydantic model.
... | 5 | 213 | 28 | 241 | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate_json(
model: typing.Type[T],
json_data: typing.Union[str, bytes, bytearray]... | import typing
from typing_extensions import Self
from prefect._internal.pydantic._base_model import BaseModel
from prefect._internal.pydantic._flags import USE_V2_MODELS
T = typing.TypeVar("T", bound="BaseModel")
def model_validate_json(
model: typing.Type[T],
json_data: typing.Union[str, bytes, bytearray]... |
5,614 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/utilities/model_validator.py | 12,17 | 1,88 | model_validator | 57,88 | 17,88 | import functools
from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, TypeVar
from prefect._internal.pydantic._flags import HAS_PYDANTIC_V2, USE_V2_MODELS
T = TypeVar("T", bound=Callable[..., Any])
if TYPE_CHECKING:
from prefect._internal.pydantic._compat import BaseModel
def model_validator(
... | import functools
from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, TypeVar
from prefect._internal.pydantic._flags import HAS_PYDANTIC_V2, USE_V2_MODELS
T = TypeVar("T", bound=Callable[..., Any])
if TYPE_CHECKING:
from prefect._internal.pydantic._compat import BaseModel
def model_validator(
... |
def decorator(validate_func: T) -> T:
if USE_V2_MODELS:
from pydantic import model_validator
return model_validator(
mode=mode,
)(validate_func) # type: ignore
elif HAS_PYDANTIC_V2:
from pydantic.v1 import root_validator
el... | """Usage docs: https://docs.pydantic.dev/2.6/concepts/validators/#model-validators
A decorator designed for Pydantic model methods to facilitate additional validations.
It can be applied to instance methods, class methods, or static methods of a class,
wrapping around the designated function to inject ... | 63 | 866 | 256 | 1,122 | import functools
from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, TypeVar
from prefect._internal.pydantic._flags import HAS_PYDANTIC_V2, USE_V2_MODELS
T = TypeVar("T", bound=Callable[..., Any])
if TYPE_CHECKING:
from prefect._internal.pydantic._compat import BaseModel
def model_validator(
... | import functools
from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, TypeVar
from prefect._internal.pydantic._flags import HAS_PYDANTIC_V2, USE_V2_MODELS
T = TypeVar("T", bound=Callable[..., Any])
if TYPE_CHECKING:
from prefect._internal.pydantic._compat import BaseModel
def model_validator(
... | |
5,615 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/v1_schema.py | 37,38 | 1,49 | has_v1_type_as_param | 38,49 | 38,49 | import inspect
import typing
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 import BaseModel as V1BaseModel
else:
from pydantic import BaseModel as V1BaseModel
def is_v1_model(v) -> bool:
if isinstance(v, V1BaseModel):
return True
try:
if ... | import inspect
import typing
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 import BaseModel as V1BaseModel
else:
from pydantic import BaseModel as V1BaseModel
def is_v1_model(v) -> bool:
if isinstance(v, V1BaseModel):
return True
try:
if ... | parameters = signature.parameters.values()
for p in parameters:
# check if this parameter is a v1 model
if is_v1_type(p.annotation):
return True
# check if this parameter is a collection of types
for v in typing.get_args(p.annotation):
if is_v1_type(v):
... | parameters = signature.parameters.values()
for p in parameters:
# check if this parameter is a v1 model
if is_v1_type(p.annotation):
return True
# check if this parameter is a collection of types
for v in typing.get_args(p.annotation):
if is_v1_type(v):
... | 40 | 278 | 106 | 384 | import inspect
import typing
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 import BaseModel as V1BaseModel
else:
from pydantic import BaseModel as V1BaseModel
def is_v1_model(v) -> bool:
if isinstance(v, V1BaseModel):
return True
try:
if ... | import inspect
import typing
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 import BaseModel as V1BaseModel
else:
from pydantic import BaseModel as V1BaseModel
def is_v1_model(v) -> bool:
if isinstance(v, V1BaseModel):
return True
try:
if ... | |
5,616 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/pydantic/v2_schema.py | 57,64 | 1,125 | process_v2_params | 70,97 | 64,97 | # Note: This file should only be imported under a HAS_PYDANTIC_V2 flag
import inspect
import typing
import typing as t
import pendulum
import pydantic
from pydantic import BaseModel as V2BaseModel
from pydantic import ConfigDict, PydanticUndefinedAnnotation, create_model
from pydantic.type_adapter import TypeAdapter
... | # Note: This file should only be imported under a HAS_PYDANTIC_V2 flag
import inspect
import typing
import typing as t
import pendulum
import pydantic
from pydantic import BaseModel as V2BaseModel
from pydantic import ConfigDict, PydanticUndefinedAnnotation, create_model
from pydantic.type_adapter import TypeAdapter
... | # Pydantic model creation will fail if names collide with the BaseModel type
if hasattr(pydantic.BaseModel, param.name):
name = param.name + "__"
aliases[name] = param.name
else:
name = param.name
type_ = t.Any if param.annotation is inspect._empty else param.annotation
# R... | """
Generate a sanitized name, type, and pydantic.Field for a given parameter.
This implementation is exactly the same as the v1 implementation except
that it uses pydantic v2 constructs.
"""
# Pydantic model creation will fail if names collide with the BaseModel type
if hasattr(pydantic.Ba... | 93 | 856 | 304 | 1,160 | # Note: This file should only be imported under a HAS_PYDANTIC_V2 flag
import inspect
import typing
import typing as t
import pendulum
import pydantic
from pydantic import BaseModel as V2BaseModel
from pydantic import ConfigDict, PydanticUndefinedAnnotation, create_model
from pydantic.type_adapter import TypeAdapter
... | # Note: This file should only be imported under a HAS_PYDANTIC_V2 flag
import inspect
import typing
import typing as t
import pendulum
import pydantic
from pydantic import BaseModel as V2BaseModel
from pydantic import ConfigDict, PydanticUndefinedAnnotation, create_model
from pydantic.type_adapter import TypeAdapter
... | |
5,617 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/schemas/fields.py | 37,39 | 1,71 | validate | 39,49 | 39,49 | import datetime
from typing import Optional
from uuid import UUID
import pendulum
from typing_extensions import TypeAlias
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 import BaseModel, Field
else:
from pydantic import BaseModel, Field
# Rather than subclassing... | import datetime
from typing import Optional
from uuid import UUID
import pendulum
from typing_extensions import TypeAlias
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 import BaseModel, Field
else:
from pydantic import BaseModel, Field
# Rather than subclassing... | if isinstance(v, str):
parsed = pendulum.parse(v)
assert isinstance(parsed, pendulum.DateTime)
return parsed
elif isinstance(v, datetime.datetime):
return pendulum.instance(v)
else:
raise ValueError("Unrecognized datetime.")
| if isinstance(v, str):
parsed = pendulum.parse(v)
assert isinstance(parsed, pendulum.DateTime)
return parsed
elif isinstance(v, datetime.datetime):
return pendulum.instance(v)
else:
raise ValueError("Unrecognized datetime.")
| 20 | 555 | 91 | 646 | import datetime
from typing import Optional
from uuid import UUID
import pendulum
from typing_extensions import TypeAlias
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 import BaseModel, Field
else:
from pydantic import BaseModel, Field
# Rather than subclassing... | import datetime
from typing import Optional
from uuid import UUID
import pendulum
from typing_extensions import TypeAlias
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 import BaseModel, Field
else:
from pydantic import BaseModel, Field
# Rather than subclassing... | |
5,618 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_internal/schemas/serializers.py | 15,16 | 1,27 | orjson_dumps_extra_compatible | 24,27 | 16,27 | from typing import Any
import orjson
def orjson_dumps(v: Any, *, default: Any) -> str:
"""
Utility for dumping a value to JSON using orjson.
orjson.dumps returns bytes, to match standard json.dumps we need to decode.
"""
return orjson.dumps(v, default=default).decode()
def orjson_dumps_extra_c... | from typing import Any
import orjson
def orjson_dumps(v: Any, *, default: Any) -> str:
"""
Utility for dumping a value to JSON using orjson.
orjson.dumps returns bytes, to match standard json.dumps we need to decode.
"""
return orjson.dumps(v, default=default).decode()
def orjson_dumps_extra_c... | return orjson.dumps(
v, default=default, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY
).decode()
| """
Utility for dumping a value to JSON using orjson, but allows for
1) non-string keys: this is helpful for situations like pandas dataframes,
which can result in non-string keys
2) numpy types: for serializing numpy arrays
orjson.dumps returns bytes, to match standard json.dumps we need to de... | 8 | 224 | 54 | 278 | from typing import Any
import orjson
def orjson_dumps(v: Any, *, default: Any) -> str:
"""
Utility for dumping a value to JSON using orjson.
orjson.dumps returns bytes, to match standard json.dumps we need to decode.
"""
return orjson.dumps(v, default=default).decode()
def orjson_dumps_extra_c... | from typing import Any
import orjson
def orjson_dumps(v: Any, *, default: Any) -> str:
"""
Utility for dumping a value to JSON using orjson.
orjson.dumps returns bytes, to match standard json.dumps we need to decode.
"""
return orjson.dumps(v, default=default).decode()
def orjson_dumps_extra_c... | |
5,620 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/fastapi/datastructures.py | 51,52 | 1,59 | Default | 58,59 | 52,59 | from typing import Any, Callable, Dict, Iterable, Type, TypeVar
from prefect._vendor.starlette.datastructures import URL as URL # noqa: F401
from prefect._vendor.starlette.datastructures import Address as Address # noqa: F401
from prefect._vendor.starlette.datastructures import FormData as FormData # noqa: F401
fro... | from typing import Any, Callable, Dict, Iterable, Type, TypeVar
from prefect._vendor.starlette.datastructures import URL as URL # noqa: F401
from prefect._vendor.starlette.datastructures import Address as Address # noqa: F401
from prefect._vendor.starlette.datastructures import FormData as FormData # noqa: F401
fro... | return DefaultPlaceholder(value) # type: ignore
| """
You shouldn't use this function directly.
It's used internally to recognize when a default value has been overwritten, even
if the overridden default value was truthy.
"""
return DefaultPlaceholder(value) # type: ignore
| 5 | 616 | 15 | 631 | from typing import Any, Callable, Dict, Iterable, Type, TypeVar
from prefect._vendor.starlette.datastructures import URL as URL # noqa: F401
from prefect._vendor.starlette.datastructures import Address as Address # noqa: F401
from prefect._vendor.starlette.datastructures import FormData as FormData # noqa: F401
fro... | from typing import Any, Callable, Dict, Iterable, Type, TypeVar
from prefect._vendor.starlette.datastructures import URL as URL # noqa: F401
from prefect._vendor.starlette.datastructures import Address as Address # noqa: F401
from prefect._vendor.starlette.datastructures import FormData as FormData # noqa: F401
fro... | |
5,621 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/fastapi/datastructures.py | 19,21 | 14,30 | validate | UploadFile | 21,25 | 21,25 | class UploadFile(StarletteUploadFile):
@classmethod
def __get_validators__(cls: Type["UploadFile"]) -> Iterable[Callable[..., Any]]:
yield cls.validate
@classmethod
def validate(cls: Type["UploadFile"], v: Any) -> Any:
FILL_FUNC_BODY @classmethod
def __modify_schema__(cls, field_schema: ... | class UploadFile(StarletteUploadFile):
@classmethod
def __get_validators__(cls: Type["UploadFile"]) -> Iterable[Callable[..., Any]]:
yield cls.validate
@classmethod
def validate(cls: Type["UploadFile"], v: Any) -> Any:
FILL_FUNC_BODY @classmethod
def __modify_schema__(cls, field_schema: ... | if not isinstance(v, StarletteUploadFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
| if not isinstance(v, StarletteUploadFile):
raise ValueError(f"Expected UploadFile, received: {type(v)}")
return v
| 11 | 143 | 44 | 187 | from typing import Any, Callable, Dict, Iterable, Type, TypeVar
from prefect._vendor.starlette.datastructures import URL as URL # noqa: F401
from prefect._vendor.starlette.datastructures import Address as Address # noqa: F401
from prefect._vendor.starlette.datastructures import FormData as FormData # noqa: F401
fro... | from typing import Any, Callable, Dict, Iterable, Type, TypeVar
from prefect._vendor.starlette.datastructures import URL as URL # noqa: F401
from prefect._vendor.starlette.datastructures import Address as Address # noqa: F401
from prefect._vendor.starlette.datastructures import FormData as FormData # noqa: F401
fro... |
5,622 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/fastapi/encoders.py | 35,46 | 1,178 | jsonable_encoder | 46,178 | 46,178 | import dataclasses
from collections import defaultdict, deque
from enum import Enum
from pathlib import PurePath
from types import GeneratorType
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 imp... | import dataclasses
from collections import defaultdict, deque
from enum import Enum
from pathlib import PurePath
from types import GeneratorType
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 imp... | custom_encoder = custom_encoder or {}
if custom_encoder:
if type(obj) in custom_encoder:
return custom_encoder[type(obj)](obj)
else:
for encoder_type, encoder_instance in custom_encoder.items():
if isinstance(obj, encoder_type):
return ... | custom_encoder = custom_encoder or {}
if custom_encoder:
if type(obj) in custom_encoder:
return custom_encoder[type(obj)](obj)
else:
for encoder_type, encoder_instance in custom_encoder.items():
if isinstance(obj, encoder_type):
return ... | 286 | 537 | 1,444 | 1,981 | import dataclasses
from collections import defaultdict, deque
from enum import Enum
from pathlib import PurePath
from types import GeneratorType
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 imp... | import dataclasses
from collections import defaultdict, deque
from enum import Enum
from pathlib import PurePath
from types import GeneratorType
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 imp... | |
5,623 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/fastapi/exception_handlers.py | 17,18 | 1,41 | http_exception_handler | 18,26 | 18,26 | from prefect._vendor.fastapi.encoders import jsonable_encoder
from prefect._vendor.fastapi.exceptions import (
RequestValidationError,
WebSocketRequestValidationError,
)
from prefect._vendor.fastapi.utils import is_body_allowed_for_status_code
from prefect._vendor.fastapi.websockets import WebSocket
from prefec... | from prefect._vendor.fastapi.encoders import jsonable_encoder
from prefect._vendor.fastapi.exceptions import (
RequestValidationError,
WebSocketRequestValidationError,
)
from prefect._vendor.fastapi.utils import is_body_allowed_for_status_code
from prefect._vendor.fastapi.websockets import WebSocket
from prefec... | headers = getattr(exc, "headers", None)
if not is_body_allowed_for_status_code(exc.status_code):
return Response(status_code=exc.status_code, headers=headers)
return JSONResponse(
{"detail": exc.detail}, status_code=exc.status_code, headers=headers
)
| headers = getattr(exc, "headers", None)
if not is_body_allowed_for_status_code(exc.status_code):
return Response(status_code=exc.status_code, headers=headers)
return JSONResponse(
{"detail": exc.detail}, status_code=exc.status_code, headers=headers
)
| 18 | 374 | 96 | 470 | from prefect._vendor.fastapi.encoders import jsonable_encoder
from prefect._vendor.fastapi.exceptions import (
RequestValidationError,
WebSocketRequestValidationError,
)
from prefect._vendor.fastapi.utils import is_body_allowed_for_status_code
from prefect._vendor.fastapi.websockets import WebSocket
from prefec... | from prefect._vendor.fastapi.encoders import jsonable_encoder
from prefect._vendor.fastapi.exceptions import (
RequestValidationError,
WebSocketRequestValidationError,
)
from prefect._vendor.fastapi.utils import is_body_allowed_for_status_code
from prefect._vendor.fastapi.websockets import WebSocket
from prefec... | |
5,625 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/fastapi/openapi/models.py | 33,35 | 28,42 | validate | EmailStr | 35,42 | 35,42 | class EmailStr(str): # type: ignore
@classmethod
def __get_validators__(cls) -> Iterable[Callable[..., Any]]:
yield cls.validate
@classmethod
def validate(cls, v: Any) -> str:
FILL_FUNC_BODY | class EmailStr(str): # type: ignore
@classmethod
def __get_validators__(cls) -> Iterable[Callable[..., Any]]:
yield cls.validate
@classmethod
def validate(cls, v: Any) -> str:
FILL_FUNC_BODY | logger.warning(
"email-validator not installed, email fields will be treated as str.\n"
"To install, run: pip install email-validator"
)
return str(v)
| logger.warning(
"email-validator not installed, email fields will be treated as str.\n"
"To install, run: pip install email-validator"
)
return str(v)
| 20 | 80 | 60 | 140 | from enum import Enum
from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Union
from prefect._vendor.fastapi.logger import logger
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 import AnyUrl, BaseModel, Field
else:
from pydantic import AnyUrl, B... | from enum import Enum
from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Union
from prefect._vendor.fastapi.logger import logger
from prefect._internal.pydantic import HAS_PYDANTIC_V2
if HAS_PYDANTIC_V2:
from pydantic.v1 import AnyUrl, BaseModel, Field
else:
from pydantic import AnyUrl, B... |
5,626 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/fastapi/responses.py | 36,37 | 35,41 | render | ORJSONResponse | 37,41 | 37,41 | class ORJSONResponse(JSONResponse):
def render(self, content: Any) -> bytes:
FILL_FUNC_BODY | class ORJSONResponse(JSONResponse):
def render(self, content: Any) -> bytes:
FILL_FUNC_BODY | assert orjson is not None, "orjson must be installed to use ORJSONResponse"
return orjson.dumps(
content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY
)
| assert orjson is not None, "orjson must be installed to use ORJSONResponse"
return orjson.dumps(
content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY
)
| 19 | 34 | 70 | 104 | from typing import Any
from prefect._vendor.starlette.responses import FileResponse as FileResponse # noqa
from prefect._vendor.starlette.responses import HTMLResponse as HTMLResponse # noqa
from prefect._vendor.starlette.responses import JSONResponse as JSONResponse # noqa
from prefect._vendor.starlette.responses ... | from typing import Any
from prefect._vendor.starlette.responses import FileResponse as FileResponse # noqa
from prefect._vendor.starlette.responses import HTMLResponse as HTMLResponse # noqa
from prefect._vendor.starlette.responses import JSONResponse as JSONResponse # noqa
from prefect._vendor.starlette.responses ... |
5,627 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/fastapi/responses.py | 30,31 | 29,35 | render | UJSONResponse | 31,35 | 31,35 | class UJSONResponse(JSONResponse):
def render(self, content: Any) -> bytes:
FILL_FUNC_BODY | class UJSONResponse(JSONResponse):
def render(self, content: Any) -> bytes:
FILL_FUNC_BODY | assert ujson is not None, "ujson must be installed to use UJSONResponse"
return ujson.dumps(content, ensure_ascii=False).encode("utf-8")
| assert ujson is not None, "ujson must be installed to use UJSONResponse"
return ujson.dumps(content, ensure_ascii=False).encode("utf-8")
| 15 | 34 | 52 | 86 | from typing import Any
from prefect._vendor.starlette.responses import FileResponse as FileResponse # noqa
from prefect._vendor.starlette.responses import HTMLResponse as HTMLResponse # noqa
from prefect._vendor.starlette.responses import JSONResponse as JSONResponse # noqa
from prefect._vendor.starlette.responses ... | from typing import Any
from prefect._vendor.starlette.responses import FileResponse as FileResponse # noqa
from prefect._vendor.starlette.responses import HTMLResponse as HTMLResponse # noqa
from prefect._vendor.starlette.responses import JSONResponse as JSONResponse # noqa
from prefect._vendor.starlette.responses ... |
5,628 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/fastapi/security/utils.py | 4,7 | 1,11 | get_authorization_scheme_param | 7,11 | 7,11 | from typing import Optional, Tuple
def get_authorization_scheme_param(
authorization_header_value: Optional[str],
) -> Tuple[str, str]:
FILL_FUNC_BODY | from typing import Optional, Tuple
def get_authorization_scheme_param(
authorization_header_value: Optional[str],
) -> Tuple[str, str]:
FILL_FUNC_BODY | if not authorization_header_value:
return "", ""
scheme, _, param = authorization_header_value.partition(" ")
return scheme, param
| if not authorization_header_value:
return "", ""
scheme, _, param = authorization_header_value.partition(" ")
return scheme, param
| 15 | 55 | 43 | 98 | from typing import Optional, Tuple
def get_authorization_scheme_param(
authorization_header_value: Optional[str],
) -> Tuple[str, str]:
FILL_FUNC_BODY | from typing import Optional, Tuple
def get_authorization_scheme_param(
authorization_header_value: Optional[str],
) -> Tuple[str, str]:
FILL_FUNC_BODY | |
5,629 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/_exception_handler.py | 30,33 | 1,81 | wrap_app_handling_exceptions | 33,81 | 33,81 | import typing
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.exceptions import HTTPException
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.types import (
ASGIAp... | import typing
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.exceptions import HTTPException
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.types import (
ASGIAp... | exception_handlers: ExceptionHandlers
status_handlers: StatusHandlers
try:
exception_handlers, status_handlers = conn.scope["starlette.exception_handlers"]
except KeyError:
exception_handlers, status_handlers = {}, {}
async def wrapped_app(scope: Scope, receive: Receive, send: Send)... | exception_handlers: ExceptionHandlers
status_handlers: StatusHandlers
try:
exception_handlers, status_handlers = conn.scope["starlette.exception_handlers"]
except KeyError:
exception_handlers, status_handlers = {}, {}
async def wrapped_app(scope: Scope, receive: Receive, send: Send)... | 131 | 296 | 464 | 760 | import typing
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.exceptions import HTTPException
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.types import (
ASGIAp... | import typing
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.exceptions import HTTPException
from prefect._vendor.starlette.requests import Request
from prefect._vendor.starlette.types import (
ASGIAp... | |
5,630 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/authentication.py | 28,35 | 1,160 | requires | 35,109 | 35,109 | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... | scopes_list = [scopes] if isinstance(scopes, str) else list(scopes)
def decorator(
func: typing.Callable[_P, typing.Any],
) -> typing.Callable[_P, typing.Any]:
sig = inspect.signature(func)
for idx, parameter in enumerate(sig.parameters.values()):
if parameter.name == "r... | scopes_list = [scopes] if isinstance(scopes, str) else list(scopes)
def decorator(
func: typing.Callable[_P, typing.Any],
) -> typing.Callable[_P, typing.Any]:
sig = inspect.signature(func)
for idx, parameter in enumerate(sig.parameters.values()):
if parameter.name == "r... | 212 | 701 | 898 | 1,599 | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... | |
5,631 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/authentication.py | 114,117 | 113,120 | authenticate | AuthenticationBackend | 117,120 | 117,120 | class AuthenticationBackend:
async def authenticate(
self, conn: HTTPConnection
) -> typing.Optional[typing.Tuple["AuthCredentials", "BaseUser"]]:
FILL_FUNC_BODY | class AuthenticationBackend:
async def authenticate(
self, conn: HTTPConnection
) -> typing.Optional[typing.Tuple["AuthCredentials", "BaseUser"]]:
FILL_FUNC_BODY | raise NotImplementedError() # pragma: no cover
| raise NotImplementedError() # pragma: no cover
| 6 | 56 | 21 | 77 | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... |
5,632 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/authentication.py | 134,136 | 125,139 | identity | BaseUser | 136,139 | 136,139 | class BaseUser:
@property
def is_authenticated(self) -> bool:
raise NotImplementedError() # pragma: no cover
@property
def display_name(self) -> str:
raise NotImplementedError() # pragma: no cover
@property
def identity(self) -> str:
FILL_FUNC_BODY | class BaseUser:
@property
def is_authenticated(self) -> bool:
raise NotImplementedError() # pragma: no cover
@property
def display_name(self) -> str:
raise NotImplementedError() # pragma: no cover
@property
def identity(self) -> str:
FILL_FUNC_BODY | raise NotImplementedError() # pragma: no cover
| raise NotImplementedError() # pragma: no cover
| 6 | 100 | 21 | 121 | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... |
5,633 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/authentication.py | 143,145 | 139,152 | is_authenticated | SimpleUser | 145,147 | 145,147 | class SimpleUser(BaseUser):
def __init__(self, username: str) -> None:
self.username = username
@property
def is_authenticated(self) -> bool:
FILL_FUNC_BODY @property
def display_name(self) -> str:
return self.username
| class SimpleUser(BaseUser):
def __init__(self, username: str) -> None:
self.username = username
@property
def is_authenticated(self) -> bool:
FILL_FUNC_BODY @property
def display_name(self) -> str:
return self.username
| return True
| return True
| 2 | 86 | 7 | 93 | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... |
5,634 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/authentication.py | 157,159 | 152,160 | display_name | UnauthenticatedUser | 159,160 | 159,160 | class UnauthenticatedUser(BaseUser):
@property
def is_authenticated(self) -> bool:
return False
@property
def display_name(self) -> str:
FILL_FUNC_BODY | class UnauthenticatedUser(BaseUser):
@property
def is_authenticated(self) -> bool:
return False
@property
def display_name(self) -> str:
FILL_FUNC_BODY | return ""
| return ""
| 2 | 62 | 5 | 67 | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... | import functools
import inspect
import sys
import typing
from urllib.parse import urlencode
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from pre... |
5,635 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/background.py | 35,38 | 31,44 | add_task | BackgroundTasks | 38,41 | 38,41 | class BackgroundTasks(BackgroundTask):
def __init__(self, tasks: typing.Optional[typing.Sequence[BackgroundTask]] = None):
self.tasks = list(tasks) if tasks else []
def add_task(
self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs
) -> None:
FILL_FUNC_BODY async... | class BackgroundTasks(BackgroundTask):
def __init__(self, tasks: typing.Optional[typing.Sequence[BackgroundTask]] = None):
self.tasks = list(tasks) if tasks else []
def add_task(
self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs
) -> None:
FILL_FUNC_BODY async... | task = BackgroundTask(func, *args, **kwargs)
self.tasks.append(task)
| task = BackgroundTask(func, *args, **kwargs)
self.tasks.append(task)
| 6 | 133 | 31 | 164 | import sys
import typing
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
P = Pa... | import sys
import typing
if sys.version_info >= (3, 10): # pragma: no cover
from typing import ParamSpec
else: # pragma: no cover
from typing_extensions import ParamSpec
from prefect._vendor.starlette._utils import is_async_callable
from prefect._vendor.starlette.concurrency import run_in_threadpool
P = Pa... |
5,636 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/concurrency.py | 10,11 | 1,60 | run_until_first_complete | 11,29 | 11,29 | import functools
import typing
import warnings
import anyio.to_thread
T = typing.TypeVar("T")
async def run_until_first_complete(*args: typing.Tuple[typing.Callable, dict]) -> None: # type: ignore[type-arg] # noqa: E501
FILL_FUNC_BODYasync def run_in_threadpool(
func: typing.Callable[..., T], *args: typing.An... | import functools
import typing
import warnings
import anyio.to_thread
T = typing.TypeVar("T")
async def run_until_first_complete(*args: typing.Tuple[typing.Callable, dict]) -> None: # type: ignore[type-arg] # noqa: E501
FILL_FUNC_BODYasync def run_in_threadpool(
func: typing.Callable[..., T], *args: typing.An... | warnings.warn(
"run_until_first_complete is deprecated "
"and will be removed in a future version.",
DeprecationWarning,
)
async with anyio.create_task_group() as task_group:
async def run(func: typing.Callable[[], typing.Coroutine]) -> None: # type: ignore[type-arg] # no... | warnings.warn(
"run_until_first_complete is deprecated "
"and will be removed in a future version.",
DeprecationWarning,
)
async with anyio.create_task_group() as task_group:
async def run(func: typing.Callable[[], typing.Coroutine]) -> None: # type: ignore[type-arg] # no... | 63 | 379 | 227 | 606 | import functools
import typing
import warnings
import anyio.to_thread
T = typing.TypeVar("T")
async def run_until_first_complete(*args: typing.Tuple[typing.Callable, dict]) -> None: # type: ignore[type-arg] # noqa: E501
FILL_FUNC_BODYasync def run_in_threadpool(
func: typing.Callable[..., T], *args: typing.An... | import functools
import typing
import warnings
import anyio.to_thread
T = typing.TypeVar("T")
async def run_until_first_complete(*args: typing.Tuple[typing.Callable, dict]) -> None: # type: ignore[type-arg] # noqa: E501
FILL_FUNC_BODYasync def run_in_threadpool(
func: typing.Callable[..., T], *args: typing.An... | |
5,637 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/config.py | 130,136 | 51,152 | _perform_cast | Config | 136,152 | 136,152 | class Config:
def __init__(
self,
env_file: typing.Optional[typing.Union[str, Path]] = None,
environ: typing.Mapping[str, str] = environ,
env_prefix: str = "",
) -> None:
self.environ = environ
self.env_prefix = env_prefix
self.file_values: typing.Dict[str... | class Config:
def __init__(
self,
env_file: typing.Optional[typing.Union[str, Path]] = None,
environ: typing.Mapping[str, str] = environ,
env_prefix: str = "",
) -> None:
self.environ = environ
self.env_prefix = env_prefix
self.file_values: typing.Dict[str... | if cast is None or value is None:
return value
elif cast is bool and isinstance(value, str):
mapping = {"true": True, "1": True, "false": False, "0": False}
value = value.lower()
if value not in mapping:
raise ValueError(
... | if cast is None or value is None:
return value
elif cast is bool and isinstance(value, str):
mapping = {"true": True, "1": True, "false": False, "0": False}
value = value.lower()
if value not in mapping:
raise ValueError(
... | 67 | 894 | 178 | 1,072 | import os
import typing
from pathlib import Path
class undefined:
pass
class EnvironError(Exception):
pass
class Environ(typing.MutableMapping[str, str]):
def __init__(self, environ: typing.MutableMapping[str, str] = os.environ):
self._environ = environ
self._has_been_read: typing.Set[... | import os
import typing
from pathlib import Path
class undefined:
pass
class EnvironError(Exception):
pass
class Environ(typing.MutableMapping[str, str]):
def __init__(self, environ: typing.MutableMapping[str, str] = os.environ):
self._environ = environ
self._has_been_read: typing.Set[... |
5,638 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/convertors.py | 86,87 | 1,88 | register_url_convertor | 87,88 | 87,88 | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... | CONVERTOR_TYPES[key] = convertor
| CONVERTOR_TYPES[key] = convertor
| 3 | 791 | 17 | 808 | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... | |
5,639 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/convertors.py | 14,15 | 8,18 | to_string | Convertor | 15,18 | 15,18 | class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
FILL_FUNC_BODY | class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
FILL_FUNC_BODY | raise NotImplementedError() # pragma: no cover
| raise NotImplementedError() # pragma: no cover
| 6 | 86 | 21 | 107 | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
FILL_FUNC_BODYclass StringConvertor(Conver... | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
FILL_FUNC_BODYclass StringConvertor(Conver... |
5,640 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/convertors.py | 59,60 | 53,67 | to_string | FloatConvertor | 60,67 | 60,67 | class FloatConvertor(Convertor[float]):
regex = r"[0-9]+(\.[0-9]+)?"
def convert(self, value: str) -> float:
return float(value)
def to_string(self, value: float) -> str:
FILL_FUNC_BODY | class FloatConvertor(Convertor[float]):
regex = r"[0-9]+(\.[0-9]+)?"
def convert(self, value: str) -> float:
return float(value)
def to_string(self, value: float) -> str:
FILL_FUNC_BODY | value = float(value)
assert value >= 0.0, "Negative floats are not supported"
assert not math.isnan(value), "NaN values are not supported"
assert not math.isinf(value), "Infinite values are not supported"
return ("%0.20f" % value).rstrip("0").rstrip(".")
| value = float(value)
assert value >= 0.0, "Negative floats are not supported"
assert not math.isnan(value), "NaN values are not supported"
assert not math.isinf(value), "Infinite values are not supported"
return ("%0.20f" % value).rstrip("0").rstrip(".")
| 32 | 85 | 96 | 181 | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... |
5,641 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/convertors.py | 47,48 | 41,53 | to_string | IntegerConvertor | 48,53 | 48,53 | class IntegerConvertor(Convertor[int]):
regex = "[0-9]+"
def convert(self, value: str) -> int:
return int(value)
def to_string(self, value: int) -> str:
FILL_FUNC_BODY | class IntegerConvertor(Convertor[int]):
regex = "[0-9]+"
def convert(self, value: str) -> int:
return int(value)
def to_string(self, value: int) -> str:
FILL_FUNC_BODY | value = int(value)
assert value >= 0, "Negative integers are not supported"
return str(value)
| value = int(value)
assert value >= 0, "Negative integers are not supported"
return str(value)
| 14 | 74 | 37 | 111 | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... |
5,642 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/convertors.py | 34,35 | 31,41 | convert | PathConvertor | 35,37 | 35,37 | class PathConvertor(Convertor[str]):
regex = ".*"
def convert(self, value: str) -> str:
FILL_FUNC_BODY def to_string(self, value: str) -> str:
return str(value)
| class PathConvertor(Convertor[str]):
regex = ".*"
def convert(self, value: str) -> str:
FILL_FUNC_BODY def to_string(self, value: str) -> str:
return str(value)
| return str(value)
| return str(value)
| 2 | 71 | 10 | 81 | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... |
5,643 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/convertors.py | 24,25 | 18,31 | to_string | StringConvertor | 25,31 | 25,31 | class StringConvertor(Convertor[str]):
regex = "[^/]+"
def convert(self, value: str) -> str:
return value
def to_string(self, value: str) -> str:
FILL_FUNC_BODY | class StringConvertor(Convertor[str]):
regex = "[^/]+"
def convert(self, value: str) -> str:
return value
def to_string(self, value: str) -> str:
FILL_FUNC_BODY | value = str(value)
assert "/" not in value, "May not contain path separators"
assert value, "Must not be empty"
return value
| value = str(value)
assert "/" not in value, "May not contain path separators"
assert value, "Must not be empty"
return value
| 21 | 70 | 48 | 118 | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... |
5,644 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/convertors.py | 70,71 | 67,77 | convert | UUIDConvertor | 71,73 | 71,73 | class UUIDConvertor(Convertor[uuid.UUID]):
regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
def convert(self, value: str) -> uuid.UUID:
FILL_FUNC_BODY def to_string(self, value: uuid.UUID) -> str:
return str(value)
| class UUIDConvertor(Convertor[uuid.UUID]):
regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
def convert(self, value: str) -> uuid.UUID:
FILL_FUNC_BODY def to_string(self, value: uuid.UUID) -> str:
return str(value)
| return uuid.UUID(value)
| return uuid.UUID(value)
| 2 | 127 | 13 | 140 | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... | import math
import typing
import uuid
T = typing.TypeVar("T")
class Convertor(typing.Generic[T]):
regex: typing.ClassVar[str] = ""
def convert(self, value: str) -> T:
raise NotImplementedError() # pragma: no cover
def to_string(self, value: T) -> str:
raise NotImplementedError() # pra... |
5,645 | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect | /home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/_vendor/starlette/datastructures.py | 502,503 | 486,508 | close | FormData | 503,508 | 503,508 | class FormData(ImmutableMultiDict[str, typing.Union[UploadFile, str]]):
"""
An immutable multidict, containing both file uploads and text input.
"""
def __init__(
self,
*args: typing.Union[
"FormData",
typing.Mapping[str, typing.Union[str, UploadFile]],
... | class FormData(ImmutableMultiDict[str, typing.Union[UploadFile, str]]):
"""
An immutable multidict, containing both file uploads and text input.
"""
def __init__(
self,
*args: typing.Union[
"FormData",
typing.Mapping[str, typing.Union[str, UploadFile]],
... | for key, value in self.multi_items():
if isinstance(value, UploadFile):
await value.close()
| for key, value in self.multi_items():
if isinstance(value, UploadFile):
await value.close()
| 10 | 183 | 39 | 222 | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... | import typing
from shlex import shlex
from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit
from prefect._vendor.starlette.concurrency import run_in_threadpool
from prefect._vendor.starlette.types import Scope
class Address(typing.NamedTuple):
host: str
port: int
_KeyType = typing.TypeVar("_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.