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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
816 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/builtins/feature_transformers.py | 140,141 | 86,161 | transform | ContinuousSelector | 152,161 | 141,161 | class ContinuousSelector(BaseEstimator, TransformerMixin):
"""Meta-transformer for selecting continuous features and transform them using PCA.
Parameters
----------
threshold : int, default=10
Maximum number of unique values per feature to consider the feature
to be categorical.
s... | class ContinuousSelector(BaseEstimator, TransformerMixin):
"""Meta-transformer for selecting continuous features and transform them using PCA.
Parameters
----------
threshold : int, default=10
Maximum number of unique values per feature to consider the feature
to be categorical.
s... | selected = auto_select_categorical_features(X, threshold=self.threshold)
_, X_sel, n_selected, _ = _X_selected(X, selected)
if n_selected == 0:
# No features selected.
raise ValueError('No continuous feature was found!')
else:
pca = PCA(svd_solver=sel... | """Select continuous features and transform them using PCA.
Parameters
----------
X: numpy ndarray, {n_samples, n_components}
New data, where n_samples is the number of samples and n_components is the number of components.
Returns
-------
array-like,... | 33 | 661 | 146 | 807 | # -*- coding: utf-8 -*-
"""Copyright 2015-Present Randal S. Olson.
This file is part of the TPOT library.
TPOT is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your... | # -*- coding: utf-8 -*-
"""Copyright 2015-Present Randal S. Olson.
This file is part of the TPOT library.
TPOT is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your... |
818 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/builtins/nn.py | 103,104 | 98,202 | fit | PytorchClassifier | 120,154 | 104,154 | class PytorchClassifier(PytorchEstimator, ClassifierMixin):
@abstractmethod
def _init_model(self, X, y): # pragma: no cover
pass
def fit(self, X, y):
FILL_FUNC_BODY def validate_inputs(self, X, y):
# Things we don't want to allow until we've tested them:
# - Sparse inputs
... | class PytorchClassifier(PytorchEstimator, ClassifierMixin):
@abstractmethod
def _init_model(self, X, y): # pragma: no cover
pass
def fit(self, X, y):
"""Generalizable method for fitting a PyTorch estimator to a training
set.
Parameters
----------
X : array-l... | # pylint: disable=no-member
self._init_model(X, y)
assert _pytorch_model_is_fully_initialized(self)
for epoch in range(self.num_epochs):
for i, (samples, labels) in enumerate(self.data_loader):
samples = samples.to(self.device)
labels = labe... | """Generalizable method for fitting a PyTorch estimator to a training
set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y ... | 73 | 711 | 340 | 1,051 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... |
819 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/builtins/nn.py | 88,89 | 70,98 | fit_transform | PytorchEstimator | 89,92 | 89,92 | class PytorchEstimator(BaseEstimator):
"""Base class for Pytorch-based estimators (currently only classifiers) for
use in TPOT.
In the future, these will be merged into TPOT's main code base.
"""
@abstractmethod
def fit(self, X, y): # pragma: no cover
pass
@abstractmethod
def ... | class PytorchEstimator(BaseEstimator):
"""Base class for Pytorch-based estimators (currently only classifiers) for
use in TPOT.
In the future, these will be merged into TPOT's main code base.
"""
@abstractmethod
def fit(self, X, y): # pragma: no cover
pass
@abstractmethod
def ... | self.fit(X, y)
return self.transform(X)
| self.fit(X, y)
return self.transform(X)
| 4 | 202 | 23 | 225 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... |
820 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/builtins/nn.py | 261,262 | 230,287 | _init_model | PytorchLRClassifier | 262,284 | 262,284 | class PytorchLRClassifier(PytorchClassifier):
"""Logistic Regression classifier, implemented in PyTorch, for use with
TPOT.
For examples on standalone use (i.e., non-TPOT) refer to:
https://github.com/trang1618/tpot-nn/blob/master/tpot_nn/estimator_sandbox.py
"""
def __init__(
self,
... | class PytorchLRClassifier(PytorchClassifier):
"""Logistic Regression classifier, implemented in PyTorch, for use with
TPOT.
For examples on standalone use (i.e., non-TPOT) refer to:
https://github.com/trang1618/tpot-nn/blob/master/tpot_nn/estimator_sandbox.py
"""
def __init__(
self,
... | device = _get_cuda_device_if_available()
X, y = self.validate_inputs(X, y)
self.input_size = X.shape[-1]
self.num_classes = len(set(y))
X = torch.tensor(X, dtype=torch.float32)
y = torch.tensor(y, dtype=torch.long)
train_dset = TensorDataset(X, y)
# S... | device = _get_cuda_device_if_available()
X, y = self.validate_inputs(X, y)
self.input_size = X.shape[-1]
self.num_classes = len(set(y))
X = torch.tensor(X, dtype=torch.float32)
y = torch.tensor(y, dtype=torch.long)
train_dset = TensorDataset(X, y)
# S... | 58 | 351 | 298 | 649 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... |
821 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/builtins/nn.py | 314,315 | 287,339 | _init_model | PytorchMLPClassifier | 315,337 | 315,337 | class PytorchMLPClassifier(PytorchClassifier):
"""Multilayer Perceptron, implemented in PyTorch, for use with TPOT.
"""
def __init__(
self,
num_epochs=10,
batch_size=8,
learning_rate=0.01,
weight_decay=0,
verbose=False
):
self.num_epochs = num_epo... | class PytorchMLPClassifier(PytorchClassifier):
"""Multilayer Perceptron, implemented in PyTorch, for use with TPOT.
"""
def __init__(
self,
num_epochs=10,
batch_size=8,
learning_rate=0.01,
weight_decay=0,
verbose=False
):
self.num_epochs = num_epo... | device = _get_cuda_device_if_available()
X, y = self.validate_inputs(X, y)
self.input_size = X.shape[-1]
self.num_classes = len(set(y))
X = torch.tensor(X, dtype=torch.float32)
y = torch.tensor(y, dtype=torch.long)
train_dset = TensorDataset(X, y)
# S... | device = _get_cuda_device_if_available()
X, y = self.validate_inputs(X, y)
self.input_size = X.shape[-1]
self.num_classes = len(set(y))
X = torch.tensor(X, dtype=torch.float32)
y = torch.tensor(y, dtype=torch.long)
train_dset = TensorDataset(X, y)
# S... | 58 | 286 | 299 | 585 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... |
822 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/builtins/nn.py | 208,209 | 202,212 | forward | _LR | 209,212 | 209,212 | class _LR(nn.Module):
# pylint: disable=arguments-differ
def __init__(self, input_size, num_classes):
super(_LR, self).__init__()
self.linear = nn.Linear(input_size, num_classes)
def forward(self, x):
FILL_FUNC_BODY | class _LR(nn.Module):
# pylint: disable=arguments-differ
def __init__(self, input_size, num_classes):
super(_LR, self).__init__()
self.linear = nn.Linear(input_size, num_classes)
def forward(self, x):
FILL_FUNC_BODY | out = self.linear(x)
return out
| out = self.linear(x)
return out
| 5 | 89 | 18 | 107 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... |
823 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/builtins/nn.py | 223,224 | 212,230 | forward | _MLP | 224,230 | 224,230 | class _MLP(nn.Module):
# pylint: disable=arguments-differ
def __init__(self, input_size, num_classes):
super(_MLP, self).__init__()
self.hidden_size = round((input_size+num_classes)/2)
self.fc1 = nn.Linear(input_size, self.hidden_size)
self.relu = nn.Tanh()
self.fc2 = n... | class _MLP(nn.Module):
# pylint: disable=arguments-differ
def __init__(self, input_size, num_classes):
super(_MLP, self).__init__()
self.hidden_size = round((input_size+num_classes)/2)
self.fc1 = nn.Linear(input_size, self.hidden_size)
self.relu = nn.Tanh()
self.fc2 = n... | hidden = self.fc1(x)
r1 = self.relu(hidden)
out = self.fc2(r1)
return out
| hidden = self.fc1(x)
r1 = self.relu(hidden)
out = self.fc2(r1)
return out
| 11 | 152 | 47 | 199 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... |
826 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/builtins/stacking_estimator.py | 50,51 | 31,95 | fit | StackingEstimator | 67,70 | 51,70 | class StackingEstimator(BaseEstimator, TransformerMixin):
"""Meta-transformer for adding predictions and/or class probabilities as synthetic feature(s).
Parameters
----------
estimator : object
The base estimator from which the transformer is built.
"""
def __init__(self, estimator):
... | class StackingEstimator(BaseEstimator, TransformerMixin):
"""Meta-transformer for adding predictions and/or class probabilities as synthetic feature(s).
Parameters
----------
estimator : object
The base estimator from which the transformer is built.
"""
def __init__(self, estimator):
... | self.estimator.fit(X, y, **fit_params)
return self
| """Fit the StackingEstimator meta-transformer.
Parameters
----------
X: array-like of shape (n_samples, n_features)
The training input samples.
y: array-like, shape (n_samples,)
The target values (integers that correspond to classes in classification, rea... | 5 | 630 | 26 | 656 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... |
827 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/builtins/zero_count.py | 38,39 | 31,67 | transform | ZeroCount | 54,67 | 39,67 | class ZeroCount(BaseEstimator, TransformerMixin):
"""Adds the count of zeros and count of non-zeros per sample as features."""
def fit(self, X, y=None):
"""Dummy function to fit in with the sklearn API."""
return self
def transform(self, X, y=None):
FILL_FUNC_BODY | class ZeroCount(BaseEstimator, TransformerMixin):
"""Adds the count of zeros and count of non-zeros per sample as features."""
def fit(self, X, y=None):
"""Dummy function to fit in with the sklearn API."""
return self
def transform(self, X, y=None):
"""Transform data by adding two ... | X = check_array(X)
n_features = X.shape[1]
X_transformed = np.copy(X)
non_zero_vector = np.count_nonzero(X_transformed, axis=1)
non_zero = np.reshape(non_zero_vector, (-1, 1))
zero_col = np.reshape(n_features - non_zero_vector, (-1, 1))
X_transformed = np.hstac... | """Transform data by adding two virtual features.
Parameters
----------
X: numpy ndarray, {n_samples, n_components}
New data, where n_samples is the number of samples and n_components
is the number of components.
y: None
Unused
Return... | 35 | 210 | 175 | 385 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... |
830 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/metrics.py | 30,31 | 1,74 | balanced_accuracy | 49,72 | 31,72 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | all_classes = np.unique(np.append(y_true, y_pred))
all_class_accuracies = []
for this_class in all_classes:
this_class_sensitivity = 0.
this_class_specificity = 0.
if sum(y_true == this_class) != 0:
this_class_sensitivity = \
float(sum((y_pred == this_cla... | """Default scoring function: balanced accuracy.
Balanced accuracy computes each class' accuracy on a per-class basis using a
one-vs-rest encoding, then computes an unweighted average of the class accuracies.
Parameters
----------
y_true: numpy.ndarray {n_samples}
True class labels
... | 85 | 546 | 327 | 873 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | |
832 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/tpot.py | 44,45 | 36,71 | _init_pretest | TPOTClassifier | 51,71 | 45,71 | class TPOTClassifier(TPOTBase):
"""TPOT estimator for classification problems."""
scoring_function = 'accuracy' # Classification scoring
default_config_dict = classifier_config_dict # Classification dictionary
classification = True
regression = False
def _init_pretest(self, features, target)... | class TPOTClassifier(TPOTBase):
"""TPOT estimator for classification problems."""
scoring_function = 'accuracy' # Classification scoring
default_config_dict = classifier_config_dict # Classification dictionary
classification = True
regression = False
def _init_pretest(self, features, target)... | num_unique_target = len(np.unique(target))
# make sure train_size is at least num_unique_target
train_size=max(min(50,int(0.9*features.shape[0])), num_unique_target)
self.pretest_X, _, self.pretest_y, _ = \
train_test_split(
features,
... | """Set the sample of data used to verify pipelines work
with the passed data set.
This is not intend for anything other than perfunctory dataset
pipeline compatibility testing
"""
num_unique_target = len(np.unique(target))
# make sure train_size is at least num_u... | 54 | 139 | 267 | 406 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... |
833 | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot | /home/hieuvd/dung_repo/raw/stars_01/EpistasisLab_tpot/tpot/tpot/tpot.py | 79,80 | 71,91 | _init_pretest | TPOTRegressor | 83,91 | 80,91 | class TPOTRegressor(TPOTBase):
"""TPOT estimator for regression problems."""
scoring_function = 'neg_mean_squared_error' # Regression scoring
default_config_dict = regressor_config_dict # Regression dictionary
classification = False
regression = True
def _init_pretest(self, features, target)... | class TPOTRegressor(TPOTBase):
"""TPOT estimator for regression problems."""
scoring_function = 'neg_mean_squared_error' # Regression scoring
default_config_dict = regressor_config_dict # Regression dictionary
classification = False
regression = True
def _init_pretest(self, features, target)... | self.pretest_X, _, self.pretest_y, _ = \
train_test_split(
features,
target,
random_state=self.random_state,
test_size=None,
train_size=... | """Set the sample of data used to verify pipelines work with the passed data set.
"""
self.pretest_X, _, self.pretest_y, _ = \
train_test_split(
features,
target,
random_state=self.ra... | 13 | 125 | 90 | 215 | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... | # -*- coding: utf-8 -*-
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- Randal S. Olson (rso@randalolson.com)
- Weixuan Fu (weixuanf@upenn.edu)
- Daniel Angell (dpa34@drexel.edu)
- and many more generous open source contributors
TPOT is f... |
834 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/app/api/endpoints/download.py | 32,35 | 1,121 | download_file_hybrid | 35,121 | 35,121 | import os
import zipfile
import aiofiles
import httpx
import yaml
from fastapi import APIRouter, Request # 导入FastAPI组件
from starlette.responses import FileResponse
from app.api.models.APIResponseModel import ErrorResponseModel # 导入响应模型
from crawlers.hybrid.hybrid_crawler import HybridCrawler # 导入混合数据爬虫
router = A... | import os
import zipfile
import aiofiles
import httpx
import yaml
from fastapi import APIRouter, Request # 导入FastAPI组件
from starlette.responses import FileResponse
from app.api.models.APIResponseModel import ErrorResponseModel # 导入响应模型
from crawlers.hybrid.hybrid_crawler import HybridCrawler # 导入混合数据爬虫
router = A... | # 是否开启此端点/Whether to enable this endpoint
if not config["API"]["Download_Switch"]:
code = 400
message = "Download endpoint is disabled."
return ErrorResponseModel(code=code, message=message, router=request.url.path, params=dict(request.query_params))
# 开始解析数据/Start parsing data
... | # 是否开启此端点/Whether to enable this endpoint
if not config["API"]["Download_Switch"]:
code = 400
message = "Download endpoint is disabled."
return ErrorResponseModel(code=code, message=message, router=request.url.path, params=dict(request.query_params))
# 开始解析数据/Start parsing data
... | 270 | 455 | 1,355 | 1,810 | import os
import zipfile
import aiofiles
import httpx
import yaml
from fastapi import APIRouter, Request # 导入FastAPI组件
from starlette.responses import FileResponse
from app.api.models.APIResponseModel import ErrorResponseModel # 导入响应模型
from crawlers.hybrid.hybrid_crawler import HybridCrawler # 导入混合数据爬虫
router = A... | import os
import zipfile
import aiofiles
import httpx
import yaml
from fastapi import APIRouter, Request # 导入FastAPI组件
from starlette.responses import FileResponse
from app.api.models.APIResponseModel import ErrorResponseModel # 导入响应模型
from crawlers.hybrid.hybrid_crawler import HybridCrawler # 导入混合数据爬虫
router = A... | |
835 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/app/api/endpoints/hybrid_parsing.py | 15,20 | 1,54 | hybrid_parsing_single_video | 40,54 | 20,54 | import asyncio
from fastapi import APIRouter, Body, Query, Request, HTTPException # 导入FastAPI组件
from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型
# 爬虫/Crawler
from crawlers.hybrid.hybrid_crawler import HybridCrawler # 导入混合爬虫
HybridCrawler = HybridCrawler() # 实例化混合爬虫
router ... | import asyncio
from fastapi import APIRouter, Body, Query, Request, HTTPException # 导入FastAPI组件
from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型
# 爬虫/Crawler
from crawlers.hybrid.hybrid_crawler import HybridCrawler # 导入混合爬虫
HybridCrawler = HybridCrawler() # 实例化混合爬虫
router ... | try:
# 解析视频/Parse video
data = await HybridCrawler.hybrid_parsing_single_video(url=url, minimal=minimal)
# 返回数据/Return data
return ResponseModel(code=200,
router=request.url.path,
data=data)
except Exception as e:
... | """
# [中文]
### 用途:
- 该接口用于解析抖音/TikTok单一视频的数据。
### 参数:
- `url`: 视频链接、分享链接、分享文本。
### 返回:
- `data`: 视频数据。
# [English]
### Purpose:
- This endpoint is used to parse data of a single Douyin/TikTok video.
### Parameters:
- `url`: Video link, share link, or share text.
... | 32 | 441 | 171 | 612 | import asyncio
from fastapi import APIRouter, Body, Query, Request, HTTPException # 导入FastAPI组件
from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型
# 爬虫/Crawler
from crawlers.hybrid.hybrid_crawler import HybridCrawler # 导入混合爬虫
HybridCrawler = HybridCrawler() # 实例化混合爬虫
router ... | import asyncio
from fastapi import APIRouter, Body, Query, Request, HTTPException # 导入FastAPI组件
from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型
# 爬虫/Crawler
from crawlers.hybrid.hybrid_crawler import HybridCrawler # 导入混合爬虫
HybridCrawler = HybridCrawler() # 实例化混合爬虫
router ... | |
836 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/app/api/endpoints/ios_shortcut.py | 15,17 | 1,25 | get_shortcut | 17,25 | 17,25 | import os
import yaml
from fastapi import APIRouter
from app.api.models.APIResponseModel import iOS_Shortcut
# 读取上级再上级目录的配置文件
config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'config.yaml')
with open(config_path, 'r', encoding='utf-8') as file:
config = yaml... | import os
import yaml
from fastapi import APIRouter
from app.api.models.APIResponseModel import iOS_Shortcut
# 读取上级再上级目录的配置文件
config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'config.yaml')
with open(config_path, 'r', encoding='utf-8') as file:
config = yaml... | shortcut_config = config["iOS_Shortcut"]
version = shortcut_config["iOS_Shortcut_Version"]
update = shortcut_config['iOS_Shortcut_Update_Time']
link = shortcut_config['iOS_Shortcut_Link']
link_en = shortcut_config['iOS_Shortcut_Link_EN']
note = shortcut_config['iOS_Shortcut_Update_Note']
not... | shortcut_config = config["iOS_Shortcut"]
version = shortcut_config["iOS_Shortcut_Version"]
update = shortcut_config['iOS_Shortcut_Update_Time']
link = shortcut_config['iOS_Shortcut_Link']
link_en = shortcut_config['iOS_Shortcut_Link_EN']
note = shortcut_config['iOS_Shortcut_Update_Note']
not... | 28 | 201 | 173 | 374 | import os
import yaml
from fastapi import APIRouter
from app.api.models.APIResponseModel import iOS_Shortcut
# 读取上级再上级目录的配置文件
config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'config.yaml')
with open(config_path, 'r', encoding='utf-8') as file:
config = yaml... | import os
import yaml
from fastapi import APIRouter
from app.api.models.APIResponseModel import iOS_Shortcut
# 读取上级再上级目录的配置文件
config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'config.yaml')
with open(config_path, 'r', encoding='utf-8') as file:
config = yaml... | |
837 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/app/api/endpoints/tiktok_app.py | 11,14 | 1,46 | fetch_one_video | 34,46 | 14,46 | from fastapi import APIRouter, Query, Request, HTTPException # 导入FastAPI组件
from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型
from crawlers.tiktok.app.app_crawler import TikTokAPPCrawler # 导入APP爬虫
router = APIRouter()
TikTokAPPCrawler = TikTokAPPCrawler()
# 获取单个作品数据
@router.ge... | from fastapi import APIRouter, Query, Request, HTTPException # 导入FastAPI组件
from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型
from crawlers.tiktok.app.app_crawler import TikTokAPPCrawler # 导入APP爬虫
router = APIRouter()
TikTokAPPCrawler = TikTokAPPCrawler()
# 获取单个作品数据
@router.ge... | try:
data = await TikTokAPPCrawler.fetch_one_video(aweme_id)
return ResponseModel(code=200,
router=request.url.path,
data=data)
except Exception as e:
status_code = 400
detail = ErrorResponseModel(code=status_code,
... | """
# [中文]
### 用途:
- 获取单个作品数据
### 参数:
- aweme_id: 作品id
### 返回:
- 作品数据
# [English]
### Purpose:
- Get single video data
### Parameters:
- aweme_id: Video id
### Return:
- Video data
# [示例/Example]
aweme_id = "7350810998023949599"
"""
try:
... | 25 | 367 | 142 | 509 | from fastapi import APIRouter, Query, Request, HTTPException # 导入FastAPI组件
from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型
from crawlers.tiktok.app.app_crawler import TikTokAPPCrawler # 导入APP爬虫
router = APIRouter()
TikTokAPPCrawler = TikTokAPPCrawler()
# 获取单个作品数据
@router.ge... | from fastapi import APIRouter, Query, Request, HTTPException # 导入FastAPI组件
from app.api.models.APIResponseModel import ResponseModel, ErrorResponseModel # 导入响应模型
from crawlers.tiktok.app.app_crawler import TikTokAPPCrawler # 导入APP爬虫
router = APIRouter()
TikTokAPPCrawler = TikTokAPPCrawler()
# 获取单个作品数据
@router.ge... | |
838 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/app/web/views/About.py | 8,9 | 1,24 | about_pop_window | 9,24 | 9,24 | from pywebio.output import popup, put_markdown, put_html, put_text, put_link, put_image
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 关于弹窗/About pop-up
def about_pop_window():
FILL_FUNC_BODY | from pywebio.output import popup, put_markdown, put_html, put_text, put_link, put_image
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 关于弹窗/About pop-up
def about_pop_window():
FILL_FUNC_BODY | with popup(t('更多信息', 'More Information')):
put_html('<h3>👀{}</h3>'.format(t('访问记录', 'Visit Record')))
put_image('https://views.whatilearened.today/views/github/evil0ctal/TikTokDownload_PyWebIO.svg',
title='访问记录')
put_html('<hr>')
put_html('<h3>⭐Github</h3>')
... | with popup(t('更多信息', 'More Information')):
put_html('<h3>👀{}</h3>'.format(t('访问记录', 'Visit Record')))
put_image('https://views.whatilearened.today/views/github/evil0ctal/TikTokDownload_PyWebIO.svg',
title='访问记录')
put_html('<hr>')
put_html('<h3>⭐Github</h3>')
... | 23 | 86 | 361 | 447 | from pywebio.output import popup, put_markdown, put_html, put_text, put_link, put_image
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 关于弹窗/About pop-up
def about_pop_window():
FILL_FUNC_BODY | from pywebio.output import popup, put_markdown, put_html, put_text, put_link, put_image
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 关于弹窗/About pop-up
def about_pop_window():
FILL_FUNC_BODY | |
839 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/app/web/views/Document.py | 8,9 | 1,31 | api_document_pop_window | 9,31 | 9,31 | from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# API文档弹窗/API documentation pop-up
def api_document_pop_window():
FILL_FUNC_BODY | from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# API文档弹窗/API documentation pop-up
def api_document_pop_window():
FILL_FUNC_BODY | with popup(t("📑API文档", "📑API Document")):
put_markdown(t("> 介绍",
"> Introduction"))
put_markdown(t("你可以利用本项目提供的API接口来获取抖音/TikTok的数据,具体接口文档请参考下方链接。",
"You can use the API provided by this project to obtain Douyin/TikTok data. For specific API documentat... | with popup(t("📑API文档", "📑API Document")):
put_markdown(t("> 介绍",
"> Introduction"))
put_markdown(t("你可以利用本项目提供的API接口来获取抖音/TikTok的数据,具体接口文档请参考下方链接。",
"You can use the API provided by this project to obtain Douyin/TikTok data. For specific API documentat... | 145 | 86 | 503 | 589 | from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# API文档弹窗/API documentation pop-up
def api_document_pop_window():
FILL_FUNC_BODY | from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# API文档弹窗/API documentation pop-up
def api_document_pop_window():
FILL_FUNC_BODY | |
840 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/app/web/views/Downloader.py | 8,9 | 1,19 | downloader_pop_window | 9,19 | 9,19 | from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 下载器弹窗/Downloader pop-up
def downloader_pop_window():
FILL_FUNC_BODY | from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 下载器弹窗/Downloader pop-up
def downloader_pop_window():
FILL_FUNC_BODY | with popup(t("💾 下载器", "💾 Downloader")):
put_markdown(t("> 桌面端下载器", "> Desktop Downloader"))
put_markdown(t("你可以使用下面的开源项目在桌面端下载视频:",
"You can use the following open source projects to download videos on the desktop:"))
put_markdown("1. [TikTokDownload](https://github.... | with popup(t("💾 下载器", "💾 Downloader")):
put_markdown(t("> 桌面端下载器", "> Desktop Downloader"))
put_markdown(t("你可以使用下面的开源项目在桌面端下载视频:",
"You can use the following open source projects to download videos on the desktop:"))
put_markdown("1. [TikTokDownload](https://github.... | 69 | 86 | 259 | 345 | from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 下载器弹窗/Downloader pop-up
def downloader_pop_window():
FILL_FUNC_BODY | from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 下载器弹窗/Downloader pop-up
def downloader_pop_window():
FILL_FUNC_BODY | |
841 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/app/web/views/EasterEgg.py | 9,10 | 1,61 | a | 10,57 | 10,57 | import numpy as np
import time
import pyfiglet
from pywebio import start_server
from pywebio.output import put_text, clear, put_html
def a():
FILL_FUNC_BODYif __name__ == '__main__':
# A boring code is ready to run!
# 原神,启动!
start_server(a, port=80)
| import numpy as np
import time
import pyfiglet
from pywebio import start_server
from pywebio.output import put_text, clear, put_html
def a():
FILL_FUNC_BODYif __name__ == '__main__':
# A boring code is ready to run!
# 原神,启动!
start_server(a, port=80)
| H, W = 60, 80
g = np.random.choice([0, 1], size=(H, W))
def u():
n = g.copy()
for i in range(H):
for j in range(W):
t = sum([g[i, (j - 1) % W], g[i, (j + 1) % W], g[(i - 1) % H, j], g[(i + 1) % H, j],
g[(i - 1) % H, (j - 1) % W], g[(i - 1... | H, W = 60, 80
g = np.random.choice([0, 1], size=(H, W))
def u():
n = g.copy()
for i in range(H):
for j in range(W):
t = sum([g[i, (j - 1) % W], g[i, (j + 1) % W], g[(i - 1) % H, j], g[(i + 1) % H, j],
g[(i - 1) % H, (j - 1) % W], g[(i - 1... | 244 | 101 | 955 | 1,056 | import numpy as np
import time
import pyfiglet
from pywebio import start_server
from pywebio.output import put_text, clear, put_html
def a():
FILL_FUNC_BODYif __name__ == '__main__':
# A boring code is ready to run!
# 原神,启动!
start_server(a, port=80)
| import numpy as np
import time
import pyfiglet
from pywebio import start_server
from pywebio.output import put_text, clear, put_html
def a():
FILL_FUNC_BODYif __name__ == '__main__':
# A boring code is ready to run!
# 原神,启动!
start_server(a, port=80)
| |
843 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/app/web/views/Shortcuts.py | 16,17 | 1,49 | ios_pop_window | 17,49 | 17,49 | import os
import yaml
from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 读取上级再上级目录的配置文件
config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'config.yaml')
with open(confi... | import os
import yaml
from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 读取上级再上级目录的配置文件
config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'config.yaml')
with open(confi... | with popup(t("iOS快捷指令", "iOS Shortcut")):
version = config["iOS_Shortcut_Version"]
update = config['iOS_Shortcut_Update_Time']
link = config['iOS_Shortcut_Link']
link_en = config['iOS_Shortcut_Link_EN']
note = config['iOS_Shortcut_Update_Note']
note_en = config['iOS_S... | with popup(t("iOS快捷指令", "iOS Shortcut")):
version = config["iOS_Shortcut_Version"]
update = config['iOS_Shortcut_Update_Time']
link = config['iOS_Shortcut_Link']
link_en = config['iOS_Shortcut_Link_EN']
note = config['iOS_Shortcut_Update_Note']
note_en = config['iOS_S... | 276 | 205 | 987 | 1,192 | import os
import yaml
from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 读取上级再上级目录的配置文件
config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'config.yaml')
with open(confi... | import os
import yaml
from pywebio.output import popup, put_markdown, put_html, put_text, put_link
from app.web.views.ViewsUtils import ViewsUtils
t = ViewsUtils().t
# 读取上级再上级目录的配置文件
config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'config.yaml')
with open(confi... | |
844 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/app/web/views/ViewsUtils.py | 15,17 | 7,25 | clear_previous_scope | ViewsUtils | 17,21 | 17,21 | class ViewsUtils:
# 自动检测语言返回翻译/Auto detect language to return translation
@staticmethod
def t(zh: str, en: str) -> str:
return zh if 'zh' in session_info.user_language else en
# 清除前一个scope/Clear the previous scope
@staticmethod
def clear_previous_scope():
FILL_FUNC_BODY @staticmetho... | class ViewsUtils:
# 自动检测语言返回翻译/Auto detect language to return translation
@staticmethod
def t(zh: str, en: str) -> str:
return zh if 'zh' in session_info.user_language else en
# 清除前一个scope/Clear the previous scope
@staticmethod
def clear_previous_scope():
FILL_FUNC_BODY @staticmetho... | _scope = get_scope(-1)
clear(_scope)
# 解析抖音分享口令中的链接并返回列表/Parse the link in the Douyin share command and return a list
| _scope = get_scope(-1)
clear(_scope)
# 解析抖音分享口令中的链接并返回列表/Parse the link in the Douyin share command and return a list
| 17 | 208 | 56 | 264 | import re
from pywebio.output import get_scope, clear
from pywebio.session import info as session_info
class ViewsUtils:
# 自动检测语言返回翻译/Auto detect language to return translation
@staticmethod
def t(zh: str, en: str) -> str:
return zh if 'zh' in session_info.user_language else en
# 清除前一个scope... | import re
from pywebio.output import get_scope, clear
from pywebio.session import info as session_info
class ViewsUtils:
# 自动检测语言返回翻译/Auto detect language to return translation
@staticmethod
def t(zh: str, en: str) -> str:
return zh if 'zh' in session_info.user_language else en
# 清除前一个scope... |
847 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/douyin/web/utils.py | 371,373 | 365,466 | get_aweme_id | AwemeIdFetcher | 382,438 | 373,438 | class AwemeIdFetcher:
# 预编译正则表达式
_DOUYIN_VIDEO_URL_PATTERN = re.compile(r"video/([^/?]*)")
_DOUYIN_NOTE_URL_PATTERN = re.compile(r"note/([^/?]*)")
_DOUYIN_DISCOVER_URL_PATTERN = re.compile(r"modal_id=([0-9]+)")
@classmethod
async def get_aweme_id(cls, url: str) -> str:
FILL_FUNC_BODY @classm... | class AwemeIdFetcher:
# 预编译正则表达式
_DOUYIN_VIDEO_URL_PATTERN = re.compile(r"video/([^/?]*)")
_DOUYIN_NOTE_URL_PATTERN = re.compile(r"note/([^/?]*)")
_DOUYIN_DISCOVER_URL_PATTERN = re.compile(r"modal_id=([0-9]+)")
@classmethod
async def get_aweme_id(cls, url: str) -> str:
"""
从单个ur... |
if not isinstance(url, str):
raise TypeError("参数必须是字符串类型")
# 提取有效URL
url = extract_valid_urls(url)
if url is None:
raise (
APINotFoundError("输入的URL不合法。类名:{0}".format(cls.__name__))
)
# 重定向到完整链接
transport = httpx.Asyn... | """
从单个url中获取aweme_id (Get aweme_id from a single url)
Args:
url (str): 输入的url (Input url)
Returns:
str: 匹配到的aweme_id (Matched aweme_id)。
"""
if not isinstance(url, str):
raise TypeError("参数必须是字符串类型")
# 提取有效URL
url =... | 132 | 509 | 716 | 1,225 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
848 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/douyin/web/utils.py | 246,248 | 236,266 | xb_model_2_endpoint | BogusManager | 248,266 | 248,266 | class BogusManager:
@classmethod
def xb_str_2_endpoint(cls, endpoint: str, user_agent: str) -> str:
try:
final_endpoint = XB(user_agent).getXBogus(endpoint)
except Exception as e:
raise RuntimeError("生成X-Bogus失败: {0})".format(e))
return final_endpoint[0]
@cl... | class BogusManager:
@classmethod
def xb_str_2_endpoint(cls, endpoint: str, user_agent: str) -> str:
try:
final_endpoint = XB(user_agent).getXBogus(endpoint)
except Exception as e:
raise RuntimeError("生成X-Bogus失败: {0})".format(e))
return final_endpoint[0]
@cl... | if not isinstance(params, dict):
raise TypeError("参数必须是字典类型")
param_str = "&".join([f"{k}={v}" for k, v in params.items()])
try:
xb_value = XB(user_agent).getXBogus(param_str)
except Exception as e:
raise RuntimeError("生成X-Bogus失败: {0})".format(e))
... | if not isinstance(params, dict):
raise TypeError("参数必须是字典类型")
param_str = "&".join([f"{k}={v}" for k, v in params.items()])
try:
xb_value = XB(user_agent).getXBogus(param_str)
except Exception as e:
raise RuntimeError("生成X-Bogus失败: {0})".format(e))
... | 48 | 161 | 227 | 388 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
849 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/douyin/web/utils.py | 468,470 | 466,473 | get_mix_id | MixIdFetcher | 470,473 | 470,473 | class MixIdFetcher:
# 获取方法同AwemeIdFetcher
@classmethod
async def get_mix_id(cls, url: str) -> str:
FILL_FUNC_BODY | class MixIdFetcher:
# 获取方法同AwemeIdFetcher
@classmethod
async def get_mix_id(cls, url: str) -> str:
FILL_FUNC_BODY | return
| return
| 1 | 57 | 8 | 65 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
850 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/douyin/web/utils.py | 271,273 | 266,365 | get_sec_user_id | SecUserIdFetcher | 282,337 | 273,337 | class SecUserIdFetcher:
# 预编译正则表达式
_DOUYIN_URL_PATTERN = re.compile(r"user/([^/?]*)")
_REDIRECT_URL_PATTERN = re.compile(r"sec_uid=([^&]*)")
@classmethod
async def get_sec_user_id(cls, url: str) -> str:
FILL_FUNC_BODY @classmethod
async def get_all_sec_user_id(cls, urls: list) -> list:
... | class SecUserIdFetcher:
# 预编译正则表达式
_DOUYIN_URL_PATTERN = re.compile(r"user/([^/?]*)")
_REDIRECT_URL_PATTERN = re.compile(r"sec_uid=([^&]*)")
@classmethod
async def get_sec_user_id(cls, url: str) -> str:
"""
从单个url中获取sec_user_id (Get sec_user_id from a single url)
Args:
... |
if not isinstance(url, str):
raise TypeError("参数必须是字符串类型")
# 提取有效URL
url = extract_valid_urls(url)
if url is None:
raise (
APINotFoundError("输入的URL不合法。类名:{0}".format(cls.__name__))
)
pattern = (
cls._REDIRECT_URL... | """
从单个url中获取sec_user_id (Get sec_user_id from a single url)
Args:
url (str): 输入的url (Input url)
Returns:
str: 匹配到的sec_user_id (Matched sec_user_id)。
"""
if not isinstance(url, str):
raise TypeError("参数必须是字符串类型")
# 提取有效URL
... | 122 | 454 | 699 | 1,153 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
851 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/douyin/web/utils.py | 158,160 | 78,200 | gen_ttwid | TokenManager | 164,200 | 160,200 | class TokenManager:
douyin_manager = config.get("TokenManager").get("douyin")
token_conf = douyin_manager.get("msToken", None)
ttwid_conf = douyin_manager.get("ttwid", None)
proxies_conf = douyin_manager.get("proxies", None)
proxies = {
"http://": proxies_conf.get("http", None),
"htt... | class TokenManager:
douyin_manager = config.get("TokenManager").get("douyin")
token_conf = douyin_manager.get("msToken", None)
ttwid_conf = douyin_manager.get("ttwid", None)
proxies_conf = douyin_manager.get("proxies", None)
proxies = {
"http://": proxies_conf.get("http", None),
"htt... |
transport = httpx.HTTPTransport(retries=5)
with httpx.Client(transport=transport) as client:
try:
response = client.post(
cls.ttwid_conf["url"], content=cls.ttwid_conf["data"]
)
response.raise_for_status()
... | """
生成请求必带的ttwid
(Generate the essential ttwid for requests)
"""
transport = httpx.HTTPTransport(retries=5)
with httpx.Client(transport=transport) as client:
try:
response = client.post(
cls.ttwid_conf["url"], content=cls.t... | 88 | 1,016 | 475 | 1,491 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
852 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/douyin/web/utils.py | 201,203 | 200,236 | gen_verify_fp | VerifyFpManager | 206,231 | 203,231 | class VerifyFpManager:
@classmethod
def gen_verify_fp(cls) -> str:
FILL_FUNC_BODY @classmethod
def gen_s_v_web_id(cls) -> str:
return cls.gen_verify_fp()
| class VerifyFpManager:
@classmethod
def gen_verify_fp(cls) -> str:
"""
生成verifyFp 与 s_v_web_id (Generate verifyFp)
"""
FILL_FUNC_BODY @classmethod
def gen_s_v_web_id(cls) -> str:
return cls.gen_verify_fp()
| base_str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
t = len(base_str)
milliseconds = int(round(time.time() * 1000))
base36 = ""
while milliseconds > 0:
remainder = milliseconds % 36
if remainder < 10:
base36 = str(re... | """
生成verifyFp 与 s_v_web_id (Generate verifyFp)
"""
base_str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
t = len(base_str)
milliseconds = int(round(time.time() * 1000))
base36 = ""
while milliseconds > 0:
remainder = mill... | 103 | 109 | 341 | 450 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
853 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/douyin/web/utils.py | 482,484 | 473,573 | get_webcast_id | WebCastIdFetcher | 493,545 | 484,545 | class WebCastIdFetcher:
# 预编译正则表达式
_DOUYIN_LIVE_URL_PATTERN = re.compile(r"live/([^/?]*)")
# https://live.douyin.com/766545142636?cover_type=0&enter_from_merge=web_live&enter_method=web_card&game_name=&is_recommend=1&live_type=game&more_detail=&request_id=20231110224012D47CD00C18B4AE4BFF9B&room_id=729982864... | class WebCastIdFetcher:
# 预编译正则表达式
_DOUYIN_LIVE_URL_PATTERN = re.compile(r"live/([^/?]*)")
# https://live.douyin.com/766545142636?cover_type=0&enter_from_merge=web_live&enter_method=web_card&game_name=&is_recommend=1&live_type=game&more_detail=&request_id=20231110224012D47CD00C18B4AE4BFF9B&room_id=729982864... |
if not isinstance(url, str):
raise TypeError("参数必须是字符串类型")
# 提取有效URL
url = extract_valid_urls(url)
if url is None:
raise (
APINotFoundError("输入的URL不合法。类名:{0}".format(cls.__name__))
)
try:
# 重定向到完整链接
tr... | """
从单个url中获取webcast_id (Get webcast_id from a single url)
Args:
url (str): 输入的url (Input url)
Returns:
str: 匹配到的webcast_id (Matched webcast_id)。
"""
if not isinstance(url, str):
raise TypeError("参数必须是字符串类型")
# 提取有效URL
... | 109 | 1,026 | 669 | 1,695 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
856 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/tiktok/app/app_crawler.py | 62,63 | 59,104 | get_tiktok_headers | TikTokAPPCrawler | 63,74 | 63,74 | class TikTokAPPCrawler:
# 从配置文件中获取TikTok的请求头
async def get_tiktok_headers(self):
FILL_FUNC_BODY """-------------------------------------------------------handler接口列表-------------------------------------------------------"""
# 获取单个作品数据
async def fetch_one_video(self, aweme_id: str):
# 获取TikT... | class TikTokAPPCrawler:
# 从配置文件中获取TikTok的请求头
async def get_tiktok_headers(self):
FILL_FUNC_BODY """-------------------------------------------------------handler接口列表-------------------------------------------------------"""
# 获取单个作品数据
async def fetch_one_video(self, aweme_id: str):
# 获取TikT... | tiktok_config = config["TokenManager"]["tiktok"]
kwargs = {
"headers": {
"User-Agent": tiktok_config["headers"]["User-Agent"],
"Referer": tiktok_config["headers"]["Referer"],
"Cookie": tiktok_config["headers"]["Cookie"],
},
... | tiktok_config = config["TokenManager"]["tiktok"]
kwargs = {
"headers": {
"User-Agent": tiktok_config["headers"]["User-Agent"],
"Referer": tiktok_config["headers"]["Referer"],
"Cookie": tiktok_config["headers"]["Cookie"],
},
... | 23 | 400 | 129 | 529 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
858 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/tiktok/web/utils.py | 441,443 | 433,530 | get_aweme_id | AwemeIdFetcher | 450,501 | 443,501 | class AwemeIdFetcher:
# https://www.tiktok.com/@scarlettjonesuk/video/7255716763118226715
# https://www.tiktok.com/@scarlettjonesuk/video/7255716763118226715?is_from_webapp=1&sender_device=pc&web_id=7306060721837852167
# 预编译正则表达式
_TIKTOK_AWEMEID_PARREN = re.compile(r"video/(\d*)")
_TIKTOK_NOTFOUND_... | class AwemeIdFetcher:
# https://www.tiktok.com/@scarlettjonesuk/video/7255716763118226715
# https://www.tiktok.com/@scarlettjonesuk/video/7255716763118226715?is_from_webapp=1&sender_device=pc&web_id=7306060721837852167
# 预编译正则表达式
_TIKTOK_AWEMEID_PARREN = re.compile(r"video/(\d*)")
_TIKTOK_NOTFOUND_... |
# 进行参数检查
if not isinstance(url, str):
raise TypeError("输入参数必须是字符串")
# 提取有效URL
url = extract_valid_urls(url)
if url is None:
raise (
APINotFoundError("输入的URL不合法。类名:{0}".format(cls.__name__))
)
transport = httpx.AsyncH... | """
获取TikTok作品aweme_id
Args:
url: 作品链接
Return:
aweme_id: 作品唯一标识
"""
# 进行参数检查
if not isinstance(url, str):
raise TypeError("输入参数必须是字符串")
# 提取有效URL
url = extract_valid_urls(url)
if url is None:
... | 105 | 558 | 610 | 1,168 | import os
import re
import json
import yaml
import httpx
import asyncio
from typing import Union
from pathlib import Path
from crawlers.utils.logger import logger
from crawlers.douyin.web.xbogus import XBogus as XB
from crawlers.utils.utils import (
gen_random_str,
get_timestamp,
extract_valid_urls,
s... | import os
import re
import json
import yaml
import httpx
import asyncio
from typing import Union
from pathlib import Path
from crawlers.utils.logger import logger
from crawlers.douyin.web.xbogus import XBogus as XB
from crawlers.utils.utils import (
gen_random_str,
get_timestamp,
extract_valid_urls,
s... |
859 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/tiktok/web/utils.py | 220,227 | 206,246 | model_2_endpoint | BogusManager | 227,246 | 227,246 | class BogusManager:
@classmethod
def xb_str_2_endpoint(
cls,
user_agent: str,
endpoint: str,
) -> str:
try:
final_endpoint = XB(user_agent).getXBogus(endpoint)
except Exception as e:
raise RuntimeError("生成X-Bogus失败: {0})".format(e))... | class BogusManager:
@classmethod
def xb_str_2_endpoint(
cls,
user_agent: str,
endpoint: str,
) -> str:
try:
final_endpoint = XB(user_agent).getXBogus(endpoint)
except Exception as e:
raise RuntimeError("生成X-Bogus失败: {0})".format(e))... | # 检查params是否是一个字典 (Check if params is a dict)
if not isinstance(params, dict):
raise TypeError("参数必须是字典类型")
param_str = "&".join([f"{k}={v}" for k, v in params.items()])
try:
xb_value = XB(user_agent).getXBogus(param_str)
except Exception as e:
... | # 检查params是否是一个字典 (Check if params is a dict)
if not isinstance(params, dict):
raise TypeError("参数必须是字典类型")
param_str = "&".join([f"{k}={v}" for k, v in params.items()])
try:
xb_value = XB(user_agent).getXBogus(param_str)
except Exception as e:
... | 56 | 180 | 246 | 426 | import os
import re
import json
import yaml
import httpx
import asyncio
from typing import Union
from pathlib import Path
from crawlers.utils.logger import logger
from crawlers.douyin.web.xbogus import XBogus as XB
from crawlers.utils.utils import (
gen_random_str,
get_timestamp,
extract_valid_urls,
s... | import os
import re
import json
import yaml
import httpx
import asyncio
from typing import Union
from pathlib import Path
from crawlers.utils.logger import logger
from crawlers.douyin.web.xbogus import XBogus as XB
from crawlers.utils.utils import (
gen_random_str,
get_timestamp,
extract_valid_urls,
s... |
860 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/tiktok/web/utils.py | 404,406 | 246,433 | get_all_uniqueid | SecUserIdFetcher | 415,433 | 406,433 | class SecUserIdFetcher:
# 预编译正则表达式
_TIKTOK_SECUID_PARREN = re.compile(
r"<script id=\"__UNIVERSAL_DATA_FOR_REHYDRATION__\" type=\"application/json\">(.*?)</script>"
)
_TIKTOK_UNIQUEID_PARREN = re.compile(r"/@([^/?]*)")
_TIKTOK_NOTFOUND_PARREN = re.compile(r"notfound")
@classmethod
a... | class SecUserIdFetcher:
# 预编译正则表达式
_TIKTOK_SECUID_PARREN = re.compile(
r"<script id=\"__UNIVERSAL_DATA_FOR_REHYDRATION__\" type=\"application/json\">(.*?)</script>"
)
_TIKTOK_UNIQUEID_PARREN = re.compile(r"/@([^/?]*)")
_TIKTOK_NOTFOUND_PARREN = re.compile(r"notfound")
@classmethod
a... |
if not isinstance(urls, list):
raise TypeError("参数必须是列表类型")
# 提取有效URL
urls = extract_valid_urls(urls)
if urls == []:
raise (
APINotFoundError(
"输入的URL List不合法。类名:{0}".format(cls.__name__)
)
)
... | """
获取列表unique_id列表 (Get list sec_user_id list)
Args:
urls: list: 用户url列表 (User url list)
Return:
unique_ids: list: 用户unique_id列表 (User unique_id list)
"""
if not isinstance(urls, list):
raise TypeError("参数必须是列表类型")
# 提取有效UR... | 32 | 1,840 | 157 | 1,997 | import os
import re
import json
import yaml
import httpx
import asyncio
from typing import Union
from pathlib import Path
from crawlers.utils.logger import logger
from crawlers.douyin.web.xbogus import XBogus as XB
from crawlers.utils.utils import (
gen_random_str,
get_timestamp,
extract_valid_urls,
s... | import os
import re
import json
import yaml
import httpx
import asyncio
from typing import Union
from pathlib import Path
from crawlers.utils.logger import logger
from crawlers.douyin.web.xbogus import XBogus as XB
from crawlers.utils.utils import (
gen_random_str,
get_timestamp,
extract_valid_urls,
s... |
863 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/api_exceptions.py | 55,56 | 52,59 | display_error | APIConnectionError | 56,59 | 56,59 | class APIConnectionError(APIError):
"""当与API的连接出现问题时抛出"""
def display_error(self):
FILL_FUNC_BODY | class APIConnectionError(APIError):
"""当与API的连接出现问题时抛出"""
def display_error(self):
FILL_FUNC_BODY | return f"API Connection Error: {self.args[0]}."
| return f"API Connection Error: {self.args[0]}."
| 5 | 43 | 22 | 65 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
864 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/api_exceptions.py | 45,46 | 36,52 | display_error | APIError | 47,52 | 46,52 | class APIError(Exception):
"""基本API异常类,其他API异常都会继承这个类"""
def __init__(self, status_code=None):
self.status_code = status_code
print(
"程序出现异常,请检查错误信息。"
)
def display_error(self):
FILL_FUNC_BODY | class APIError(Exception):
"""基本API异常类,其他API异常都会继承这个类"""
def __init__(self, status_code=None):
self.status_code = status_code
print(
"程序出现异常,请检查错误信息。"
)
def display_error(self):
"""显示错误信息和状态码(如果有的话)"""
FILL_FUNC_BODY | return f"Error: {self.args[0]}." + (
f" Status Code: {self.status_code}." if self.status_code else ""
)
| """显示错误信息和状态码(如果有的话)"""
return f"Error: {self.args[0]}." + (
f" Status Code: {self.status_code}." if self.status_code else ""
)
| 14 | 107 | 50 | 157 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
865 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/api_exceptions.py | 69,70 | 66,73 | display_error | APINotFoundError | 70,73 | 70,73 | class APINotFoundError(APIError):
"""当API端点不存在时抛出"""
def display_error(self):
FILL_FUNC_BODY | class APINotFoundError(APIError):
"""当API端点不存在时抛出"""
def display_error(self):
FILL_FUNC_BODY | return f"API Not Found Error: {self.args[0]}."
| return f"API Not Found Error: {self.args[0]}."
| 6 | 44 | 23 | 67 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
866 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/api_exceptions.py | 83,84 | 80,87 | display_error | APIRateLimitError | 84,87 | 84,87 | class APIRateLimitError(APIError):
"""当达到API的请求速率限制时抛出"""
def display_error(self):
FILL_FUNC_BODY | class APIRateLimitError(APIError):
"""当达到API的请求速率限制时抛出"""
def display_error(self):
FILL_FUNC_BODY | return f"API Rate Limit Error: {self.args[0]}."
| return f"API Rate Limit Error: {self.args[0]}."
| 6 | 45 | 24 | 69 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
867 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/api_exceptions.py | 76,77 | 73,80 | display_error | APIResponseError | 77,80 | 77,80 | class APIResponseError(APIError):
"""当API返回的响应与预期不符时抛出"""
def display_error(self):
FILL_FUNC_BODY | class APIResponseError(APIError):
"""当API返回的响应与预期不符时抛出"""
def display_error(self):
FILL_FUNC_BODY | return f"API Response Error: {self.args[0]}."
| return f"API Response Error: {self.args[0]}."
| 5 | 47 | 22 | 69 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
868 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/api_exceptions.py | 104,105 | 101,106 | display_error | APIRetryExhaustedError | 105,106 | 105,106 | class APIRetryExhaustedError(APIError):
"""当API请求重试次数用尽时抛出"""
def display_error(self):
FILL_FUNC_BODY | class APIRetryExhaustedError(APIError):
"""当API请求重试次数用尽时抛出"""
def display_error(self):
FILL_FUNC_BODY | return f"API Retry Exhausted Error: {self.args[0]}."
| return f"API Retry Exhausted Error: {self.args[0]}."
| 6 | 49 | 22 | 71 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
869 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/api_exceptions.py | 90,91 | 87,94 | display_error | APITimeoutError | 91,94 | 91,94 | class APITimeoutError(APIError):
"""当API请求超时时抛出"""
def display_error(self):
FILL_FUNC_BODY | class APITimeoutError(APIError):
"""当API请求超时时抛出"""
def display_error(self):
FILL_FUNC_BODY | return f"API Timeout Error: {self.args[0]}."
| return f"API Timeout Error: {self.args[0]}."
| 5 | 43 | 23 | 66 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
870 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/api_exceptions.py | 97,98 | 94,101 | display_error | APIUnauthorizedError | 98,101 | 98,101 | class APIUnauthorizedError(APIError):
"""当API请求由于授权失败而被拒绝时抛出"""
def display_error(self):
FILL_FUNC_BODY | class APIUnauthorizedError(APIError):
"""当API请求由于授权失败而被拒绝时抛出"""
def display_error(self):
FILL_FUNC_BODY | return f"API Unauthorized Error: {self.args[0]}."
| return f"API Unauthorized Error: {self.args[0]}."
| 5 | 48 | 24 | 72 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
871 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/api_exceptions.py | 62,63 | 59,66 | display_error | APIUnavailableError | 63,66 | 63,66 | class APIUnavailableError(APIError):
"""当API服务不可用时抛出,例如维护或超时"""
def display_error(self):
FILL_FUNC_BODY | class APIUnavailableError(APIError):
"""当API服务不可用时抛出,例如维护或超时"""
def display_error(self):
FILL_FUNC_BODY | return f"API Unavailable Error: {self.args[0]}."
| return f"API Unavailable Error: {self.args[0]}."
| 5 | 48 | 23 | 71 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
872 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/logger.py | 147,148 | 1,170 | log_setup | 148,169 | 148,169 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | logger = logging.getLogger("Douyin_TikTok_Download_API_Crawlers")
if logger.hasHandlers():
# logger已经被设置,不做任何操作
return logger
# 创建临时的日志目录
temp_log_dir = Path("./logs")
temp_log_dir.mkdir(exist_ok=True)
# 初始化日志管理器
log_manager = LogManager()
log_manager.setup_logging(
... | logger = logging.getLogger("Douyin_TikTok_Download_API_Crawlers")
if logger.hasHandlers():
# logger已经被设置,不做任何操作
return logger
# 创建临时的日志目录
temp_log_dir = Path("./logs")
temp_log_dir.mkdir(exist_ok=True)
# 初始化日志管理器
log_manager = LogManager()
log_manager.setup_logging(
... | 30 | 1,683 | 216 | 1,899 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | |
873 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/logger.py | 121,122 | 77,147 | clean_logs | LogManager | 123,139 | 122,139 | class LogManager(metaclass=Singleton):
def __init__(self):
if getattr(self, "_initialized", False): # 防止重复初始化
return
self.logger = logging.getLogger("Douyin_TikTok_Download_API_Crawlers")
self.logger.setLevel(logging.INFO)
self.log_dir = None
self._initialized =... | class LogManager(metaclass=Singleton):
def __init__(self):
if getattr(self, "_initialized", False): # 防止重复初始化
return
self.logger = logging.getLogger("Douyin_TikTok_Download_API_Crawlers")
self.logger.setLevel(logging.INFO)
self.log_dir = None
self._initialized =... | if not self.log_dir:
return
# self.shutdown()
all_logs = sorted(self.log_dir.glob("*.log"))
if keep_last_n == 0:
files_to_delete = all_logs
else:
files_to_delete = all_logs[:-keep_last_n]
for log_file in files_to_delete:
try... | """保留最近的n个日志文件并删除其他文件"""
if not self.log_dir:
return
# self.shutdown()
all_logs = sorted(self.log_dir.glob("*.log"))
if keep_last_n == 0:
files_to_delete = all_logs
else:
files_to_delete = all_logs[:-keep_last_n]
for log_file in... | 33 | 630 | 173 | 803 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
874 | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API | /home/hieuvd/dung_repo/raw/stars_01/Evil0ctal_Douyin_TikTok_Download_API/Douyin_TikTok_Download_API/crawlers/utils/logger.py | 65,67 | 46,77 | reset_instance | Singleton | 71,77 | 67,77 | class Singleton(type):
_instances = {} # 存储实例的字典
_lock: threading.Lock = threading.Lock() # 线程锁
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __call__(cls, *args, **kwargs):
"""
重写默认的类实例化方法。当尝试创建类的一个新实例时,此方法将被调用。
如果已经有一个与参数匹配的实例存在,则返回该实例;否... | class Singleton(type):
_instances = {} # 存储实例的字典
_lock: threading.Lock = threading.Lock() # 线程锁
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __call__(cls, *args, **kwargs):
"""
重写默认的类实例化方法。当尝试创建类的一个新实例时,此方法将被调用。
如果已经有一个与参数匹配的实例存在,则返回该实例;否... | key = (cls, args, frozenset(kwargs.items()))
with cls._lock:
if key in cls._instances:
del cls._instances[key]
| """
重置指定参数的实例。这只是从 _instances 字典中删除实例的引用,
并不真正删除该实例。如果其他地方仍引用该实例,它仍然存在且可用。
"""
key = (cls, args, frozenset(kwargs.items()))
with cls._lock:
if key in cls._instances:
del cls._instances[key]
| 13 | 324 | 55 | 379 | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | # ==============================================================================
# Copyright (C) 2021 Evil0ctal
#
# This file is part of the Douyin_TikTok_Download_API project.
#
# This project is licensed under the Apache License 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
877 | /home/hieuvd/dung_repo/raw/stars_01/FujiwaraChoki_MoneyPrinter/MoneyPrinter | /home/hieuvd/dung_repo/raw/stars_01/FujiwaraChoki_MoneyPrinter/MoneyPrinter/Backend/search.py | 6,7 | 1,67 | search_for_stock_videos | 17,67 | 7,67 | import requests
from typing import List
from termcolor import colored
def search_for_stock_videos(query: str, api_key: str, it: int, min_dur: int) -> List[str]:
FILL_FUNC_BODY | import requests
from typing import List
from termcolor import colored
def search_for_stock_videos(query: str, api_key: str, it: int, min_dur: int) -> List[str]:
"""
Searches for stock videos based on a query.
Args:
query (str): The query to search for.
api_key (str): The API key to use.
... |
# Build headers
headers = {
"Authorization": api_key
}
# Build URL
qurl = f"https://api.pexels.com/videos/search?query={query}&per_page={it}"
# Send the request
r = requests.get(qurl, headers=headers)
# Parse the response
response = r.json()
# Parse each video
... | """
Searches for stock videos based on a query.
Args:
query (str): The query to search for.
api_key (str): The API key to use.
Returns:
List[str]: A list of stock videos.
"""
# Build headers
headers = {
"Authorization": api_key
}
# Build URL
... | 165 | 132 | 510 | 642 | import requests
from typing import List
from termcolor import colored
def search_for_stock_videos(query: str, api_key: str, it: int, min_dur: int) -> List[str]:
FILL_FUNC_BODY | import requests
from typing import List
from termcolor import colored
def search_for_stock_videos(query: str, api_key: str, it: int, min_dur: int) -> List[str]:
"""
Searches for stock videos based on a query.
Args:
query (str): The query to search for.
api_key (str): The API key to use.
... | |
878 | /home/hieuvd/dung_repo/raw/stars_01/FujiwaraChoki_MoneyPrinter/MoneyPrinter | /home/hieuvd/dung_repo/raw/stars_01/FujiwaraChoki_MoneyPrinter/MoneyPrinter/Backend/utils.py | 96,97 | 1,119 | check_env_vars | 106,119 | 97,119 | import os
import sys
import json
import random
import logging
import zipfile
import requests
from termcolor import colored
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def clean_dir(path: str) -> None:
"""
Removes every file in a directory.
Args:
... | import os
import sys
import json
import random
import logging
import zipfile
import requests
from termcolor import colored
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def clean_dir(path: str) -> None:
"""
Removes every file in a directory.
Args:
... | try:
required_vars = ["PEXELS_API_KEY", "TIKTOK_SESSION_ID", "IMAGEMAGICK_BINARY"]
missing_vars = [var + os.getenv(var) for var in required_vars if os.getenv(var) is None or (len(os.getenv(var)) == 0)]
if missing_vars:
missing_vars_str = ", ".join(missing_vars)
lo... | """
Checks if the necessary environment variables are set.
Returns:
None
Raises:
SystemExit: If any required environment variables are missing.
"""
try:
required_vars = ["PEXELS_API_KEY", "TIKTOK_SESSION_ID", "IMAGEMAGICK_BINARY"]
missing_vars = [var + os.getenv... | 74 | 834 | 248 | 1,082 | import os
import sys
import json
import random
import logging
import zipfile
import requests
from termcolor import colored
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def clean_dir(path: str) -> None:
"""
Removes every file in a directory.
Args:
... | import os
import sys
import json
import random
import logging
import zipfile
import requests
from termcolor import colored
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def clean_dir(path: str) -> None:
"""
Removes every file in a directory.
Args:
... | |
880 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/Claude.py | 16,17 | 8,105 | _get_claude_style_history | Claude_Client | 17,73 | 17,73 | class Claude_Client(BaseLLMModel):
def __init__(self, model_name, api_secret) -> None:
super().__init__(model_name=model_name)
self.api_secret = api_secret
if None in [self.api_secret]:
raise Exception("请在配置文件或者环境变量中设置Claude的API Secret")
self.claude_client = Anthropic(api... | class Claude_Client(BaseLLMModel):
def __init__(self, model_name, api_secret) -> None:
super().__init__(model_name=model_name)
self.api_secret = api_secret
if None in [self.api_secret]:
raise Exception("请在配置文件或者环境变量中设置Claude的API Secret")
self.claude_client = Anthropic(api... | history = []
image_buffer = []
image_count = 0
for message in self.history:
if message["role"] == "user":
content = []
if image_buffer:
if image_count == 1:
content.append(
... | history = []
image_buffer = []
image_count = 0
for message in self.history:
if message["role"] == "user":
content = []
if image_buffer:
if image_count == 1:
content.append(
... | 151 | 472 | 607 | 1,079 | from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT
from ..presets import *
from ..utils import *
from .base_model import BaseLLMModel
class Claude_Client(BaseLLMModel):
def __init__(self, model_name, api_secret) -> None:
super().__init__(model_name=model_name)
self.api_secret = api_secret
... | from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT
from ..presets import *
from ..utils import *
from .base_model import BaseLLMModel
class Claude_Client(BaseLLMModel):
def __init__(self, model_name, api_secret) -> None:
super().__init__(model_name=model_name)
self.api_secret = api_secret
... |
881 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/DALLE3.py | 23,24 | 8,67 | get_answer_at_once | OpenAI_DALLE3_Client | 24,62 | 24,62 | class OpenAI_DALLE3_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, config={"api_key": api_key})
if self.api_host is not None:
self.chat_completion_url, self.images_completion_url, self.openai_ap... | class OpenAI_DALLE3_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, config={"api_key": api_key})
if self.api_host is not None:
self.chat_completion_url, self.images_completion_url, self.openai_ap... | prompt = self._get_dalle3_prompt()
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
payload = {
"model": self.model_name,
"prompt": prompt,
"n": 1,
"size": "1024x1024",
... | prompt = self._get_dalle3_prompt()
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
payload = {
"model": self.model_name,
"prompt": prompt,
"n": 1,
"size": "1024x1024",
... | 95 | 429 | 465 | 894 | import logging
from .base_model import BaseLLMModel
from .. import shared
import requests
from ..presets import *
from ..config import retrieve_proxy, sensitive_id
class OpenAI_DALLE3_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name... | import logging
from .base_model import BaseLLMModel
from .. import shared
import requests
from ..presets import *
from ..config import retrieve_proxy, sensitive_id
class OpenAI_DALLE3_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name... |
882 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/GoogleGemini.py | 27,28 | 18,81 | _get_gemini_style_input | GoogleGeminiClient | 28,38 | 28,38 | class GoogleGeminiClient(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, config={"api_key": api_key})
if "vision" in model_name.lower():
self.multimodal = True
else:
self.multimodal ... | class GoogleGeminiClient(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, config={"api_key": api_key})
if "vision" in model_name.lower():
self.multimodal = True
else:
self.multimodal ... | self.history.extend([{"role": "image", "content": i} for i in self.image_paths])
self.image_paths = []
messages = []
for item in self.history:
if item["role"] == "image":
messages.append(PIL.Image.open(item["content"]))
else:
messag... | self.history.extend([{"role": "image", "content": i} for i in self.image_paths])
self.image_paths = []
messages = []
for item in self.history:
if item["role"] == "image":
messages.append(PIL.Image.open(item["content"]))
else:
messag... | 27 | 627 | 110 | 737 | import json
import logging
import textwrap
import uuid
import google.generativeai as genai
import gradio as gr
import PIL
import requests
from modules.presets import i18n
from ..index_func import construct_index
from ..utils import count_token
from .base_model import BaseLLMModel
class GoogleGeminiClient(BaseLLMMo... | import json
import logging
import textwrap
import uuid
import google.generativeai as genai
import gradio as gr
import PIL
import requests
from modules.presets import i18n
from ..index_func import construct_index
from ..utils import count_token
from .base_model import BaseLLMModel
class GoogleGeminiClient(BaseLLMMo... |
883 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/GooglePaLM.py | 18,19 | 5,29 | get_answer_at_once | Google_PaLM_Client | 19,29 | 19,29 | class Google_PaLM_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, config={"api_key": api_key})
def _get_palm_style_input(self):
new_history = []
for item in self.history:
if item["ro... | class Google_PaLM_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, config={"api_key": api_key})
def _get_palm_style_input(self):
new_history = []
for item in self.history:
if item["ro... | palm.configure(api_key=self.api_key)
messages = self._get_palm_style_input()
response = palm.chat(context=self.system_prompt, messages=messages,
temperature=self.temperature, top_p=self.top_p, model=self.model_name)
if response.last is not None:
r... | palm.configure(api_key=self.api_key)
messages = self._get_palm_style_input()
response = palm.chat(context=self.system_prompt, messages=messages,
temperature=self.temperature, top_p=self.top_p, model=self.model_name)
if response.last is not None:
r... | 36 | 193 | 172 | 365 | from .base_model import BaseLLMModel
import google.generativeai as palm
class Google_PaLM_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, config={"api_key": api_key})
def _get_palm_style_input(self):
... | from .base_model import BaseLLMModel
import google.generativeai as palm
class Google_PaLM_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, config={"api_key": api_key})
def _get_palm_style_input(self):
... |
884 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/Ollama.py | 26,27 | 15,55 | update_token_limit | OllamaClient | 27,43 | 27,43 | class OllamaClient(BaseLLMModel):
def __init__(self, model_name, user_name="", ollama_host="", backend_model="") -> None:
super().__init__(model_name=model_name, user=user_name)
self.backend_model = backend_model
self.ollama_host = ollama_host
self.update_token_limit()
def get_m... | class OllamaClient(BaseLLMModel):
def __init__(self, model_name, user_name="", ollama_host="", backend_model="") -> None:
super().__init__(model_name=model_name, user=user_name)
self.backend_model = backend_model
self.ollama_host = ollama_host
self.update_token_limit()
def get_m... | lower_model_name = self.backend_model.lower()
if "mistral" in lower_model_name:
self.token_upper_limit = 8*1024
elif "gemma" in lower_model_name:
self.token_upper_limit = 8*1024
elif "codellama" in lower_model_name:
self.token_upper_limit = 4*1024
... | lower_model_name = self.backend_model.lower()
if "mistral" in lower_model_name:
self.token_upper_limit = 8*1024
elif "gemma" in lower_model_name:
self.token_upper_limit = 8*1024
elif "codellama" in lower_model_name:
self.token_upper_limit = 4*1024
... | 52 | 316 | 253 | 569 | import json
import logging
import textwrap
import uuid
from ollama import Client
from modules.presets import i18n
from ..index_func import construct_index
from ..utils import count_token
from .base_model import BaseLLMModel
class OllamaClient(BaseLLMModel):
def __init__(self, model_name, user_name="", ollama_h... | import json
import logging
import textwrap
import uuid
from ollama import Client
from modules.presets import i18n
from ..index_func import construct_index
from ..utils import count_token
from .base_model import BaseLLMModel
class OllamaClient(BaseLLMModel):
def __init__(self, model_name, user_name="", ollama_h... |
885 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/OpenAIInstruct.py | 16,18 | 9,27 | get_answer_at_once | OpenAI_Instruct_Client | 18,27 | 18,27 | class OpenAI_Instruct_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, config={"api_key": api_key})
def _get_instruct_style_input(self):
return "".join([item["content"] for item in self.history])
@s... | class OpenAI_Instruct_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, config={"api_key": api_key})
def _get_instruct_style_input(self):
return "".join([item["content"] for item in self.history])
@s... | prompt = self._get_instruct_style_input()
with retrieve_proxy():
response = client.completions.create(
model=self.model_name,
prompt=prompt,
temperature=self.temperature,
top_p=self.top_p,
)
return response.c... | prompt = self._get_instruct_style_input()
with retrieve_proxy():
response = client.completions.create(
model=self.model_name,
prompt=prompt,
temperature=self.temperature,
top_p=self.top_p,
)
return response.c... | 16 | 144 | 105 | 249 | from openai import OpenAI
client = OpenAI()
from .base_model import BaseLLMModel
from .. import shared
from ..config import retrieve_proxy
class OpenAI_Instruct_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, con... | from openai import OpenAI
client = OpenAI()
from .base_model import BaseLLMModel
from .. import shared
from ..config import retrieve_proxy
class OpenAI_Instruct_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name, con... |
886 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/inspurai.py | 37,38 | 17,45 | as_dict | Example | 38,45 | 38,45 | class Example:
""" store some examples(input, output pairs and formats) for few-shots to prime the model."""
def __init__(self, inp, out):
self.input = inp
self.output = out
self.id = uuid.uuid4().hex
def get_input(self):
"""return the input of the example."""
retur... | class Example:
""" store some examples(input, output pairs and formats) for few-shots to prime the model."""
def __init__(self, inp, out):
self.input = inp
self.output = out
self.id = uuid.uuid4().hex
def get_input(self):
"""return the input of the example."""
retur... | return {
"input": self.get_input(),
"output": self.get_output(),
"id": self.get_id(),
}
| return {
"input": self.get_input(),
"output": self.get_output(),
"id": self.get_id(),
}
| 9 | 168 | 49 | 217 | # 代码主要来源于 https://github.com/Shawn-Inspur/Yuan-1.0/blob/main/yuan_api/inspurai.py
import hashlib
import json
import os
import time
import uuid
from datetime import datetime
import pytz
import requests
from modules.presets import NO_APIKEY_MSG
from modules.models.base_model import BaseLLMModel
class Example:
""... | # 代码主要来源于 https://github.com/Shawn-Inspur/Yuan-1.0/blob/main/yuan_api/inspurai.py
import hashlib
import json
import os
import time
import uuid
from datetime import datetime
import pytz
import requests
from modules.presets import NO_APIKEY_MSG
from modules.models.base_model import BaseLLMModel
class Example:
""... |
887 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/inspurai.py | 139,149 | 45,209 | response | Yuan | 150,163 | 149,163 | class Yuan:
"""The main class for a user to interface with the Inspur Yuan API.
A user can set account info and add examples of the API request.
"""
def __init__(self,
engine='base_10B',
temperature=0.9,
max_tokens=100,
input_prefix=''... | class Yuan:
"""The main class for a user to interface with the Inspur Yuan API.
A user can set account info and add examples of the API request.
"""
def __init__(self,
engine='base_10B',
temperature=0.9,
max_tokens=100,
input_prefix=''... |
if self.api is None:
return NO_APIKEY_MSG
try:
# requestId = submit_request(query,temperature,topP,topK,max_tokens, engine)
requestId = self.api.submit_request(query, temperature, topP, topK, max_tokens, engine, frequencyPenalty,
... | """Obtains the original result returned by the API."""
if self.api is None:
return NO_APIKEY_MSG
try:
# requestId = submit_request(query,temperature,topP,topK,max_tokens, engine)
requestId = self.api.submit_request(query, temperature, topP, topK, max_tokens, ... | 34 | 1,612 | 150 | 1,762 | # 代码主要来源于 https://github.com/Shawn-Inspur/Yuan-1.0/blob/main/yuan_api/inspurai.py
import hashlib
import json
import os
import time
import uuid
from datetime import datetime
import pytz
import requests
from modules.presets import NO_APIKEY_MSG
from modules.models.base_model import BaseLLMModel
class Example:
""... | # 代码主要来源于 https://github.com/Shawn-Inspur/Yuan-1.0/blob/main/yuan_api/inspurai.py
import hashlib
import json
import os
import time
import uuid
from datetime import datetime
import pytz
import requests
from modules.presets import NO_APIKEY_MSG
from modules.models.base_model import BaseLLMModel
class Example:
""... |
888 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/inspurai.py | 246,248 | 209,281 | submit_request | YuanAPI | 249,265 | 248,265 | class YuanAPI:
ACCOUNT = ''
PHONE = ''
SUBMIT_URL = "http://api.airyuan.cn:32102/v1/interface/api/infer/getRequestId?"
REPLY_URL = "http://api.airyuan.cn:32102/v1/interface/api/result?"
def __init__(self, user, phone):
self.ACCOUNT = user
self.PHONE = phone
@staticmethod
d... | class YuanAPI:
ACCOUNT = ''
PHONE = ''
SUBMIT_URL = "http://api.airyuan.cn:32102/v1/interface/api/infer/getRequestId?"
REPLY_URL = "http://api.airyuan.cn:32102/v1/interface/api/result?"
def __init__(self, user, phone):
self.ACCOUNT = user
self.PHONE = phone
@staticmethod
d... | headers = self.header_generation()
# url=SUBMIT_URL + "account={0}&data={1}&temperature={2}&topP={3}&topK={4}&tokensToGenerate={5}&type={6}".format(ACCOUNT,query,temperature,topP,topK,max_tokens,"api")
# url=SUBMIT_URL + "engine={0}&account={1}&data={2}&temperature={3}&topP={4}&topK={5}&tokensTo... | """Submit query to the backend server and get requestID."""
headers = self.header_generation()
# url=SUBMIT_URL + "account={0}&data={1}&temperature={2}&topP={3}&topK={4}&tokensToGenerate={5}&type={6}".format(ACCOUNT,query,temperature,topP,topK,max_tokens,"api")
# url=SUBMIT_URL + "engine... | 52 | 641 | 409 | 1,050 | # 代码主要来源于 https://github.com/Shawn-Inspur/Yuan-1.0/blob/main/yuan_api/inspurai.py
import hashlib
import json
import os
import time
import uuid
from datetime import datetime
import pytz
import requests
from modules.presets import NO_APIKEY_MSG
from modules.models.base_model import BaseLLMModel
class Example:
""... | # 代码主要来源于 https://github.com/Shawn-Inspur/Yuan-1.0/blob/main/yuan_api/inspurai.py
import hashlib
import json
import os
import time
import uuid
from datetime import datetime
import pytz
import requests
from modules.presets import NO_APIKEY_MSG
from modules.models.base_model import BaseLLMModel
class Example:
""... |
889 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/inspurai.py | 298,299 | 281,346 | get_answer_at_once | Yuan_Client | 299,346 | 299,346 | class Yuan_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="", system_prompt=None):
super().__init__(model_name=model_name, user=user_name)
self.history = []
self.api_key = api_key
self.system_prompt = system_prompt
self.input_prefix = ""
sel... | class Yuan_Client(BaseLLMModel):
def __init__(self, model_name, api_key, user_name="", system_prompt=None):
super().__init__(model_name=model_name, user=user_name)
self.history = []
self.api_key = api_key
self.system_prompt = system_prompt
self.input_prefix = ""
sel... | # yuan temperature is (0,1] and base model temperature is [0,2], and yuan 0.9 == base 1 so need to convert
temperature = self.temperature if self.temperature <= 1 else 0.9 + (self.temperature - 1) / 10
topP = self.top_p
topK = self.n_choices
# max_tokens should be in [1,200]
... | # yuan temperature is (0,1] and base model temperature is [0,2], and yuan 0.9 == base 1 so need to convert
temperature = self.temperature if self.temperature <= 1 else 0.9 + (self.temperature - 1) / 10
topP = self.top_p
topK = self.n_choices
# max_tokens should be in [1,200]
... | 183 | 191 | 672 | 863 | # 代码主要来源于 https://github.com/Shawn-Inspur/Yuan-1.0/blob/main/yuan_api/inspurai.py
import hashlib
import json
import os
import time
import uuid
from datetime import datetime
import pytz
import requests
from modules.presets import NO_APIKEY_MSG
from modules.models.base_model import BaseLLMModel
class Example:
""... | # 代码主要来源于 https://github.com/Shawn-Inspur/Yuan-1.0/blob/main/yuan_api/inspurai.py
import hashlib
import json
import os
import time
import uuid
from datetime import datetime
import pytz
import requests
from modules.presets import NO_APIKEY_MSG
from modules.models.base_model import BaseLLMModel
class Example:
""... |
890 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/minimax.py | 68,69 | 14,162 | _get_response | MiniMax_Client | 69,130 | 69,130 | class MiniMax_Client(BaseLLMModel):
"""
MiniMax Client
接口文档见 https://api.minimax.chat/document/guides/chat
"""
def __init__(self, model_name, api_key, user_name="", system_prompt=None):
super().__init__(model_name=model_name, user=user_name)
self.url = f'https://api.minimax.chat/v1/... | class MiniMax_Client(BaseLLMModel):
"""
MiniMax Client
接口文档见 https://api.minimax.chat/document/guides/chat
"""
def __init__(self, model_name, api_key, user_name="", system_prompt=None):
super().__init__(model_name=model_name, user=user_name)
self.url = f'https://api.minimax.chat/v1/... | minimax_api_key = self.api_key
history = self.history
logging.debug(colorama.Fore.YELLOW +
f"{history}" + colorama.Fore.RESET)
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {minimax_api_key}",
}
te... | minimax_api_key = self.api_key
history = self.history
logging.debug(colorama.Fore.YELLOW +
f"{history}" + colorama.Fore.RESET)
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {minimax_api_key}",
}
te... | 144 | 1,060 | 672 | 1,732 | import json
import os
import colorama
import requests
import logging
from modules.models.base_model import BaseLLMModel
from modules.presets import STANDARD_ERROR_MSG, GENERAL_ERROR_MSG, TIMEOUT_STREAMING, TIMEOUT_ALL, i18n
group_id = os.environ.get("MINIMAX_GROUP_ID", "")
class MiniMax_Client(BaseLLMModel):
"... | import json
import os
import colorama
import requests
import logging
from modules.models.base_model import BaseLLMModel
from modules.presets import STANDARD_ERROR_MSG, GENERAL_ERROR_MSG, TIMEOUT_STREAMING, TIMEOUT_ALL, i18n
group_id = os.environ.get("MINIMAX_GROUP_ID", "")
class MiniMax_Client(BaseLLMModel):
"... |
891 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/spark.py | 107,108 | 67,167 | gen_params | Spark_Client | 111,125 | 108,125 | class Spark_Client(BaseLLMModel):
def __init__(self, model_name, appid, api_key, api_secret, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name)
self.api_key = api_key
self.appid = appid
self.api_secret = api_secret
if None in [self.api_key, self.ap... | class Spark_Client(BaseLLMModel):
def __init__(self, model_name, appid, api_key, api_secret, user_name="") -> None:
super().__init__(model_name=model_name, user=user_name)
self.api_key = api_key
self.appid = appid
self.api_secret = api_secret
if None in [self.api_key, self.ap... | data = {
"header": {"app_id": self.appid, "uid": "1234"},
"parameter": {
"chat": {
"domain": self.domain,
"random_threshold": self.temperature,
"max_tokens": 4096,
"auditing": "default",
... | """
通过appid和用户的提问来生成请参数
"""
data = {
"header": {"app_id": self.appid, "uid": "1234"},
"parameter": {
"chat": {
"domain": self.domain,
"random_threshold": self.temperature,
"max_tokens": 40... | 29 | 1,006 | 129 | 1,135 | import _thread as thread
import base64
import datetime
import hashlib
import hmac
import json
from collections import deque
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
from threading i... | import _thread as thread
import base64
import datetime
import hashlib
import hmac
import json
from collections import deque
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
from threading i... |
892 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/models/spark.py | 33,34 | 21,67 | create_url | Ws_Param | 34,67 | 34,67 | class Ws_Param(object):
# 来自官方 Demo
# 初始化
def __init__(self, APPID, APIKey, APISecret, Spark_url):
self.APPID = APPID
self.APIKey = APIKey
self.APISecret = APISecret
self.host = urlparse(Spark_url).netloc
self.path = urlparse(Spark_url).path
self.Spark_url = S... | class Ws_Param(object):
# 来自官方 Demo
# 初始化
def __init__(self, APPID, APIKey, APISecret, Spark_url):
self.APPID = APPID
self.APIKey = APIKey
self.APISecret = APISecret
self.host = urlparse(Spark_url).netloc
self.path = urlparse(Spark_url).path
self.Spark_url = S... | # 生成RFC1123格式的时间戳
now = datetime.now()
date = format_date_time(mktime(now.timetuple()))
# 拼接字符串
signature_origin = "host: " + self.host + "\n"
signature_origin += "date: " + date + "\n"
signature_origin += "GET " + self.path + " HTTP/1.1"
# 进行hmac-sha256... | # 生成RFC1123格式的时间戳
now = datetime.now()
date = format_date_time(mktime(now.timetuple()))
# 拼接字符串
signature_origin = "host: " + self.host + "\n"
signature_origin += "date: " + date + "\n"
signature_origin += "GET " + self.path + " HTTP/1.1"
# 进行hmac-sha256... | 84 | 152 | 469 | 621 | import _thread as thread
import base64
import datetime
import hashlib
import hmac
import json
from collections import deque
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
from threading i... | import _thread as thread
import base64
import datetime
import hashlib
import hmac
import json
from collections import deque
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
from threading i... |
893 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/overwrites.py | 69,70 | 1,98 | init_with_class_name_as_elem_classes | 70,87 | 70,87 | from __future__ import annotations
import inspect
import gradio as gr
from gradio.components.chatbot import ChatbotData, FileMessage
from gradio.data_classes import FileData
from gradio_client import utils as client_utils
from modules.utils import convert_bot_before_marked, convert_user_before_marked
def postproce... | from __future__ import annotations
import inspect
import gradio as gr
from gradio.components.chatbot import ChatbotData, FileMessage
from gradio.data_classes import FileData
from gradio_client import utils as client_utils
from modules.utils import convert_bot_before_marked, convert_user_before_marked
def postproce... | def wrapper(self, *args, **kwargs):
if "elem_classes" in kwargs and isinstance(kwargs["elem_classes"], str):
kwargs["elem_classes"] = [kwargs["elem_classes"]]
else:
kwargs["elem_classes"] = []
kwargs["elem_classes"].append("gradio-" + self.__class__.__name__.lower())... | def wrapper(self, *args, **kwargs):
if "elem_classes" in kwargs and isinstance(kwargs["elem_classes"], str):
kwargs["elem_classes"] = [kwargs["elem_classes"]]
else:
kwargs["elem_classes"] = []
kwargs["elem_classes"].append("gradio-" + self.__class__.__name__.lower())... | 34 | 927 | 176 | 1,103 | from __future__ import annotations
import inspect
import gradio as gr
from gradio.components.chatbot import ChatbotData, FileMessage
from gradio.data_classes import FileData
from gradio_client import utils as client_utils
from modules.utils import convert_bot_before_marked, convert_user_before_marked
def postproce... | from __future__ import annotations
import inspect
import gradio as gr
from gradio.components.chatbot import ChatbotData, FileMessage
from gradio.data_classes import FileData
from gradio_client import utils as client_utils
from modules.utils import convert_bot_before_marked, convert_user_before_marked
def postproce... | |
896 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/shared.py | 6,7 | 1,78 | format_openai_host | 7,19 | 7,19 | from modules.presets import CHAT_COMPLETION_URL, BALANCE_API_URL, USAGE_API_URL, API_HOST, OPENAI_API_BASE, IMAGES_COMPLETION_URL
import os
import queue
import openai
def format_openai_host(api_host: str):
FILL_FUNC_BODYclass State:
interrupted = False
multi_api_key = False
chat_completion_url = CHAT_COMPL... | from modules.presets import CHAT_COMPLETION_URL, BALANCE_API_URL, USAGE_API_URL, API_HOST, OPENAI_API_BASE, IMAGES_COMPLETION_URL
import os
import queue
import openai
def format_openai_host(api_host: str):
FILL_FUNC_BODYclass State:
interrupted = False
multi_api_key = False
chat_completion_url = CHAT_COMPL... | api_host = api_host.rstrip("/")
if not api_host.startswith("http"):
api_host = f"https://{api_host}"
if api_host.endswith("/v1"):
api_host = api_host[:-3]
chat_completion_url = f"{api_host}/v1/chat/completions"
images_completion_url = f"{api_host}/v1/images/generations"
openai_ap... | api_host = api_host.rstrip("/")
if not api_host.startswith("http"):
api_host = f"https://{api_host}"
if api_host.endswith("/v1"):
api_host = api_host[:-3]
chat_completion_url = f"{api_host}/v1/chat/completions"
images_completion_url = f"{api_host}/v1/images/generations"
openai_ap... | 35 | 758 | 238 | 996 | from modules.presets import CHAT_COMPLETION_URL, BALANCE_API_URL, USAGE_API_URL, API_HOST, OPENAI_API_BASE, IMAGES_COMPLETION_URL
import os
import queue
import openai
def format_openai_host(api_host: str):
FILL_FUNC_BODYclass State:
interrupted = False
multi_api_key = False
chat_completion_url = CHAT_COMPL... | from modules.presets import CHAT_COMPLETION_URL, BALANCE_API_URL, USAGE_API_URL, API_HOST, OPENAI_API_BASE, IMAGES_COMPLETION_URL
import os
import queue
import openai
def format_openai_host(api_host: str):
FILL_FUNC_BODYclass State:
interrupted = False
multi_api_key = False
chat_completion_url = CHAT_COMPL... | |
897 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/shared.py | 63,64 | 19,73 | wrapped | State | 64,70 | 64,70 | class State:
interrupted = False
multi_api_key = False
chat_completion_url = CHAT_COMPLETION_URL
balance_api_url = BALANCE_API_URL
usage_api_url = USAGE_API_URL
openai_api_base = OPENAI_API_BASE
images_completion_url = IMAGES_COMPLETION_URL
api_host = API_HOST
def interrupt(self):
... | class State:
interrupted = False
multi_api_key = False
chat_completion_url = CHAT_COMPLETION_URL
balance_api_url = BALANCE_API_URL
usage_api_url = USAGE_API_URL
openai_api_base = OPENAI_API_BASE
images_completion_url = IMAGES_COMPLETION_URL
api_host = API_HOST
def interrupt(self):
... | api_key = self.api_key_queue.get()
args[0].api_key = api_key
ret = func(*args, **kwargs)
self.api_key_queue.put(api_key)
return ret
| api_key = self.api_key_queue.get()
args[0].api_key = api_key
ret = func(*args, **kwargs)
self.api_key_queue.put(api_key)
return ret
| 13 | 551 | 67 | 618 | from modules.presets import CHAT_COMPLETION_URL, BALANCE_API_URL, USAGE_API_URL, API_HOST, OPENAI_API_BASE, IMAGES_COMPLETION_URL
import os
import queue
import openai
def format_openai_host(api_host: str):
api_host = api_host.rstrip("/")
if not api_host.startswith("http"):
api_host = f"https://{api_hos... | from modules.presets import CHAT_COMPLETION_URL, BALANCE_API_URL, USAGE_API_URL, API_HOST, OPENAI_API_BASE, IMAGES_COMPLETION_URL
import os
import queue
import openai
def format_openai_host(api_host: str):
api_host = api_host.rstrip("/")
if not api_host.startswith("http"):
api_host = f"https://{api_hos... |
898 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/train_func.py | 132,133 | 1,163 | add_to_models | 133,158 | 133,158 | import os
import logging
import traceback
from openai import OpenAI
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
import gradio as gr
import ujson as json
import commentjson
import openpyxl
import modules.presets as presets
from modules.utils import get_file_hash, count_token
from modules.presets import i18n
... | import os
import logging
import traceback
from openai import OpenAI
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
import gradio as gr
import ujson as json
import commentjson
import openpyxl
import modules.presets as presets
from modules.utils import get_file_hash, count_token
from modules.presets import i18n
... | succeeded_jobs = [job for job in client.fine_tuning.jobs.list().data if job.status == "succeeded"]
extra_models = [job.fine_tuned_model for job in succeeded_jobs]
for i in extra_models:
if i not in presets.MODELS:
presets.MODELS.append(i)
with open('config.json', 'r') as f:
... | succeeded_jobs = [job for job in client.fine_tuning.jobs.list().data if job.status == "succeeded"]
extra_models = [job.fine_tuned_model for job in succeeded_jobs]
for i in extra_models:
if i not in presets.MODELS:
presets.MODELS.append(i)
with open('config.json', 'r') as f:
... | 98 | 1,585 | 391 | 1,976 | import os
import logging
import traceback
from openai import OpenAI
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
import gradio as gr
import ujson as json
import commentjson
import openpyxl
import modules.presets as presets
from modules.utils import get_file_hash, count_token
from modules.presets import i18n
... | import os
import logging
import traceback
from openai import OpenAI
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
import gradio as gr
import ujson as json
import commentjson
import openpyxl
import modules.presets as presets
from modules.utils import get_file_hash, count_token
from modules.presets import i18n
... | |
899 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/webui.py | 21,22 | 1,85 | webpath | 22,28 | 22,28 |
from collections import namedtuple
import os
import gradio as gr
from . import shared
# with open("./assets/ChuanhuChat.js", "r", encoding="utf-8") as f, \
# open("./assets/external-scripts.js", "r", encoding="utf-8") as f1:
# customJS = f.read()
# externalScripts = f1.read()
def get_html(filename):
... |
from collections import namedtuple
import os
import gradio as gr
from . import shared
# with open("./assets/ChuanhuChat.js", "r", encoding="utf-8") as f, \
# open("./assets/external-scripts.js", "r", encoding="utf-8") as f1:
# customJS = f.read()
# externalScripts = f1.read()
def get_html(filename):
... | if fn.startswith(shared.assets_path):
web_path = os.path.relpath(fn, shared.chuanhu_path).replace('\\', '/')
else:
web_path = os.path.abspath(fn)
return f'file={web_path}?{os.path.getmtime(fn)}'
| if fn.startswith(shared.assets_path):
web_path = os.path.relpath(fn, shared.chuanhu_path).replace('\\', '/')
else:
web_path = os.path.abspath(fn)
return f'file={web_path}?{os.path.getmtime(fn)}'
| 13 | 1,229 | 96 | 1,325 |
from collections import namedtuple
import os
import gradio as gr
from . import shared
# with open("./assets/ChuanhuChat.js", "r", encoding="utf-8") as f, \
# open("./assets/external-scripts.js", "r", encoding="utf-8") as f1:
# customJS = f.read()
# externalScripts = f1.read()
def get_html(filename):
... |
from collections import namedtuple
import os
import gradio as gr
from . import shared
# with open("./assets/ChuanhuChat.js", "r", encoding="utf-8") as f, \
# open("./assets/external-scripts.js", "r", encoding="utf-8") as f1:
# customJS = f.read()
# externalScripts = f1.read()
def get_html(filename):
... | |
900 | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT | /home/hieuvd/dung_repo/raw/stars_01/GaiZhenbiao_ChuanhuChatGPT/ChuanhuChatGPT/modules/webui_locale.py | 33,34 | 6,53 | change_language | I18nAuto | 34,46 | 34,46 | class I18nAuto:
def __init__(self):
if os.path.exists("config.json"):
with open("config.json", "r", encoding='utf-8') as f:
config = json.load(f)
else:
config = {}
language = config.get("language", "auto")
language = os.environ.get("LANGUAGE", ... | class I18nAuto:
def __init__(self):
if os.path.exists("config.json"):
with open("config.json", "r", encoding='utf-8') as f:
config = json.load(f)
else:
config = {}
language = config.get("language", "auto")
language = os.environ.get("LANGUAGE", ... | language = language.replace("-", "_")
self.language_map = {}
self.file_is_exists = os.path.isfile(f"./locale/{language}.json")
if self.file_is_exists:
with open(f"./locale/{language}.json", "r", encoding="utf-8") as f:
self.language_map.update(json.load(f))
... | language = language.replace("-", "_")
self.language_map = {}
self.file_is_exists = os.path.isfile(f"./locale/{language}.json")
if self.file_is_exists:
with open(f"./locale/{language}.json", "r", encoding="utf-8") as f:
self.language_map.update(json.load(f))
... | 45 | 516 | 220 | 736 | import os
import locale
import logging
import commentjson as json
class I18nAuto:
def __init__(self):
if os.path.exists("config.json"):
with open("config.json", "r", encoding='utf-8') as f:
config = json.load(f)
else:
config = {}
language = config.get... | import os
import locale
import logging
import commentjson as json
class I18nAuto:
def __init__(self):
if os.path.exists("config.json"):
with open("config.json", "r", encoding='utf-8') as f:
config = json.load(f)
else:
config = {}
language = config.get... |
974 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/examples/app/hpo/utils.py | 9,10 | 1,56 | download_data | 20,56 | 10,56 | import os
import os.path
import tarfile
import zipfile
import requests
def download_data(url: str, path: str = "data/", verbose: bool = False) -> None:
FILL_FUNC_BODY | import os
import os.path
import tarfile
import zipfile
import requests
def download_data(url: str, path: str = "data/", verbose: bool = False) -> None:
"""Download file with progressbar.
# Code taken from: https://gist.github.com/ruxi/5d6803c116ec1130d484a4ab8c00c603
# __author__ = "github.com/ruxi"
... | if url == "NEED_TO_BE_CREATED":
raise NotImplementedError
if not os.path.exists(path):
os.makedirs(path)
local_filename = os.path.join(path, url.split("/")[-1])
r = requests.get(url, stream=True, verify=False)
file_size = int(r.headers["Content-Length"]) if "Content-Length" in r.hea... | """Download file with progressbar.
# Code taken from: https://gist.github.com/ruxi/5d6803c116ec1130d484a4ab8c00c603
# __author__ = "github.com/ruxi"
# __license__ = "MIT"
Usage:
download_file('http://web4host.net/5MB.zip')
"""
if url == "NEED_TO_BE_CREATED":
raise NotImpl... | 118 | 175 | 571 | 746 | import os
import os.path
import tarfile
import zipfile
import requests
def download_data(url: str, path: str = "data/", verbose: bool = False) -> None:
FILL_FUNC_BODY | import os
import os.path
import tarfile
import zipfile
import requests
def download_data(url: str, path: str = "data/", verbose: bool = False) -> None:
"""Download file with progressbar.
# Code taken from: https://gist.github.com/ruxi/5d6803c116ec1130d484a4ab8c00c603
# __author__ = "github.com/ruxi"
... | |
975 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/examples/fabric/reinforcement_learning/rl/loss.py | 12,20 | 1,30 | value_loss | 20,28 | 20,28 | import torch
import torch.nn.functional as F
from torch import Tensor
def policy_loss(advantages: torch.Tensor, ratio: torch.Tensor, clip_coef: float) -> torch.Tensor:
pg_loss1 = -advantages * ratio
pg_loss2 = -advantages * torch.clamp(ratio, 1 - clip_coef, 1 + clip_coef)
return torch.max(pg_loss1, pg_los... | import torch
import torch.nn.functional as F
from torch import Tensor
def policy_loss(advantages: torch.Tensor, ratio: torch.Tensor, clip_coef: float) -> torch.Tensor:
pg_loss1 = -advantages * ratio
pg_loss2 = -advantages * torch.clamp(ratio, 1 - clip_coef, 1 + clip_coef)
return torch.max(pg_loss1, pg_los... | new_values = new_values.view(-1)
if not clip_vloss:
values_pred = new_values
else:
values_pred = old_values + torch.clamp(new_values - old_values, -clip_coef, clip_coef)
return vf_coef * F.mse_loss(values_pred, returns)
| new_values = new_values.view(-1)
if not clip_vloss:
values_pred = new_values
else:
values_pred = old_values + torch.clamp(new_values - old_values, -clip_coef, clip_coef)
return vf_coef * F.mse_loss(values_pred, returns)
| 24 | 245 | 103 | 348 | import torch
import torch.nn.functional as F
from torch import Tensor
def policy_loss(advantages: torch.Tensor, ratio: torch.Tensor, clip_coef: float) -> torch.Tensor:
pg_loss1 = -advantages * ratio
pg_loss2 = -advantages * torch.clamp(ratio, 1 - clip_coef, 1 + clip_coef)
return torch.max(pg_loss1, pg_los... | import torch
import torch.nn.functional as F
from torch import Tensor
def policy_loss(advantages: torch.Tensor, ratio: torch.Tensor, clip_coef: float) -> torch.Tensor:
pg_loss1 = -advantages * ratio
pg_loss2 = -advantages * torch.clamp(ratio, 1 - clip_coef, 1 + clip_coef)
return torch.max(pg_loss1, pg_los... | |
977 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/examples/fabric/tensor_parallel/model.py | 174,175 | 143,217 | init_weights | Attention | 175,179 | 175,179 | class Attention(nn.Module):
"""Multi-head attention module.
Args:
model_args (ModelArgs): Model configuration arguments.
Attributes:
n_kv_heads (int): Number of key and value heads.
n_heads (int): Number of query heads.
n_local_kv_heads (int): Number of local key and value ... | class Attention(nn.Module):
"""Multi-head attention module.
Args:
model_args (ModelArgs): Model configuration arguments.
Attributes:
n_kv_heads (int): Number of key and value heads.
n_heads (int): Number of query heads.
n_local_kv_heads (int): Number of local key and value ... | for linear in (self.wq, self.wk, self.wv):
nn.init.trunc_normal_(linear.weight, mean=0.0, std=0.02)
nn.init.trunc_normal_(self.wo.weight, mean=0.0, std=init_std)
| for linear in (self.wq, self.wk, self.wv):
nn.init.trunc_normal_(linear.weight, mean=0.0, std=0.02)
nn.init.trunc_normal_(self.wo.weight, mean=0.0, std=init_std)
| 12 | 1,080 | 85 | 1,165 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import nn
@dataclass
class ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import nn
@dataclass
class ... |
978 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/examples/fabric/tensor_parallel/model.py | 254,255 | 217,260 | init_weights | FeedForward | 255,260 | 255,260 | class FeedForward(nn.Module):
"""FeedForward module.
Args:
dim (int): Input dimension.
hidden_dim (int): Hidden dimension of the feedforward layer.
multiple_of (int): Value to ensure hidden dimension is a multiple of this value.
ffn_dim_multiplier (Optional[float]): Custom multi... | class FeedForward(nn.Module):
"""FeedForward module.
Args:
dim (int): Input dimension.
hidden_dim (int): Hidden dimension of the feedforward layer.
multiple_of (int): Value to ensure hidden dimension is a multiple of this value.
ffn_dim_multiplier (Optional[float]): Custom multi... | nn.init.trunc_normal_(self.w1.weight, mean=0.0, std=0.02)
for linear in (self.w2, self.w3):
nn.init.trunc_normal_(linear.weight, mean=0.0, std=init_std)
| nn.init.trunc_normal_(self.w1.weight, mean=0.0, std=0.02)
for linear in (self.w2, self.w3):
nn.init.trunc_normal_(linear.weight, mean=0.0, std=init_std)
| 11 | 433 | 83 | 516 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import nn
@dataclass
class ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import nn
@dataclass
class ... |
979 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/examples/fabric/tensor_parallel/model.py | 135,136 | 114,143 | forward | RMSNorm | 136,139 | 136,139 | class RMSNorm(nn.Module):
"""Initialize the RMSNorm normalization layer.
Args:
dim (int): The dimension of the input tensor.
eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
Attributes:
eps (float): A small value added to the d... | class RMSNorm(nn.Module):
"""Initialize the RMSNorm normalization layer.
Args:
dim (int): The dimension of the input tensor.
eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
Attributes:
eps (float): A small value added to the d... | output = self._norm(x.float()).type_as(x)
return output * self.weight
| output = self._norm(x.float()).type_as(x)
return output * self.weight
| 7 | 274 | 30 | 304 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import nn
@dataclass
class ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import nn
@dataclass
class ... |
980 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/examples/fabric/tensor_parallel/model.py | 377,378 | 326,437 | init_weights | Transformer | 391,405 | 378,405 | class Transformer(nn.Module):
"""Transformer Module.
Args:
model_args (ModelArgs): Model configuration arguments.
Attributes:
model_args (ModelArgs): Model configuration arguments.
vocab_size (int): Vocabulary size.
n_layers (int): Number of layers in the model.
tok... | class Transformer(nn.Module):
"""Transformer Module.
Args:
model_args (ModelArgs): Model configuration arguments.
Attributes:
model_args (ModelArgs): Model configuration arguments.
vocab_size (int): Vocabulary size.
n_layers (int): Number of layers in the model.
tok... | nn.init.normal_(self.tok_embeddings.weight)
for layer in self.layers:
layer.init_weights()
self.norm.reset_parameters()
final_out_std = self.model_args.dim**-0.5
cutoff_factor = 3
nn.init.trunc_normal_(
self.output.weight,
mean=0.0,
... | """[Note: On ``init_weights`` vs.
``reset_parameters``]
Modules may define ``reset_parameters`` to initialize parameter values.
``reset_parameters`` is meant to only initialize directly owned
parameters/buffers, not those of their child modules, and it can be
used to giv... | 24 | 1,092 | 161 | 1,253 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import nn
@dataclass
class ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import nn
@dataclass
class ... |
981 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/examples/fabric/tensor_parallel/model.py | 301,306 | 260,326 | forward | TransformerBlock | 316,319 | 306,319 | class TransformerBlock(nn.Module):
"""TransformerBlock Module.
Args:
layer_id (int): Identifier for the layer.
model_args (ModelArgs): Model configuration arguments.
Attributes:
n_heads (int): Number of attention heads.
dim (int): Dimension size of the model.
head_d... | class TransformerBlock(nn.Module):
"""TransformerBlock Module.
Args:
layer_id (int): Identifier for the layer.
model_args (ModelArgs): Model configuration arguments.
Attributes:
n_heads (int): Number of attention heads.
dim (int): Dimension size of the model.
head_d... | h = x + self.attention(self.attention_norm(x), freqs_cis)
return h + self.feed_forward(self.ffn_norm(h))
| """Perform a forward pass through the TransformerBlock.
Args:
x (torch.Tensor): Input tensor.
freqs_cis (torch.Tensor): Precomputed cosine and sine frequencies.
Returns:
torch.Tensor: Output tensor after applying attention and feedforward layers.
""... | 10 | 708 | 49 | 757 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import nn
@dataclass
class ... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import nn
@dataclass
class ... |
982 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/examples/fabric/tensor_parallel/parallelism.py | 19,20 | 1,102 | parallelize | 26,102 | 20,102 | import torch
from model import Transformer
from torch.distributed._composable.fsdp import MixedPrecisionPolicy
from torch.distributed._composable.fsdp.fully_shard import fully_shard
from torch.distributed._tensor import Replicate, Shard
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_... | import torch
from model import Transformer
from torch.distributed._composable.fsdp import MixedPrecisionPolicy
from torch.distributed._composable.fsdp.fully_shard import fully_shard
from torch.distributed._tensor import Replicate, Shard
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_... |
dp_mesh = device_mesh["data_parallel"]
tp_mesh = device_mesh["tensor_parallel"]
if tp_mesh.size() > 1:
# 1. Parallelize the first embedding and the last linear proj layer
# 2. Parallelize the root norm layer over the sequence dim
# 3. Shard the first transformer block's inputs
... | """Apply parallelisms and activation checkpointing to the model.
NOTE: The passed-in model preferably should be on meta device. Otherwise,
the model must fit on GPU or CPU memory.
"""
dp_mesh = device_mesh["data_parallel"]
tp_mesh = device_mesh["tensor_parallel"]
if tp_mesh.size() > 1:
... | 266 | 291 | 1,050 | 1,341 | import torch
from model import Transformer
from torch.distributed._composable.fsdp import MixedPrecisionPolicy
from torch.distributed._composable.fsdp.fully_shard import fully_shard
from torch.distributed._tensor import Replicate, Shard
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_... | import torch
from model import Transformer
from torch.distributed._composable.fsdp import MixedPrecisionPolicy
from torch.distributed._composable.fsdp.fully_shard import fully_shard
from torch.distributed._tensor import Replicate, Shard
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_... | |
984 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/api/request_types.py | 23,24 | 21,27 | to_dict | _BaseRequest | 24,27 | 24,27 | @dataclass
class _BaseRequest:
def to_dict(self):
FILL_FUNC_BODY | @dataclass
class _BaseRequest:
def to_dict(self):
FILL_FUNC_BODY | return asdict(self)
| return asdict(self)
| 2 | 30 | 13 | 43 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
985 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/api/request_types.py | 31,32 | 27,35 | to_dict | _DeltaRequest | 32,35 | 32,35 | @dataclass
class _DeltaRequest(_BaseRequest):
delta: Delta
def to_dict(self):
FILL_FUNC_BODY | @dataclass
class _DeltaRequest(_BaseRequest):
delta: Delta
def to_dict(self):
FILL_FUNC_BODY | return self.delta.to_dict()
| return self.delta.to_dict()
| 2 | 40 | 16 | 56 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
986 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/cmd_apps.py | 90,94 | 86,147 | _textualize_state_transitions | _AppList | 94,125 | 94,125 | class _AppList(Formatable):
def __init__(self, apps: List[Externalv1LightningappInstance]) -> None:
self.apps = apps
@staticmethod
def _textualize_state_transitions(
desired_state: V1LightningappInstanceState, current_state: V1LightningappInstanceStatus
) -> Text:
FILL_FUNC_BODY def ... | class _AppList(Formatable):
def __init__(self, apps: List[Externalv1LightningappInstance]) -> None:
self.apps = apps
@staticmethod
def _textualize_state_transitions(
desired_state: V1LightningappInstanceState, current_state: V1LightningappInstanceStatus
) -> Text:
FILL_FUNC_BODY def ... | phases = {
V1LightningappInstanceState.IMAGE_BUILDING: Text("building image", style="bold yellow"),
V1LightningappInstanceState.PENDING: Text("pending", style="bold yellow"),
V1LightningappInstanceState.RUNNING: Text("running", style="bold green"),
V1LightningappI... | phases = {
V1LightningappInstanceState.IMAGE_BUILDING: Text("building image", style="bold yellow"),
V1LightningappInstanceState.PENDING: Text("pending", style="bold yellow"),
V1LightningappInstanceState.RUNNING: Text("running", style="bold green"),
V1LightningappI... | 85 | 343 | 446 | 789 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
987 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/cmd_apps.py | 40,41 | 34,86 | get_app | _AppManager | 41,46 | 41,46 | class _AppManager:
"""_AppManager implements API calls specific to Lightning AI BYOC apps."""
def __init__(self) -> None:
self.api_client = LightningClient(retry=False)
def get_app(self, app_id: str) -> Externalv1LightningappInstance:
FILL_FUNC_BODY def list_apps(self, limit: int = 100, phase_i... | class _AppManager:
"""_AppManager implements API calls specific to Lightning AI BYOC apps."""
def __init__(self) -> None:
self.api_client = LightningClient(retry=False)
def get_app(self, app_id: str) -> Externalv1LightningappInstance:
FILL_FUNC_BODY def list_apps(self, limit: int = 100, phase_i... | project = _get_project(self.api_client)
return self.api_client.lightningapp_instance_service_get_lightningapp_instance(
project_id=project.project_id, id=app_id
)
| project = _get_project(self.api_client)
return self.api_client.lightningapp_instance_service_get_lightningapp_instance(
project_id=project.project_id, id=app_id
)
| 8 | 591 | 66 | 657 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
988 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/cmd_init.py | 25,26 | 1,168 | app | 26,45 | 26,45 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | if app_name is None:
app_name = _capture_valid_app_component_name(resource_type="app")
# generate resource template
new_resource_name, _ = _make_resource(resource_dir="app-template", resource_name=app_name)
m = f"""
⚡ Lightning app template created! ⚡
{new_resource_name}
run your ... | if app_name is None:
app_name = _capture_valid_app_component_name(resource_type="app")
# generate resource template
new_resource_name, _ = _make_resource(resource_dir="app-template", resource_name=app_name)
m = f"""
⚡ Lightning app template created! ⚡
{new_resource_name}
run your ... | 51 | 1,495 | 187 | 1,682 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
991 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/cmd_react_ui_init.py | 68,69 | 1,132 | _check_react_prerequisites | 70,132 | 69,132 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | missing_msgs = []
version_regex = r"\d{1,2}\.\d{1,2}\.\d{1,3}"
logger.info("Checking pre-requisites for react")
# make sure npm is installed
npm_version = subprocess.check_output(["npm", "--version"])
has_npm = bool(re.search(version_regex, str(npm_version)))
npm_version = re.search(versio... | """Args are for test purposes only."""
missing_msgs = []
version_regex = r"\d{1,2}\.\d{1,2}\.\d{1,3}"
logger.info("Checking pre-requisites for react")
# make sure npm is installed
npm_version = subprocess.check_output(["npm", "--version"])
has_npm = bool(re.search(version_regex, str(npm_ve... | 201 | 701 | 780 | 1,481 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
992 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/commands/app_commands.py | 35,36 | 1,136 | _run_app_command | 37,88 | 36,88 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # 1: Collect the url and comments from the running application
_clean_lightning_connection()
running_help = _is_running_help(sys.argv)
retriever = _LightningAppOpenAPIRetriever(app_id, use_cache=running_help)
if not running_help and (retriever.url is None or retriever.api_commands is None):
... | """Execute a function in a running App from its name."""
# 1: Collect the url and comments from the running application
_clean_lightning_connection()
running_help = _is_running_help(sys.argv)
retriever = _LightningAppOpenAPIRetriever(app_id, use_cache=running_help)
if not running_help and (re... | 175 | 945 | 605 | 1,550 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
993 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/commands/cd.py | 34,36 | 1,118 | cd | 37,113 | 36,113 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | with Live(Spinner("point", text=Text("pending...", style="white")), transient=True) as live:
root = "/"
if isinstance(path, Tuple) and len(path) > 0:
path = " ".join(path)
# handle ~/
if isinstance(path, str) and path.startswith(_HOME):
path = "/" + path.rep... | """Change the current directory within the Lightning Cloud filesystem."""
with Live(Spinner("point", text=Text("pending...", style="white")), transient=True) as live:
root = "/"
if isinstance(path, Tuple) and len(path) > 0:
path = " ".join(path)
# handle ~/
if isins... | 214 | 482 | 771 | 1,253 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
995 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/commands/logs.py | 54,55 | 1,123 | _show_logs | 55,123 | 55,123 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | client = LightningClient(retry=False)
project = _get_project(client)
apps = {
getattr(app, "display_name", None) or app.name: app
for app in client.lightningapp_instance_service_list_lightningapp_instances(
project_id=project.project_id
).lightningapps
}
if not ... | client = LightningClient(retry=False)
project = _get_project(client)
apps = {
getattr(app, "display_name", None) or app.name: app
for app in client.lightningapp_instance_service_list_lightningapp_instances(
project_id=project.project_id
).lightningapps
}
if not ... | 233 | 530 | 814 | 1,344 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
997 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/commands/pwd.py | 28,29 | 1,54 | pwd | 30,42 | 29,42 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | if sys.platform == "win32":
print("`pwd` isn't supported on windows. Open an issue on Github.")
sys.exit(0)
with Live(Spinner("point", text=Text("pending...", style="white")), transient=True):
root = _pwd()
print(root)
return root
| """Print your current working directory in the Lightning Cloud filesystem."""
if sys.platform == "win32":
print("`pwd` isn't supported on windows. Open an issue on Github.")
sys.exit(0)
with Live(Spinner("point", text=Text("pending...", style="white")), transient=True):
root = _pwd(... | 26 | 363 | 104 | 467 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
998 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/commands/rm.py | 30,34 | 1,102 | rm | 35,102 | 34,102 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | root = _pwd()
if rm_path in (".", ".."):
return _error_and_exit('rm "." and ".." may not be removed')
if ".." in rm_path:
return _error_and_exit('rm ".." or higher may not be removed')
root = os.path.join(root, rm_path)
splits = [split for split in root.split("/") if split != ""]
... | """Delete files on the Lightning Cloud filesystem."""
root = _pwd()
if rm_path in (".", ".."):
return _error_and_exit('rm "." and ".." may not be removed')
if ".." in rm_path:
return _error_and_exit('rm ".." or higher may not be removed')
root = os.path.join(root, rm_path)
spl... | 222 | 372 | 852 | 1,224 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,000 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/connect/data.py | 33,57 | 1,110 | connect_data | 58,110 | 57,110 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
from lightning_cloud.openapi import Create, V1AwsDataConnection
if sys.platform == "win32":
_error_and_exit("Data connection isn't supported on windows. Open an issue on Github.")
with Live(Spinner("point", text=Text("pending...", style="white")), transient=True) as live:
live.stop()
... | """Create a new data connection."""
from lightning_cloud.openapi import Create, V1AwsDataConnection
if sys.platform == "win32":
_error_and_exit("Data connection isn't supported on windows. Open an issue on Github.")
with Live(Spinner("point", text=Text("pending...", style="white")), transient... | 135 | 607 | 560 | 1,167 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
1,002 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/lightning_cli_delete.py | 29,30 | 1,125 | _find_selected_app_instance_id | 30,64 | 30,64 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | console = Console()
app_manager = _AppManager()
all_app_names_and_ids = {}
selected_app_instance_id = None
for app in app_manager.list_apps():
all_app_names_and_ids[app.name] = app.id
# figure out the ID of some app_name
if app_name == app.name or app_name == app.id:
... | console = Console()
app_manager = _AppManager()
all_app_names_and_ids = {}
selected_app_instance_id = None
for app in app_manager.list_apps():
all_app_names_and_ids[app.name] = app.id
# figure out the ID of some app_name
if app_name == app.name or app_name == app.id:
... | 101 | 938 | 399 | 1,337 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,003 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/lightning_cli_launch.py | 37,43 | 1,131 | run_server | 49,53 | 43,53 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | logger.debug(f"Run Server: {file} {queue_id} {host} {port}")
start_application_server(file, host, port, queue_id=queue_id)
| """It takes the application file as input, build the application object and then use that to run the application
server.
This is used by the cloud runners to start the status server for the application
"""
logger.debug(f"Run Server: {file} {queue_id} {host} {port}")
start_application_server(fi... | 10 | 1,554 | 54 | 1,608 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,004 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/lightning_cli_list.py | 28,30 | 1,33 | list_apps | 31,33 | 30,33 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | app_manager = _AppManager()
app_manager.list()
| """List your Lightning AI apps."""
app_manager = _AppManager()
app_manager.list()
| 4 | 271 | 20 | 291 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,005 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/cli/pl-app-template/setup.py | 9,10 | 1,35 | _load_requirements | 11,29 | 10,29 | import os
from typing import List
from setuptools import find_packages, setup
_PROJECT_ROOT = os.path.dirname(__file__)
def _load_requirements(path_dir: str, file_name: str = "requirements.txt", comment_char: str = "#") -> List[str]:
FILL_FUNC_BODYsetup(
name="{{ app_name }}",
version="0.0.1",
packages=... | import os
from typing import List
from setuptools import find_packages, setup
_PROJECT_ROOT = os.path.dirname(__file__)
def _load_requirements(path_dir: str, file_name: str = "requirements.txt", comment_char: str = "#") -> List[str]:
"""Load requirements from a file."""
FILL_FUNC_BODYsetup(
name="{{ app_nam... | with open(os.path.join(path_dir, file_name)) as file:
lines = [ln.strip() for ln in file.readlines()]
reqs = []
for ln in lines:
# filer all comments
if comment_char in ln:
ln = ln[: ln.index(comment_char)].strip()
# skip directly installed dependencies
if... | """Load requirements from a file."""
with open(os.path.join(path_dir, file_name)) as file:
lines = [ln.strip() for ln in file.readlines()]
reqs = []
for ln in lines:
# filer all comments
if comment_char in ln:
ln = ln[: ln.index(comment_char)].strip()
# skip d... | 57 | 151 | 189 | 340 | import os
from typing import List
from setuptools import find_packages, setup
_PROJECT_ROOT = os.path.dirname(__file__)
def _load_requirements(path_dir: str, file_name: str = "requirements.txt", comment_char: str = "#") -> List[str]:
FILL_FUNC_BODYsetup(
name="{{ app_name }}",
version="0.0.1",
packages=... | import os
from typing import List
from setuptools import find_packages, setup
_PROJECT_ROOT = os.path.dirname(__file__)
def _load_requirements(path_dir: str, file_name: str = "requirements.txt", comment_char: str = "#") -> List[str]:
"""Load requirements from a file."""
FILL_FUNC_BODYsetup(
name="{{ app_nam... | |
1,006 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/database/client.py | 28,29 | 1,94 | _configure_session | 34,47 | 29,47 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | retry_strategy = Retry(
# wait time between retries increases exponentially according to: backoff_factor * (2 ** (retry - 1))
total=_CONNECTION_RETRY_TOTAL,
backoff_factor=_CONNECTION_RETRY_BACKOFF_FACTOR,
status_forcelist=[429, 500, 502, 503, 504],
)
adapter = HTTPAdapter(ma... | """Configures the session for GET and POST requests.
It enables a generous retrial strategy that waits for the application server to connect.
"""
retry_strategy = Retry(
# wait time between retries increases exponentially according to: backoff_factor * (2 ** (retry - 1))
total=_CONNECT... | 39 | 824 | 181 | 1,005 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | |
1,007 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/database/client.py | 79,80 | 50,94 | delete | DatabaseClient | 80,86 | 80,86 | class DatabaseClient:
def __init__(self, db_url: str, token: Optional[str] = None, model: Optional[T] = None) -> None:
self.db_url = db_url
self.model = model
self.token = token or ""
self._session = None
def select_all(self, model: Optional[Type[T]] = None) -> List[T]:
... | class DatabaseClient:
def __init__(self, db_url: str, token: Optional[str] = None, model: Optional[T] = None) -> None:
self.db_url = db_url
self.model = model
self.token = token or ""
self._session = None
def select_all(self, model: Optional[Type[T]] = None) -> List[T]:
... | resp = self.session.post(
self.db_url + "/delete/",
data=_GeneralModel.from_obj(model, token=self.token).json(),
)
assert resp.status_code == 200
| resp = self.session.post(
self.db_url + "/delete/",
data=_GeneralModel.from_obj(model, token=self.token).json(),
)
assert resp.status_code == 200
| 13 | 452 | 66 | 518 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,008 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/multi_node/base.py | 90,91 | 25,108 | run | MultiNode | 91,108 | 91,108 | class MultiNode(LightningFlow):
def __init__(
self,
work_cls: Type["LightningWork"],
num_nodes: int,
cloud_compute: "CloudCompute",
*work_args: Any,
**work_kwargs: Any,
) -> None:
"""This component enables performing distributed multi-node multi-device tra... | class MultiNode(LightningFlow):
def __init__(
self,
work_cls: Type["LightningWork"],
num_nodes: int,
cloud_compute: "CloudCompute",
*work_args: Any,
**work_kwargs: Any,
) -> None:
"""This component enables performing distributed multi-node multi-device tra... | # 1. Wait for all works to be started !
if not all(w.internal_ip for w in self.ws):
return
# 2. Loop over all node machines
for node_rank in range(len(self.ws)):
# 3. Run the user code in a distributed way !
self.ws[node_rank].run(
mai... | # 1. Wait for all works to be started !
if not all(w.internal_ip for w in self.ws):
return
# 2. Loop over all node machines
for node_rank in range(len(self.ws)):
# 3. Run the user code in a distributed way !
self.ws[node_rank].run(
mai... | 56 | 584 | 206 | 790 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,009 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/multi_node/fabric.py | 37,47 | 35,111 | run | _FabricRunExecutor | 47,111 | 47,111 | @dataclass
class _FabricRunExecutor(_PyTorchSpawnRunExecutor):
@staticmethod
def run(
local_rank: int,
work_run: Callable,
main_address: str,
main_port: int,
num_nodes: int,
node_rank: int,
nprocs: int,
):
FILL_FUNC_BODY | @dataclass
class _FabricRunExecutor(_PyTorchSpawnRunExecutor):
@staticmethod
def run(
local_rank: int,
work_run: Callable,
main_address: str,
main_port: int,
num_nodes: int,
node_rank: int,
nprocs: int,
):
FILL_FUNC_BODY | fabrics = []
strategies = []
mps_accelerators = []
for pkg_name in ("lightning.fabric", "lightning_" + "fabric"):
try:
pkg = importlib.import_module(pkg_name)
fabrics.append(pkg.Fabric)
strategies.append(pkg.strategies.DDPStrat... | fabrics = []
strategies = []
mps_accelerators = []
for pkg_name in ("lightning.fabric", "lightning_" + "fabric"):
try:
pkg = importlib.import_module(pkg_name)
fabrics.append(pkg.Fabric)
strategies.append(pkg.strategies.DDPStrat... | 196 | 103 | 852 | 955 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,010 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/multi_node/pytorch_spawn.py | 57,59 | 36,104 | dispatch_run | _PyTorchSpawnRunExecutor | 59,74 | 59,74 | class _PyTorchSpawnRunExecutor(WorkRunExecutor):
enable_start_observer: bool = False
def __call__(
self,
main_address: str,
main_port: int,
num_nodes: int,
node_rank: int,
):
import torch
with self.enable_spawn():
nprocs = torch.cuda.devi... | class _PyTorchSpawnRunExecutor(WorkRunExecutor):
enable_start_observer: bool = False
def __call__(
self,
main_address: str,
main_port: int,
num_nodes: int,
node_rank: int,
):
import torch
with self.enable_spawn():
nprocs = torch.cuda.devi... | if local_rank == 0:
if isinstance(delta_queue, dict):
delta_queue = cls.process_queue(delta_queue)
work._request_queue = cls.process_queue(work._request_queue)
work._response_queue = cls.process_queue(work._response_queue)
state_observer =... | if local_rank == 0:
if isinstance(delta_queue, dict):
delta_queue = cls.process_queue(delta_queue)
work._request_queue = cls.process_queue(work._request_queue)
work._response_queue = cls.process_queue(work._response_queue)
state_observer =... | 33 | 543 | 192 | 735 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,011 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/multi_node/trainer.py | 37,47 | 35,106 | run | _LightningTrainerRunExecutor | 47,106 | 47,106 | @dataclass
class _LightningTrainerRunExecutor(_PyTorchSpawnRunExecutor):
@staticmethod
def run(
local_rank: int,
work_run: Callable,
main_address: str,
main_port: int,
num_nodes: int,
node_rank: int,
nprocs: int,
):
FILL_FUNC_BODY | @dataclass
class _LightningTrainerRunExecutor(_PyTorchSpawnRunExecutor):
@staticmethod
def run(
local_rank: int,
work_run: Callable,
main_address: str,
main_port: int,
num_nodes: int,
node_rank: int,
nprocs: int,
):
FILL_FUNC_BODY | trainers = []
strategies = []
mps_accelerators = []
for pkg_name in ("lightning.pytorch", "pytorch_" + "lightning"):
try:
pkg = importlib.import_module(pkg_name)
trainers.append(pkg.Trainer)
strategies.append(pkg.strategies.DDP... | trainers = []
strategies = []
mps_accelerators = []
for pkg_name in ("lightning.pytorch", "pytorch_" + "lightning"):
try:
pkg = importlib.import_module(pkg_name)
trainers.append(pkg.Trainer)
strategies.append(pkg.strategies.DDP... | 179 | 106 | 797 | 903 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,012 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/python/popen.py | 108,109 | 29,113 | on_exit | PopenPythonScript | 109,113 | 109,113 | class PopenPythonScript(LightningWork):
def on_before_run(self):
"""Called before the python script is executed."""
def on_after_run(self):
"""Called after the python script is executed."""
def configure_tracer(self) -> Tracer:
"""Override this hook to customize your tracer when ru... | class PopenPythonScript(LightningWork):
def on_before_run(self):
"""Called before the python script is executed."""
def on_after_run(self):
"""Called after the python script is executed."""
def configure_tracer(self) -> Tracer:
"""Override this hook to customize your tracer when ru... | for child_pid in _collect_child_process_pids(os.getpid()):
os.kill(child_pid, signal.SIGTERM)
| for child_pid in _collect_child_process_pids(os.getpid()):
os.kill(child_pid, signal.SIGTERM)
| 6 | 827 | 46 | 873 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,013 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/python/tracer.py | 191,192 | 38,200 | on_exit | TracerPythonScript | 192,195 | 192,195 | class TracerPythonScript(LightningWork):
_start_method = "spawn"
def on_before_run(self):
"""Called before the python script is executed."""
def on_after_run(self, res: Any):
"""Called after the python script is executed."""
for name in self.outputs:
setattr(self, name,... | class TracerPythonScript(LightningWork):
_start_method = "spawn"
def on_before_run(self):
"""Called before the python script is executed."""
def on_after_run(self, res: Any):
"""Called after the python script is executed."""
for name in self.outputs:
setattr(self, name,... | for child_pid in _collect_child_process_pids(os.getpid()):
os.kill(child_pid, signal.SIGTERM)
| for child_pid in _collect_child_process_pids(os.getpid()):
os.kill(child_pid, signal.SIGTERM)
| 6 | 1,723 | 44 | 1,767 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,015 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/serve/python_server.py | 106,108 | 99,112 | response_code_sample | Category | 108,112 | 108,112 | class Category(BaseModel):
category: Optional[int] = None
@staticmethod
def get_sample_data() -> Dict[Any, Any]:
return {"category": 463}
@staticmethod
def response_code_sample() -> str:
FILL_FUNC_BODY | class Category(BaseModel):
category: Optional[int] = None
@staticmethod
def get_sample_data() -> Dict[Any, Any]:
return {"category": 463}
@staticmethod
def response_code_sample() -> str:
FILL_FUNC_BODY | return """print("Predicted category is: ", response.json()["category"])
"""
| return """print("Predicted category is: ", response.json()["category"])
"""
| 7 | 81 | 28 | 109 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
1,016 | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning | /home/hieuvd/dung_repo/raw/stars_01/Lightning-AI_pytorch-lightning/pytorch-lightning/src/lightning/app/components/serve/python_server.py | 91,93 | 65,99 | response_code_sample | Image | 93,99 | 93,99 | class Image(BaseModel):
image: Optional[str] = None
@staticmethod
def get_sample_data() -> Dict[Any, Any]:
url = "https://raw.githubusercontent.com/Lightning-AI/LAI-Triton-Server-Component/main/catimage.png"
img = requests.get(url).content
img = base64.b64encode(img).decode("UTF-8")... | class Image(BaseModel):
image: Optional[str] = None
@staticmethod
def get_sample_data() -> Dict[Any, Any]:
url = "https://raw.githubusercontent.com/Lightning-AI/LAI-Triton-Server-Component/main/catimage.png"
img = requests.get(url).content
img = base64.b64encode(img).decode("UTF-8")... | return """img = response.json()["image"]
img = base64.b64decode(img.encode("utf-8"))
Path("response.png").write_bytes(img)
"""
| return """img = response.json()["image"]
img = base64.b64decode(img.encode("utf-8"))
Path("response.png").write_bytes(img)
"""
| 9 | 347 | 56 | 403 | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright The Lightning AI team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.