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
9,080
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/data_loaders/multitask_epoch_sampler.py
61,62
49,66
get_task_proportions
WeightedSampler
62,66
62,66
@MultiTaskEpochSampler.register("weighted") class WeightedSampler(MultiTaskEpochSampler): """ Returns a weighted distribution over datasets at every epoch, where every task has a weight. Registered as a `MultiTaskEpochSampler` with name "weighted". """ def __init__(self, weights: Dict[str, flo...
@MultiTaskEpochSampler.register("weighted") class WeightedSampler(MultiTaskEpochSampler): """ Returns a weighted distribution over datasets at every epoch, where every task has a weight. Registered as a `MultiTaskEpochSampler` with name "weighted". """ def __init__(self, weights: Dict[str, flo...
total = sum(self.weights[task] for task in data_loaders.keys()) return {task: self.weights[task] / total for task in data_loaders.keys()}
total = sum(self.weights[task] for task in data_loaders.keys()) return {task: self.weights[task] / total for task in data_loaders.keys()}
16
149
55
204
from typing import Any, Dict, Mapping from allennlp.common.registrable import Registrable from allennlp.data.data_loaders.data_loader import DataLoader class MultiTaskEpochSampler(Registrable): """ A class that determines with what proportion each dataset should be sampled for a given epoch. This is used...
from typing import Any, Dict, Mapping from allennlp.common.registrable import Registrable from allennlp.data.data_loaders.data_loader import DataLoader class MultiTaskEpochSampler(Registrable): """ A class that determines with what proportion each dataset should be sampled for a given epoch. This is used...
9,084
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/dataset_readers/interleaving_dataset_reader.py
91,92
18,122
_read
InterleavingDatasetReader
92,116
92,116
@DatasetReader.register("interleaving") class InterleavingDatasetReader(DatasetReader): """ A `DatasetReader` that wraps multiple other dataset readers, and interleaves their instances, adding a `MetadataField` to indicate the provenance of each instance. Unlike most of our other dataset readers, h...
@DatasetReader.register("interleaving") class InterleavingDatasetReader(DatasetReader): """ A `DatasetReader` that wraps multiple other dataset readers, and interleaves their instances, adding a `MetadataField` to indicate the provenance of each instance. Unlike most of our other dataset readers, h...
if isinstance(file_path, str): try: file_paths = json.loads(file_path) except json.JSONDecodeError: raise ConfigurationError( "the file_path for the InterleavingDatasetReader " "needs to be a JSON-serialized dictiona...
if isinstance(file_path, str): try: file_paths = json.loads(file_path) except json.JSONDecodeError: raise ConfigurationError( "the file_path for the InterleavingDatasetReader " "needs to be a JSON-serialized dictiona...
70
1,012
273
1,285
from typing import Dict, Mapping, Iterable, Union, Optional import json from allennlp.common.checks import ConfigurationError from allennlp.data.dataset_readers.dataset_reader import ( DatasetReader, PathOrStr, WorkerInfo, DistributedInfo, ) from allennlp.data.fields import MetadataField from allennlp...
from typing import Dict, Mapping, Iterable, Union, Optional import json from allennlp.common.checks import ConfigurationError from allennlp.data.dataset_readers.dataset_reader import ( DatasetReader, PathOrStr, WorkerInfo, DistributedInfo, ) from allennlp.data.fields import MetadataField from allennlp...
9,085
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/dataset_readers/multitask.py
36,42
12,47
read
MultiTaskDatasetReader
42,47
42,47
@DatasetReader.register("multitask") class MultiTaskDatasetReader(DatasetReader): """ This `DatasetReader` simply collects a dictionary of other `DatasetReaders`. It is designed for a different class (the `MultiTaskDataLoader`) to actually read from each of the underlying dataset readers, and so this r...
@DatasetReader.register("multitask") class MultiTaskDatasetReader(DatasetReader): """ This `DatasetReader` simply collects a dictionary of other `DatasetReaders`. It is designed for a different class (the `MultiTaskDataLoader`) to actually read from each of the underlying dataset readers, and so this r...
if force_task is None: raise RuntimeError("This class is not designed to be called like this.") return self.readers[force_task].read(file_paths)
if force_task is None: raise RuntimeError("This class is not designed to be called like this.") return self.readers[force_task].read(file_paths)
17
394
51
445
from os import PathLike from typing import Dict, Iterator, Union, Optional from allennlp.data.instance import Instance from allennlp.data.dataset_readers.dataset_reader import ( DatasetReader, WorkerInfo, DatasetReaderInput, ) @DatasetReader.register("multitask") class MultiTaskDatasetReader(DatasetReade...
from os import PathLike from typing import Dict, Iterator, Union, Optional from allennlp.data.instance import Instance from allennlp.data.dataset_readers.dataset_reader import ( DatasetReader, WorkerInfo, DatasetReaderInput, ) @DatasetReader.register("multitask") class MultiTaskDatasetReader(DatasetReade...
9,086
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/dataset_readers/multitask.py
71,72
47,80
text_to_instance
_MultitaskDatasetReaderShim
72,78
72,78
@DatasetReader.register("multitask_shim") class _MultitaskDatasetReaderShim(DatasetReader): """This dataset reader wraps another dataset reader and adds the name of the "task" into each instance as a metadata field. You should not have to use this yourself.""" def __init__(self, inner: DatasetReader, head:...
@DatasetReader.register("multitask_shim") class _MultitaskDatasetReaderShim(DatasetReader): """This dataset reader wraps another dataset reader and adds the name of the "task" into each instance as a metadata field. You should not have to use this yourself.""" def __init__(self, inner: DatasetReader, head:...
from allennlp.data.fields import MetadataField instance = self.inner.text_to_instance(*inputs) instance.add_field("task", MetadataField(self.head)) return instance
from allennlp.data.fields import MetadataField instance = self.inner.text_to_instance(*inputs) instance.add_field("task", MetadataField(self.head)) return instance
11
326
61
387
from os import PathLike from typing import Dict, Iterator, Union, Optional from allennlp.data.instance import Instance from allennlp.data.dataset_readers.dataset_reader import ( DatasetReader, WorkerInfo, DatasetReaderInput, ) @DatasetReader.register("multitask") class MultiTaskDatasetReader(DatasetReade...
from os import PathLike from typing import Dict, Iterator, Union, Optional from allennlp.data.instance import Instance from allennlp.data.dataset_readers.dataset_reader import ( DatasetReader, WorkerInfo, DatasetReaderInput, ) @DatasetReader.register("multitask") class MultiTaskDatasetReader(DatasetReade...
9,087
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/dataset_readers/sequence_tagging.py
65,66
17,106
_read
SequenceTaggingDatasetReader
66,86
66,86
@DatasetReader.register("sequence_tagging") class SequenceTaggingDatasetReader(DatasetReader): """ Reads instances from a pretokenised file where each line is in the following format: ``` WORD###TAG [TAB] WORD###TAG [TAB] ..... \n ``` and converts it into a `Dataset` suitable for sequence tagg...
@DatasetReader.register("sequence_tagging") class SequenceTaggingDatasetReader(DatasetReader): """ Reads instances from a pretokenised file where each line is in the following format: ``` WORD###TAG [TAB] WORD###TAG [TAB] ..... \n ``` and converts it into a `Dataset` suitable for sequence tagg...
# if `file_path` is a URL, redirect to the cache file_path = cached_path(file_path) with open(file_path, "r") as data_file: logger.info("Reading instances from lines in file at: %s", file_path) for line in self.shard_iterable(data_file): line = line.strip...
# if `file_path` is a URL, redirect to the cache file_path = cached_path(file_path) with open(file_path, "r") as data_file: logger.info("Reading instances from lines in file at: %s", file_path) for line in self.shard_iterable(data_file): line = line.strip...
71
837
237
1,074
from typing import Dict, List, Any import logging from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.fields import TextField, SequenceLabelField, MetadataField, Field from allennlp.data.instance import Instance from allennlp.dat...
from typing import Dict, List, Any import logging from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.fields import TextField, SequenceLabelField, MetadataField, Field from allennlp.data.instance import Instance from allennlp.dat...
9,088
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/dataset_readers/sharded_dataset_reader.py
59,60
16,87
_read
ShardedDatasetReader
60,87
60,87
@DatasetReader.register("sharded") class ShardedDatasetReader(DatasetReader): """ Wraps another dataset reader and uses it to read from multiple input files. Note that in this case the `file_path` passed to `read()` should either be a glob path or a path or URL to an archive file ('.zip' or '.tar.gz')....
@DatasetReader.register("sharded") class ShardedDatasetReader(DatasetReader): """ Wraps another dataset reader and uses it to read from multiple input files. Note that in this case the `file_path` passed to `read()` should either be a glob path or a path or URL to an archive file ('.zip' or '.tar.gz')....
try: maybe_extracted_archive = cached_path(file_path, extract_archive=True) if not os.path.isdir(maybe_extracted_archive): # This isn't a directory, so `file_path` is just a file. raise ConfigurationError(f"{file_path} should be an archive or directory") ...
try: maybe_extracted_archive = cached_path(file_path, extract_archive=True) if not os.path.isdir(maybe_extracted_archive): # This isn't a directory, so `file_path` is just a file. raise ConfigurationError(f"{file_path} should be an archive or directory") ...
110
513
376
889
import glob import logging import os from typing import Iterable from allennlp.common.checks import ConfigurationError from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader, PathOrStr from allennlp.data.instance import Instance logger = logging.get...
import glob import logging import os from typing import Iterable from allennlp.common.checks import ConfigurationError from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader, PathOrStr from allennlp.data.instance import Instance logger = logging.get...
9,089
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/dataset_readers/text_classification_json.py
143,144
16,149
apply_token_indexers
TextClassificationJsonReader
144,149
144,149
@DatasetReader.register("text_classification_json") class TextClassificationJsonReader(DatasetReader): """ Reads tokens and their labels from a labeled text classification dataset. The output of `read` is a list of `Instance` s with the fields: tokens : `TextField` and label : `LabelField` ...
@DatasetReader.register("text_classification_json") class TextClassificationJsonReader(DatasetReader): """ Reads tokens and their labels from a labeled text classification dataset. The output of `read` is a list of `Instance` s with the fields: tokens : `TextField` and label : `LabelField` ...
if self._segment_sentences: for text_field in instance.fields["tokens"]: # type: ignore text_field._token_indexers = self._token_indexers else: instance.fields["tokens"]._token_indexers = self._token_indexers # type: ignore
if self._segment_sentences: for text_field in instance.fields["tokens"]: # type: ignore text_field._token_indexers = self._token_indexers else: instance.fields["tokens"]._token_indexers = self._token_indexers # type: ignore
19
1,495
83
1,578
from typing import Dict, List, Union import logging import json from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.fields import LabelField, TextField, Field, ListField from allennlp.data.instance import Instance from allennlp.da...
from typing import Dict, List, Union import logging import json from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.fields import LabelField, TextField, Field, ListField from allennlp.data.instance import Instance from allennlp.da...
9,090
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/fields/flag_field.py
18,19
7,46
get_padding_lengths
FlagField
19,21
19,21
class FlagField(Field[Any]): """ A class representing a flag, which must be constant across all instances in a batch. This will be passed to a `forward` method as a single value of whatever type you pass in. """ __slots__ = ["flag_value"] def __init__(self, flag_value: Any) -> None: se...
class FlagField(Field[Any]): """ A class representing a flag, which must be constant across all instances in a batch. This will be passed to a `forward` method as a single value of whatever type you pass in. """ __slots__ = ["flag_value"] def __init__(self, flag_value: Any) -> None: se...
return {}
return {}
2
409
7
416
from typing import Any, Dict, List from allennlp.data.fields.field import Field class FlagField(Field[Any]): """ A class representing a flag, which must be constant across all instances in a batch. This will be passed to a `forward` method as a single value of whatever type you pass in. """ __s...
from typing import Any, Dict, List from allennlp.data.fields.field import Field class FlagField(Field[Any]): """ A class representing a flag, which must be constant across all instances in a batch. This will be passed to a `forward` method as a single value of whatever type you pass in. """ __s...
9,091
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/fields/list_field.py
95,96
10,116
empty_field
ListField
96,105
96,105
class ListField(SequenceField[DataArray]): """ A `ListField` is a list of other fields. You would use this to represent, e.g., a list of answer options that are themselves `TextFields`. This field will get converted into a tensor that has one more mode than the items in the list. If this is a list...
class ListField(SequenceField[DataArray]): """ A `ListField` is a list of other fields. You would use this to represent, e.g., a list of answer options that are themselves `TextFields`. This field will get converted into a tensor that has one more mode than the items in the list. If this is a list...
# Our "empty" list field will actually have a single field in the list, so that we can # correctly construct nested lists. For example, if we have a type that is # `ListField[ListField[LabelField]]`, we need the top-level `ListField` to know to # construct a `ListField[LabelField]` when...
# Our "empty" list field will actually have a single field in the list, so that we can # correctly construct nested lists. For example, if we have a type that is # `ListField[ListField[LabelField]]`, we need the top-level `ListField` to know to # construct a `ListField[LabelField]` when...
91
1,303
182
1,485
from typing import Dict, List, Iterator, Sequence, Any from allennlp.data.fields.field import DataArray, Field from allennlp.data.vocabulary import Vocabulary from allennlp.data.fields.sequence_field import SequenceField from allennlp.common.util import pad_sequence_to_length class ListField(SequenceField[DataArray...
from typing import Dict, List, Iterator, Sequence, Any from allennlp.data.fields.field import DataArray, Field from allennlp.data.vocabulary import Vocabulary from allennlp.data.fields.sequence_field import SequenceField from allennlp.common.util import pad_sequence_to_length class ListField(SequenceField[DataArray...
9,092
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/fields/metadata_field.py
65,66
7,69
human_readable_repr
MetadataField
66,69
66,69
class MetadataField(Field[DataArray], Mapping[str, Any]): """ A `MetadataField` is a `Field` that does not get converted into tensors. It just carries side information that might be needed later on, for computing some third-party metric, or outputting debugging information, or whatever else you need. ...
class MetadataField(Field[DataArray], Mapping[str, Any]): """ A `MetadataField` is a `Field` that does not get converted into tensors. It just carries side information that might be needed later on, for computing some third-party metric, or outputting debugging information, or whatever else you need. ...
if hasattr(self.metadata, "human_readable_repr"): return self.metadata.human_readable_repr() return self.metadata
if hasattr(self.metadata, "human_readable_repr"): return self.metadata.human_readable_repr() return self.metadata
7
592
44
636
from typing import Any, Dict, List, Mapping from allennlp.data.fields.field import DataArray, Field class MetadataField(Field[DataArray], Mapping[str, Any]): """ A `MetadataField` is a `Field` that does not get converted into tensors. It just carries side information that might be needed later on, for ...
from typing import Any, Dict, List, Mapping from allennlp.data.fields.field import DataArray, Field class MetadataField(Field[DataArray], Mapping[str, Any]): """ A `MetadataField` is a `Field` that does not get converted into tensors. It just carries side information that might be needed later on, for ...
9,093
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/fields/sequence_field.py
14,15
4,22
sequence_length
SequenceField
18,20
15,20
class SequenceField(Field[DataArray]): """ A `SequenceField` represents a sequence of things. This class just adds a method onto `Field`: :func:`sequence_length`. It exists so that `SequenceLabelField`, `IndexField` and other similar `Fields` can have a single type to require, with a consistent API, w...
class SequenceField(Field[DataArray]): """ A `SequenceField` represents a sequence of things. This class just adds a method onto `Field`: :func:`sequence_length`. It exists so that `SequenceLabelField`, `IndexField` and other similar `Fields` can have a single type to require, with a consistent API, w...
raise NotImplementedError
""" How many elements are there in this sequence? """ raise NotImplementedError
2
195
11
206
from allennlp.data.fields.field import DataArray, Field class SequenceField(Field[DataArray]): """ A `SequenceField` represents a sequence of things. This class just adds a method onto `Field`: :func:`sequence_length`. It exists so that `SequenceLabelField`, `IndexField` and other similar `Fields` c...
from allennlp.data.fields.field import DataArray, Field class SequenceField(Field[DataArray]): """ A `SequenceField` represents a sequence of things. This class just adds a method onto `Field`: :func:`sequence_length`. It exists so that `SequenceLabelField`, `IndexField` and other similar `Fields` c...
9,094
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/instance.py
88,91
8,123
as_tensor_dict
Instance
99,105
91,105
class Instance(Mapping[str, Field]): """ An `Instance` is a collection of :class:`~allennlp.data.fields.field.Field` objects, specifying the inputs and outputs to some model. We don't make a distinction between inputs and outputs here, though - all operations are done on all fields, and when we ret...
class Instance(Mapping[str, Field]): """ An `Instance` is a collection of :class:`~allennlp.data.fields.field.Field` objects, specifying the inputs and outputs to some model. We don't make a distinction between inputs and outputs here, though - all operations are done on all fields, and when we ret...
padding_lengths = padding_lengths or self.get_padding_lengths() tensors = {} for field_name, field in self.fields.items(): tensors[field_name] = field.as_tensor(padding_lengths[field_name]) return tensors
""" Pads each `Field` in this instance to the lengths given in `padding_lengths` (which is keyed by field name, then by padding key, the same as the return value in :func:`get_padding_lengths`), returning a list of torch tensors for each field. If `padding_lengths` is omitted, w...
18
1,303
79
1,382
from typing import Dict, MutableMapping, Mapping from allennlp.data.fields.field import DataArray, Field from allennlp.data.vocabulary import Vocabulary from allennlp.common.util import JsonDict class Instance(Mapping[str, Field]): """ An `Instance` is a collection of :class:`~allennlp.data.fields.field.Fiel...
from typing import Dict, MutableMapping, Mapping from allennlp.data.fields.field import DataArray, Field from allennlp.data.vocabulary import Vocabulary from allennlp.common.util import JsonDict class Instance(Mapping[str, Field]): """ An `Instance` is a collection of :class:`~allennlp.data.fields.field.Fiel...
9,095
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/samplers/batch_sampler.py
11,12
7,20
get_num_batches
BatchSampler
12,14
12,14
class BatchSampler(Registrable): def get_batch_indices(self, instances: Sequence[Instance]) -> Iterable[List[int]]: raise NotImplementedError def get_num_batches(self, instances: Sequence[Instance]) -> int: FILL_FUNC_BODY def get_batch_size(self) -> Optional[int]: """ Not all `BatchS...
class BatchSampler(Registrable): def get_batch_indices(self, instances: Sequence[Instance]) -> Iterable[List[int]]: raise NotImplementedError def get_num_batches(self, instances: Sequence[Instance]) -> int: FILL_FUNC_BODY def get_batch_size(self) -> Optional[int]: """ Not all `BatchS...
raise NotImplementedError
raise NotImplementedError
2
139
11
150
from typing import List, Iterable, Sequence, Optional from allennlp.common.registrable import Registrable from allennlp.data.instance import Instance class BatchSampler(Registrable): def get_batch_indices(self, instances: Sequence[Instance]) -> Iterable[List[int]]: raise NotImplementedError def get_...
from typing import List, Iterable, Sequence, Optional from allennlp.common.registrable import Registrable from allennlp.data.instance import Instance class BatchSampler(Registrable): def get_batch_indices(self, instances: Sequence[Instance]) -> Iterable[List[int]]: raise NotImplementedError def get_...
9,096
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/samplers/bucket_batch_sampler.py
15,16
1,173
add_noise_to_value
16,21
16,21
import logging import math from typing import List, Iterable, Tuple, Sequence, Optional import random from allennlp.common.checks import ConfigurationError from allennlp.common.util import lazy_groups_of from allennlp.data.instance import Instance from allennlp.data.samplers.batch_sampler import BatchSampler logger ...
import logging import math from typing import List, Iterable, Tuple, Sequence, Optional import random from allennlp.common.checks import ConfigurationError from allennlp.common.util import lazy_groups_of from allennlp.data.instance import Instance from allennlp.data.samplers.batch_sampler import BatchSampler logger ...
noise_value = value * noise_param noise = random.uniform(-noise_value, noise_value) return value + noise
noise_value = value * noise_param noise = random.uniform(-noise_value, noise_value) return value + noise
13
1,981
40
2,021
import logging import math from typing import List, Iterable, Tuple, Sequence, Optional import random from allennlp.common.checks import ConfigurationError from allennlp.common.util import lazy_groups_of from allennlp.data.instance import Instance from allennlp.data.samplers.batch_sampler import BatchSampler logger ...
import logging import math from typing import List, Iterable, Tuple, Sequence, Optional import random from allennlp.common.checks import ConfigurationError from allennlp.common.util import lazy_groups_of from allennlp.data.instance import Instance from allennlp.data.samplers.batch_sampler import BatchSampler logger ...
9,097
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/samplers/bucket_batch_sampler.py
82,85
21,173
_argsort_by_padding
BucketBatchSampler
90,116
85,116
@BatchSampler.register("bucket") class BucketBatchSampler(BatchSampler): """ An sampler which by default, argsorts batches with respect to the maximum input lengths `per batch`. You can provide a list of field names and padding keys (or pass none, in which case they will be inferred) which the dataset w...
@BatchSampler.register("bucket") class BucketBatchSampler(BatchSampler): """ An sampler which by default, argsorts batches with respect to the maximum input lengths `per batch`. You can provide a list of field names and padding keys (or pass none, in which case they will be inferred) which the dataset w...
if not self.sorting_keys: logger.info("No sorting keys given; trying to guess a good one") self._guess_sorting_keys(instances) logger.info(f"Using {self.sorting_keys} as the sorting keys") instances_with_lengths = [] for instance in instances: # Ma...
""" Argsorts the instances by their padding lengths, using the keys in `sorting_keys` (in the order in which they are provided). `sorting_keys` is a list of `(field_name, padding_key)` tuples. """ if not self.sorting_keys: logger.info("No sorting keys given; t...
102
1,495
391
1,886
import logging import math from typing import List, Iterable, Tuple, Sequence, Optional import random from allennlp.common.checks import ConfigurationError from allennlp.common.util import lazy_groups_of from allennlp.data.instance import Instance from allennlp.data.samplers.batch_sampler import BatchSampler logger ...
import logging import math from typing import List, Iterable, Tuple, Sequence, Optional import random from allennlp.common.checks import ConfigurationError from allennlp.common.util import lazy_groups_of from allennlp.data.instance import Instance from allennlp.data.samplers.batch_sampler import BatchSampler logger ...
9,098
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/samplers/max_tokens_batch_sampler.py
62,67
16,112
_lazy_groups_of_max_size
MaxTokensBatchSampler
72,98
67,98
@BatchSampler.register("max_tokens_sampler") class MaxTokensBatchSampler(BucketBatchSampler): """ An sampler which by default, argsorts batches with respect to the maximum input lengths `per batch`. Batches are then created such that the number of tokens in a batch does not exceed the given maximum numb...
@BatchSampler.register("max_tokens_sampler") class MaxTokensBatchSampler(BucketBatchSampler): """ An sampler which by default, argsorts batches with respect to the maximum input lengths `per batch`. Batches are then created such that the number of tokens in a batch does not exceed the given maximum numb...
cur_max_size = 0 group: List[A] = [] iterator = iter(iterable) size_iter = iter(sizes) for item, size in zip(iterator, size_iter): if size > self.max_tokens: logger.warning( "Found instance of size %d, which is bigger than the exp...
""" Takes an `iterable` of data and an iterable `sizes` of the same length which represents the sizes of each corresponding item in `iterable`. The instances from `iterable` are batched such that the total size of the batch as computed from `sizes` does not exceed `max_size`. """...
74
963
243
1,206
import logging import random from typing import List, Iterable, Iterator, TypeVar, Sequence from allennlp.data.instance import Instance from allennlp.data.samplers.batch_sampler import BatchSampler from allennlp.data.samplers.bucket_batch_sampler import BucketBatchSampler logger = logging.getLogger(__name__) A = T...
import logging import random from typing import List, Iterable, Iterator, TypeVar, Sequence from allennlp.data.instance import Instance from allennlp.data.samplers.batch_sampler import BatchSampler from allennlp.data.samplers.bucket_batch_sampler import BucketBatchSampler logger = logging.getLogger(__name__) A = T...
9,099
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/token_indexers/single_id_token_indexer.py
76,79
13,119
tokens_to_indices
SingleIdTokenIndexer
79,93
79,93
@TokenIndexer.register("single_id") class SingleIdTokenIndexer(TokenIndexer): """ This :class:`TokenIndexer` represents tokens as single integers. Registered as a `TokenIndexer` with name "single_id". # Parameters namespace : `Optional[str]`, optional (default=`"tokens"`) We will use this...
@TokenIndexer.register("single_id") class SingleIdTokenIndexer(TokenIndexer): """ This :class:`TokenIndexer` represents tokens as single integers. Registered as a `TokenIndexer` with name "single_id". # Parameters namespace : `Optional[str]`, optional (default=`"tokens"`) We will use this...
indices: List[int] = [] for token in itertools.chain(self._start_tokens, tokens, self._end_tokens): text = self._get_feature_value(token) if self.namespace is None: # We could have a check here that `text` is an int; not sure it's worth it. indice...
indices: List[int] = [] for token in itertools.chain(self._start_tokens, tokens, self._end_tokens): text = self._get_feature_value(token) if self.namespace is None: # We could have a check here that `text` is an int; not sure it's worth it. indice...
49
1,295
169
1,464
from typing import Dict, List, Optional, Any import itertools from allennlp.data.vocabulary import Vocabulary from allennlp.data.tokenizers import Token from allennlp.data.token_indexers.token_indexer import TokenIndexer, IndexedTokenList _DEFAULT_VALUE = "THIS IS A REALLY UNLIKELY VALUE THAT HAS TO BE A STRING" ...
from typing import Dict, List, Optional, Any import itertools from allennlp.data.vocabulary import Vocabulary from allennlp.data.tokenizers import Token from allennlp.data.token_indexers.token_indexer import TokenIndexer, IndexedTokenList _DEFAULT_VALUE = "THIS IS A REALLY UNLIKELY VALUE THAT HAS TO BE A STRING" ...
9,100
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/tokenizers/character_tokenizer.py
57,58
8,93
tokenize
CharacterTokenizer
58,80
58,80
@Tokenizer.register("character") class CharacterTokenizer(Tokenizer): """ A `CharacterTokenizer` splits strings into character tokens. Registered as a `Tokenizer` with name "character". # Parameters byte_encoding : `str`, optional (default=`None`) If not `None`, we will use this encoding ...
@Tokenizer.register("character") class CharacterTokenizer(Tokenizer): """ A `CharacterTokenizer` splits strings into character tokens. Registered as a `Tokenizer` with name "character". # Parameters byte_encoding : `str`, optional (default=`None`) If not `None`, we will use this encoding ...
if self._lowercase_characters: text = text.lower() if self._byte_encoding is not None: # We add 1 here so that we can still use 0 for masking, no matter what bytes we get out # of this. tokens = [Token(text_id=c + 1) for c in text.encode(self._byte_encodin...
if self._lowercase_characters: text = text.lower() if self._byte_encoding is not None: # We add 1 here so that we can still use 0 for masking, no matter what bytes we get out # of this. tokens = [Token(text_id=c + 1) for c in text.encode(self._byte_encodin...
88
809
290
1,099
from typing import List, Union, Dict, Any from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer import Tokenizer @Tokenizer.register("character") class CharacterTokenizer(Tokenizer): """ A `CharacterTokenizer` splits strings into character tokens. Registered as ...
from typing import List, Union, Dict, Any from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer import Tokenizer @Tokenizer.register("character") class CharacterTokenizer(Tokenizer): """ A `CharacterTokenizer` splits strings into character tokens. Registered as ...
9,101
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/tokenizers/letters_digits_tokenizer.py
18,19
9,22
tokenize
LettersDigitsTokenizer
19,22
19,22
@Tokenizer.register("letters_digits") class LettersDigitsTokenizer(Tokenizer): """ A `Tokenizer` which keeps runs of (unicode) letters and runs of digits together, while every other non-whitespace character becomes a separate word. Registered as a `Tokenizer` with name "letters_digits". """ de...
@Tokenizer.register("letters_digits") class LettersDigitsTokenizer(Tokenizer): """ A `Tokenizer` which keeps runs of (unicode) letters and runs of digits together, while every other non-whitespace character becomes a separate word. Registered as a `Tokenizer` with name "letters_digits". """ de...
# We use the [^\W\d_] pattern as a trick to match unicode letters tokens = [Token(m.group(), idx=m.start()) for m in re.finditer(r"[^\W\d_]+|\d+|\S", text)] return tokens
# We use the [^\W\d_] pattern as a trick to match unicode letters tokens = [Token(m.group(), idx=m.start()) for m in re.finditer(r"[^\W\d_]+|\d+|\S", text)] return tokens
24
119
74
193
import re from typing import List from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer import Tokenizer @Tokenizer.register("letters_digits") class LettersDigitsTokenizer(Tokenizer): """ A `Tokenizer` which keeps runs of (unicode) letters and runs of digits together...
import re from typing import List from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer import Tokenizer @Tokenizer.register("letters_digits") class LettersDigitsTokenizer(Tokenizer): """ A `Tokenizer` which keeps runs of (unicode) letters and runs of digits together...
9,102
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/tokenizers/token_class.py
114,115
1,127
show_token
115,127
115,127
from dataclasses import dataclass from typing import Optional @dataclass(init=False, repr=False) class Token: """ A simple token representation, keeping track of the token's text, offset in the passage it was taken from, POS tag, dependency relation, and similar information. These fields match spacy's ...
from dataclasses import dataclass from typing import Optional @dataclass(init=False, repr=False) class Token: """ A simple token representation, keeping track of the token's text, offset in the passage it was taken from, POS tag, dependency relation, and similar information. These fields match spacy's ...
return ( f"{token.text} " f"(idx: {token.idx}) " f"(idx_end: {token.idx_end}) " f"(lemma: {token.lemma_}) " f"(pos: {token.pos_}) " f"(tag: {token.tag_}) " f"(dep: {token.dep_}) " f"(ent_type: {token.ent_type_}) " f"(text_id: {token.text_id}) "...
return ( f"{token.text} " f"(idx: {token.idx}) " f"(idx_end: {token.idx_end}) " f"(lemma: {token.lemma_}) " f"(pos: {token.pos_}) " f"(tag: {token.tag_}) " f"(dep: {token.dep_}) " f"(ent_type: {token.ent_type_}) " f"(text_id: {token.text_id}) "...
32
1,114
158
1,272
from dataclasses import dataclass from typing import Optional @dataclass(init=False, repr=False) class Token: """ A simple token representation, keeping track of the token's text, offset in the passage it was taken from, POS tag, dependency relation, and similar information. These fields match spacy's ...
from dataclasses import dataclass from typing import Optional @dataclass(init=False, repr=False) class Token: """ A simple token representation, keeping track of the token's text, offset in the passage it was taken from, POS tag, dependency relation, and similar information. These fields match spacy's ...
9,103
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/tokenizers/token_class.py
104,105
5,114
ensure_text
Token
108,114
105,114
@dataclass(init=False, repr=False) class Token: """ A simple token representation, keeping track of the token's text, offset in the passage it was taken from, POS tag, dependency relation, and similar information. These fields match spacy's exactly, so we can just use a spacy token for this. # Par...
@dataclass(init=False, repr=False) class Token: """ A simple token representation, keeping track of the token's text, offset in the passage it was taken from, POS tag, dependency relation, and similar information. These fields match spacy's exactly, so we can just use a spacy token for this. # Par...
if self.text is None: raise ValueError("Unexpected null text for token") else: return self.text
""" Return the `text` field, raising an exception if it's `None`. """ if self.text is None: raise ValueError("Unexpected null text for token") else: return self.text
13
1,047
41
1,088
from dataclasses import dataclass from typing import Optional @dataclass(init=False, repr=False) class Token: """ A simple token representation, keeping track of the token's text, offset in the passage it was taken from, POS tag, dependency relation, and similar information. These fields match spacy's ...
from dataclasses import dataclass from typing import Optional @dataclass(init=False, repr=False) class Token: """ A simple token representation, keeping track of the token's text, offset in the passage it was taken from, POS tag, dependency relation, and similar information. These fields match spacy's ...
9,104
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/tokenizers/tokenizer.py
77,78
11,82
num_special_tokens_for_pair
Tokenizer
81,82
78,82
class Tokenizer(Registrable): """ A `Tokenizer` splits strings of text into tokens. Typically, this either splits text into word tokens or character tokens, and those are the two tokenizer subclasses we have implemented here, though you could imagine wanting to do other kinds of tokenization for struct...
class Tokenizer(Registrable): """ A `Tokenizer` splits strings of text into tokens. Typically, this either splits text into word tokens or character tokens, and those are the two tokenizer subclasses we have implemented here, though you could imagine wanting to do other kinds of tokenization for struct...
return 0
""" Returns the number of special tokens added for a pair of sequences. """ return 0
2
692
6
698
from typing import List, Optional import logging from allennlp.common import Registrable from allennlp.data.tokenizers.token_class import Token logger = logging.getLogger(__name__) class Tokenizer(Registrable): """ A `Tokenizer` splits strings of text into tokens. Typically, this either splits text into ...
from typing import List, Optional import logging from allennlp.common import Registrable from allennlp.data.tokenizers.token_class import Token logger = logging.getLogger(__name__) class Tokenizer(Registrable): """ A `Tokenizer` splits strings of text into tokens. Typically, this either splits text into ...
9,105
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/data/tokenizers/whitespace_tokenizer.py
22,23
8,27
tokenize
WhitespaceTokenizer
23,25
23,25
@Tokenizer.register("whitespace") @Tokenizer.register("just_spaces") class WhitespaceTokenizer(Tokenizer): """ A `Tokenizer` that assumes you've already done your own tokenization somehow and have separated the tokens by spaces. We just split the input string on whitespace and return the resulting list...
@Tokenizer.register("whitespace") @Tokenizer.register("just_spaces") class WhitespaceTokenizer(Tokenizer): """ A `Tokenizer` that assumes you've already done your own tokenization somehow and have separated the tokens by spaces. We just split the input string on whitespace and return the resulting list...
return [Token(t) for t in text.split()]
return [Token(t) for t in text.split()]
6
214
19
233
from typing import List, Dict, Any from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer import Tokenizer @Tokenizer.register("whitespace") @Tokenizer.register("just_spaces") class WhitespaceTokenizer(Tokenizer): """ A `Tokenizer` that assumes you've already done you...
from typing import List, Dict, Any from allennlp.data.tokenizers.token_class import Token from allennlp.data.tokenizers.tokenizer import Tokenizer @Tokenizer.register("whitespace") @Tokenizer.register("just_spaces") class WhitespaceTokenizer(Tokenizer): """ A `Tokenizer` that assumes you've already done you...
9,106
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/evaluation/serializers/serializers.py
61,62
54,107
_to_params
SimpleSerializer
62,64
62,64
@Serializer.register("simple") class SimpleSerializer(Serializer): """ Very simple serializer. Only sanitizes the batches and outputs. Will use a passed serializer function for the outputs if it exists. """ def _to_params(self) -> Dict[str, Any]: FILL_FUNC_BODY def __call__( self, ...
@Serializer.register("simple") class SimpleSerializer(Serializer): """ Very simple serializer. Only sanitizes the batches and outputs. Will use a passed serializer function for the outputs if it exists. """ def _to_params(self) -> Dict[str, Any]: FILL_FUNC_BODY def __call__( self, ...
return {"type": "simple"}
return {"type": "simple"}
3
460
12
472
from typing import Optional, Dict, Any, Callable import logging import json from allennlp.common.util import sanitize from allennlp.data.fields import TensorField from allennlp.common import Registrable from allennlp.data import DataLoader logger = logging.getLogger(__name__) class Serializer(Registrable): """ ...
from typing import Optional, Dict, Any, Callable import logging import json from allennlp.common.util import sanitize from allennlp.data.fields import TensorField from allennlp.common import Registrable from allennlp.data import DataLoader logger = logging.getLogger(__name__) class Serializer(Registrable): """ ...
9,107
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/fairness/bias_mitigator_applicator.py
98,99
21,103
_maybe_warn_for_unseparable_batches
BiasMitigatorApplicator
99,101
99,101
@Model.register("bias_mitigator_applicator") class BiasMitigatorApplicator(Model): """ Wrapper class to apply bias mitigation to any pretrained Model. # Parameters vocab : `Vocabulary` Vocabulary of base model. base_model : `Model` Base model for which to mitigate biases. bias_...
@Model.register("bias_mitigator_applicator") class BiasMitigatorApplicator(Model): """ Wrapper class to apply bias mitigation to any pretrained Model. # Parameters vocab : `Vocabulary` Vocabulary of base model. base_model : `Model` Base model for which to mitigate biases. bias_...
return self.base_model._maybe_warn_for_unseparable_batches(*args, **kwargs)
return self.base_model._maybe_warn_for_unseparable_batches(*args, **kwargs)
3
956
30
986
""" A Model wrapper to mitigate biases in contextual embeddings during finetuning on a downstream task and test time. Based on: Dev, S., Li, T., Phillips, J.M., & Srikumar, V. (2020). [On Measuring and Mitigating Biased Inferences of Word Embeddings] (https://api.semanticscholar.org/CorpusID:201670701). ArXiv, abs/190...
""" A Model wrapper to mitigate biases in contextual embeddings during finetuning on a downstream task and test time. Based on: Dev, S., Li, T., Phillips, J.M., & Srikumar, V. (2020). [On Measuring and Mitigating Biased Inferences of Word Embeddings] (https://api.semanticscholar.org/CorpusID:201670701). ArXiv, abs/190...
9,108
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/interpret/attackers/attacker.py
24,32
8,60
attack_from_json
Attacker
59,60
32,60
class Attacker(Registrable): """ An `Attacker` will modify an input (e.g., add or delete tokens) to try to change an AllenNLP Predictor's output in a desired manner (e.g., make it incorrect). """ def __init__(self, predictor: Predictor) -> None: self.predictor = predictor def initializ...
class Attacker(Registrable): """ An `Attacker` will modify an input (e.g., add or delete tokens) to try to change an AllenNLP Predictor's output in a desired manner (e.g., make it incorrect). """ def __init__(self, predictor: Predictor) -> None: self.predictor = predictor def initializ...
raise NotImplementedError()
""" This function finds a modification to the input text that would change the model's prediction in some desired manner (e.g., an adversarial attack). # Parameters inputs : `JsonDict` The input you want to attack (the same as the argument to a Predictor, e.g., ...
2
552
10
562
from typing import List from allennlp.common import Registrable from allennlp.common.util import JsonDict from allennlp.predictors import Predictor class Attacker(Registrable): """ An `Attacker` will modify an input (e.g., add or delete tokens) to try to change an AllenNLP Predictor's output in a desired...
from typing import List from allennlp.common import Registrable from allennlp.common.util import JsonDict from allennlp.predictors import Predictor class Attacker(Registrable): """ An `Attacker` will modify an input (e.g., add or delete tokens) to try to change an AllenNLP Predictor's output in a desired...
9,109
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/interpret/attackers/utils.py
5,8
1,50
get_fields_to_compare
25,40
8,40
from allennlp.common.util import JsonDict from allennlp.data import Instance def get_fields_to_compare( inputs: JsonDict, instance: Instance, input_field_to_attack: str ) -> JsonDict: FILL_FUNC_BODYdef instance_has_changed(instance: Instance, fields_to_compare: JsonDict): if "clusters" in fields_to_compare: ...
from allennlp.common.util import JsonDict from allennlp.data import Instance def get_fields_to_compare( inputs: JsonDict, instance: Instance, input_field_to_attack: str ) -> JsonDict: """ Gets a list of the fields that should be checked for equality after an attack is performed. # Parameters inp...
# TODO(mattg): this really should live on the Predictor. We have some messy stuff for, e.g., # reading comprehension models, and the interpret code can't really know about the internals of # that (or at least it shouldn't now, and once we split out the reading comprehension repo, it # really *can't*). ...
""" Gets a list of the fields that should be checked for equality after an attack is performed. # Parameters inputs : `JsonDict` The input you want to attack, similar to the argument to a Predictor, e.g., predict_json(). instance : `Instance` A labeled instance that is output from ...
81
423
182
605
from allennlp.common.util import JsonDict from allennlp.data import Instance def get_fields_to_compare( inputs: JsonDict, instance: Instance, input_field_to_attack: str ) -> JsonDict: FILL_FUNC_BODYdef instance_has_changed(instance: Instance, fields_to_compare: JsonDict): if "clusters" in fields_to_compare: ...
from allennlp.common.util import JsonDict from allennlp.data import Instance def get_fields_to_compare( inputs: JsonDict, instance: Instance, input_field_to_attack: str ) -> JsonDict: """ Gets a list of the fields that should be checked for equality after an attack is performed. # Parameters inp...
9,110
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/modules/seq2seq_encoders/seq2seq_encoder.py
24,25
5,38
get_output_dim
Seq2SeqEncoder
29,31
25,31
class Seq2SeqEncoder(_EncoderBase, Registrable): """ A `Seq2SeqEncoder` is a `Module` that takes as input a sequence of vectors and returns a modified sequence of vectors. Input shape : `(batch_size, sequence_length, input_dim)`; output shape : `(batch_size, sequence_length, output_dim)`. We add t...
class Seq2SeqEncoder(_EncoderBase, Registrable): """ A `Seq2SeqEncoder` is a `Module` that takes as input a sequence of vectors and returns a modified sequence of vectors. Input shape : `(batch_size, sequence_length, input_dim)`; output shape : `(batch_size, sequence_length, output_dim)`. We add t...
raise NotImplementedError
""" Returns the dimension of each vector in the sequence output by this `Seq2SeqEncoder`. This is `not` the shape of the returned tensor, but the last element of that shape. """ raise NotImplementedError
2
408
11
419
from allennlp.modules.encoder_base import _EncoderBase from allennlp.common import Registrable class Seq2SeqEncoder(_EncoderBase, Registrable): """ A `Seq2SeqEncoder` is a `Module` that takes as input a sequence of vectors and returns a modified sequence of vectors. Input shape : `(batch_size, sequence_l...
from allennlp.modules.encoder_base import _EncoderBase from allennlp.common import Registrable class Seq2SeqEncoder(_EncoderBase, Registrable): """ A `Seq2SeqEncoder` is a `Module` that takes as input a sequence of vectors and returns a modified sequence of vectors. Input shape : `(batch_size, sequence_l...
9,111
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/modules/seq2vec_encoders/seq2vec_encoder.py
24,25
5,30
get_output_dim
Seq2VecEncoder
29,30
25,30
class Seq2VecEncoder(_EncoderBase, Registrable): """ A `Seq2VecEncoder` is a `Module` that takes as input a sequence of vectors and returns a single vector. Input shape : `(batch_size, sequence_length, input_dim)`; output shape: `(batch_size, output_dim)`. We add two methods to the basic `Module` ...
class Seq2VecEncoder(_EncoderBase, Registrable): """ A `Seq2VecEncoder` is a `Module` that takes as input a sequence of vectors and returns a single vector. Input shape : `(batch_size, sequence_length, input_dim)`; output shape: `(batch_size, output_dim)`. We add two methods to the basic `Module` ...
raise NotImplementedError
""" Returns the dimension of the final vector output by this `Seq2VecEncoder`. This is `not` the shape of the returned tensor, but the last element of that shape. """ raise NotImplementedError
2
324
9
333
from allennlp.modules.encoder_base import _EncoderBase from allennlp.common import Registrable class Seq2VecEncoder(_EncoderBase, Registrable): """ A `Seq2VecEncoder` is a `Module` that takes as input a sequence of vectors and returns a single vector. Input shape : `(batch_size, sequence_length, input_di...
from allennlp.modules.encoder_base import _EncoderBase from allennlp.common import Registrable class Seq2VecEncoder(_EncoderBase, Registrable): """ A `Seq2VecEncoder` is a `Module` that takes as input a sequence of vectors and returns a single vector. Input shape : `(batch_size, sequence_length, input_di...
9,112
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/modules/transformer/bimodal_connection_layer.py
88,96
32,116
forward
BiModalConnectionLayer
96,116
96,116
class BiModalConnectionLayer(TransformerModule, FromParams): _pretrained_mapping = {"biAttention": "bimodal_attention", "biOutput": "bimodal_output"} def __init__( self, hidden_size1: int, hidden_size2: int, combined_hidden_size: int, intermediate_size1: int, in...
class BiModalConnectionLayer(TransformerModule, FromParams): _pretrained_mapping = {"biAttention": "bimodal_attention", "biOutput": "bimodal_output"} def __init__( self, hidden_size1: int, hidden_size2: int, combined_hidden_size: int, intermediate_size1: int, in...
bi_output1, bi_output2 = self.bimodal_attention( input_tensor1, input_tensor2, attention_mask1, attention_mask2, co_attention_mask, ) attention_output1, attention_output2 = self.bimodal_output( bi_output2, input_tensor1, b...
bi_output1, bi_output2 = self.bimodal_attention( input_tensor1, input_tensor2, attention_mask1, attention_mask2, co_attention_mask, ) attention_output1, attention_output2 = self.bimodal_output( bi_output2, input_tensor1, b...
36
566
224
790
from allennlp.common import FromParams from allennlp.modules.transformer.activation_layer import ActivationLayer from allennlp.modules.transformer.output_layer import OutputLayer from allennlp.modules.transformer.bimodal_attention import BiModalAttention from allennlp.modules.transformer.transformer_module import Tra...
from allennlp.common import FromParams from allennlp.modules.transformer.activation_layer import ActivationLayer from allennlp.modules.transformer.output_layer import OutputLayer from allennlp.modules.transformer.bimodal_attention import BiModalAttention from allennlp.modules.transformer.transformer_module import Tra...
9,113
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/modules/transformer/bimodal_connection_layer.py
24,25
10,32
forward
BiModalOutput
25,32
25,32
class BiModalOutput(TransformerModule, FromParams): def __init__( self, hidden_size1: int, hidden_size2: int, combined_hidden_size: int, dropout1: float, dropout2: float, ): super().__init__() self.bert_output1 = OutputLayer(combined_hidden_size, ...
class BiModalOutput(TransformerModule, FromParams): def __init__( self, hidden_size1: int, hidden_size2: int, combined_hidden_size: int, dropout1: float, dropout2: float, ): super().__init__() self.bert_output1 = OutputLayer(combined_hidden_size, ...
hidden_states1 = self.bert_output1(hidden_states1, input_tensor1) hidden_states2 = self.bert_output2(hidden_states2, input_tensor2) return hidden_states1, hidden_states2
hidden_states1 = self.bert_output1(hidden_states1, input_tensor1) hidden_states2 = self.bert_output2(hidden_states2, input_tensor2) return hidden_states1, hidden_states2
11
174
71
245
from allennlp.common import FromParams from allennlp.modules.transformer.activation_layer import ActivationLayer from allennlp.modules.transformer.output_layer import OutputLayer from allennlp.modules.transformer.bimodal_attention import BiModalAttention from allennlp.modules.transformer.transformer_module import Tra...
from allennlp.common import FromParams from allennlp.modules.transformer.activation_layer import ActivationLayer from allennlp.modules.transformer.output_layer import OutputLayer from allennlp.modules.transformer.bimodal_attention import BiModalAttention from allennlp.modules.transformer.transformer_module import Tra...
9,114
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/predictors/multitask.py
56,57
15,92
predict_instance
MultiTaskPredictor
57,67
57,67
@Predictor.register("multitask") class MultiTaskPredictor(Predictor): """ Predictor for multitask models. Registered as a `Predictor` with name "multitask". This predictor is tightly coupled to `MultiTaskDatasetReader` and `MultiTaskModel`, and will not work if used with other readers or models. ...
@Predictor.register("multitask") class MultiTaskPredictor(Predictor): """ Predictor for multitask models. Registered as a `Predictor` with name "multitask". This predictor is tightly coupled to `MultiTaskDatasetReader` and `MultiTaskModel`, and will not work if used with other readers or models. ...
task_field = instance["task"] if not isinstance(task_field, MetadataField): raise ValueError(self._WRONG_FIELD_ERROR) task: str = task_field.metadata if not isinstance(self._dataset_reader, MultiTaskDatasetReader): raise ConfigurationError(self._WRONG_READER_ERROR...
task_field = instance["task"] if not isinstance(task_field, MetadataField): raise ValueError(self._WRONG_FIELD_ERROR) task: str = task_field.metadata if not isinstance(self._dataset_reader, MultiTaskDatasetReader): raise ConfigurationError(self._WRONG_READER_ERROR...
25
814
145
959
import collections from typing import Type, List, Dict from allennlp.common import JsonDict from allennlp.data import Instance from allennlp.models.multitask import MultiTaskModel from allennlp.predictors.predictor import Predictor from allennlp.common.util import sanitize from allennlp.data.fields import MetadataFie...
import collections from typing import Type, List, Dict from allennlp.common import JsonDict from allennlp.data import Instance from allennlp.models.multitask import MultiTaskModel from allennlp.predictors.predictor import Predictor from allennlp.common.util import sanitize from allennlp.data.fields import MetadataFie...
9,115
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/tools/archive_surgery.py
28,29
1,83
main
29,80
29,80
#! /usr/bin/env python """ Helper script for modifying config.json files that are locked inside model.tar.gz archives. This is useful if you need to rename things or add or remove values, usually because of changes to the library. This script will untar the archive to a temp directory, launch an editor to modify the c...
#! /usr/bin/env python """ Helper script for modifying config.json files that are locked inside model.tar.gz archives. This is useful if you need to rename things or add or remove values, usually because of changes to the library. This script will untar the archive to a temp directory, launch an editor to modify the c...
parser = argparse.ArgumentParser( description="Perform surgery on a model.tar.gz archive", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument("--input-file", required=True, help="path to input file") parser.add_argument( "--editor", default=os....
parser = argparse.ArgumentParser( description="Perform surgery on a model.tar.gz archive", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument("--input-file", required=True, help="path to input file") parser.add_argument( "--editor", default=os....
150
241
608
849
#! /usr/bin/env python """ Helper script for modifying config.json files that are locked inside model.tar.gz archives. This is useful if you need to rename things or add or remove values, usually because of changes to the library. This script will untar the archive to a temp directory, launch an editor to modify the c...
#! /usr/bin/env python """ Helper script for modifying config.json files that are locked inside model.tar.gz archives. This is useful if you need to rename things or add or remove values, usually because of changes to the library. This script will untar the archive to a temp directory, launch an editor to modify the c...
9,116
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/tools/inspect_cache.py
7,8
1,30
main
8,28
8,28
import os from allennlp.common.file_utils import CACHE_DIRECTORY from allennlp.common.file_utils import filename_to_url def main(): FILL_FUNC_BODYif __name__ == "__main__": main()
import os from allennlp.common.file_utils import CACHE_DIRECTORY from allennlp.common.file_utils import filename_to_url def main(): FILL_FUNC_BODYif __name__ == "__main__": main()
print(f"Looking for datasets in {CACHE_DIRECTORY}...") if not os.path.exists(CACHE_DIRECTORY): print("Directory does not exist.") print("No cached datasets found.") cached_files = os.listdir(CACHE_DIRECTORY) if not cached_files: print("Directory is empty.") print("No ca...
print(f"Looking for datasets in {CACHE_DIRECTORY}...") if not os.path.exists(CACHE_DIRECTORY): print("Directory does not exist.") print("No cached datasets found.") cached_files = os.listdir(CACHE_DIRECTORY) if not cached_files: print("Directory is empty.") print("No ca...
53
71
206
277
import os from allennlp.common.file_utils import CACHE_DIRECTORY from allennlp.common.file_utils import filename_to_url def main(): FILL_FUNC_BODYif __name__ == "__main__": main()
import os from allennlp.common.file_utils import CACHE_DIRECTORY from allennlp.common.file_utils import filename_to_url def main(): FILL_FUNC_BODYif __name__ == "__main__": main()
9,117
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/training/callbacks/confidence_checks.py
37,50
13,64
on_batch
ConfidenceChecksCallback
50,64
50,64
@TrainerCallback.register("sanity_checks") @TrainerCallback.register("confidence_checks") class ConfidenceChecksCallback(TrainerCallback): """ Performs model confidence checks. Checks performed: * `NormalizationBiasVerification` for detecting invalid combinations of bias and normalization layer...
@TrainerCallback.register("sanity_checks") @TrainerCallback.register("confidence_checks") class ConfidenceChecksCallback(TrainerCallback): """ Performs model confidence checks. Checks performed: * `NormalizationBiasVerification` for detecting invalid combinations of bias and normalization layer...
if not is_primary: return None # We destroy the hooks after the first batch, since we only want to # perform this check once. if epoch == 0 and batch_number == 1 and is_training: self._verification.destroy_hooks() detected_pairs = self._verification.c...
if not is_primary: return None # We destroy the hooks after the first batch, since we only want to # perform this check once. if epoch == 0 and batch_number == 1 and is_training: self._verification.destroy_hooks() detected_pairs = self._verification.c...
54
383
145
528
from typing import List, Dict, Any, Optional, TYPE_CHECKING from allennlp.training.callbacks.callback import TrainerCallback from allennlp.data import TensorDict from allennlp.confidence_checks.normalization_bias_verification import NormalizationBiasVerification if TYPE_CHECKING: from allennlp.training.gradient_...
from typing import List, Dict, Any, Optional, TYPE_CHECKING from allennlp.training.callbacks.callback import TrainerCallback from allennlp.data import TensorDict from allennlp.confidence_checks.normalization_bias_verification import NormalizationBiasVerification if TYPE_CHECKING: from allennlp.training.gradient_...
9,118
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/training/callbacks/should_validate.py
54,55
9,61
_should_validate
ShouldValidateCallback
55,61
55,61
@TrainerCallback.register("should_validate_callback") class ShouldValidateCallback(TrainerCallback): """ A callback that you can pass to the `GradientDescentTrainer` to change the frequency of validation during training. If `validation_start` is not `None`, validation will not occur until `validation_st...
@TrainerCallback.register("should_validate_callback") class ShouldValidateCallback(TrainerCallback): """ A callback that you can pass to the `GradientDescentTrainer` to change the frequency of validation during training. If `validation_start` is not `None`, validation will not occur until `validation_st...
should_validate = True if self._validation_start is not None and epoch < self._validation_start: should_validate = False elif self._validation_interval is not None and epoch % self._validation_interval != 0: should_validate = False return should_validate
should_validate = True if self._validation_start is not None and epoch < self._validation_start: should_validate = False elif self._validation_interval is not None and epoch % self._validation_interval != 0: should_validate = False return should_validate
31
517
76
593
from typing import Dict, Any, TYPE_CHECKING, Optional from allennlp.training.callbacks.callback import TrainerCallback if TYPE_CHECKING: from allennlp.training.gradient_descent_trainer import GradientDescentTrainer @TrainerCallback.register("should_validate_callback") class ShouldValidateCallback(TrainerCallbac...
from typing import Dict, Any, TYPE_CHECKING, Optional from allennlp.training.callbacks.callback import TrainerCallback if TYPE_CHECKING: from allennlp.training.gradient_descent_trainer import GradientDescentTrainer @TrainerCallback.register("should_validate_callback") class ShouldValidateCallback(TrainerCallbac...
9,119
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/training/callbacks/track_epoch.py
24,32
9,33
on_epoch
TrackEpochCallback
32,33
32,33
@TrainerCallback.register("track_epoch_callback") class TrackEpochCallback(TrainerCallback): """ A callback that you can pass to the `GradientDescentTrainer` to access the current epoch number in your model during training. This callback sets `model.epoch`, which can be read inside of `model.forward()`....
@TrainerCallback.register("track_epoch_callback") class TrackEpochCallback(TrainerCallback): """ A callback that you can pass to the `GradientDescentTrainer` to access the current epoch number in your model during training. This callback sets `model.epoch`, which can be read inside of `model.forward()`....
trainer.model.epoch = epoch + 1 # type: ignore[assignment]
trainer.model.epoch = epoch + 1 # type: ignore[assignment]
8
273
23
296
from typing import Dict, Any, TYPE_CHECKING from allennlp.training.callbacks.callback import TrainerCallback if TYPE_CHECKING: from allennlp.training.gradient_descent_trainer import GradientDescentTrainer @TrainerCallback.register("track_epoch_callback") class TrackEpochCallback(TrainerCallback): """ A ...
from typing import Dict, Any, TYPE_CHECKING from allennlp.training.callbacks.callback import TrainerCallback if TYPE_CHECKING: from allennlp.training.gradient_descent_trainer import GradientDescentTrainer @TrainerCallback.register("track_epoch_callback") class TrackEpochCallback(TrainerCallback): """ A ...
9,120
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/training/metric_tracker.py
77,78
6,134
load_state_dict
MetricTracker
81,91
78,91
class MetricTracker: """ This class tracks a metric during training for the dual purposes of early stopping and for knowing whether the current value is the best so far. It mimics the PyTorch `state_dict` / `load_state_dict` interface, so that it can be checkpointed along with your model and optimiz...
class MetricTracker: """ This class tracks a metric during training for the dual purposes of early stopping and for knowing whether the current value is the best so far. It mimics the PyTorch `state_dict` / `load_state_dict` interface, so that it can be checkpointed along with your model and optimiz...
self._best_so_far = state_dict["best_so_far"] self._epochs_with_no_improvement = state_dict["epochs_with_no_improvement"] self._is_best_so_far = state_dict["is_best_so_far"] self._epoch_number = state_dict["epoch_number"] self.best_epoch = state_dict["best_epoch"] # Even...
""" A `Trainer` can use this to hydrate a metric tracker from a serialized state. """ self._best_so_far = state_dict["best_so_far"] self._epochs_with_no_improvement = state_dict["epochs_with_no_improvement"] self._is_best_so_far = state_dict["is_best_so_far"] self...
45
1,333
193
1,526
from typing import Optional, Dict, Any, List, Union from allennlp.common.checks import ConfigurationError class MetricTracker: """ This class tracks a metric during training for the dual purposes of early stopping and for knowing whether the current value is the best so far. It mimics the PyTorch `st...
from typing import Optional, Dict, Any, List, Union from allennlp.common.checks import ConfigurationError class MetricTracker: """ This class tracks a metric during training for the dual purposes of early stopping and for knowing whether the current value is the best so far. It mimics the PyTorch `st...
9,121
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/training/metrics/average.py
28,29
5,43
get_metric
Average
34,40
29,40
@Metric.register("average") class Average(Metric): """ This [`Metric`](./metric.md) breaks with the typical `Metric` API and just stores values that were computed in some fashion outside of a `Metric`. If you have some external code that computes the metric for you, for instance, you can use this to re...
@Metric.register("average") class Average(Metric): """ This [`Metric`](./metric.md) breaks with the typical `Metric` API and just stores values that were computed in some fashion outside of a `Metric`. If you have some external code that computes the metric for you, for instance, you can use this to re...
average_value = self._total_value / self._count if self._count > 0 else 0.0 if reset: self.reset() return float(average_value)
""" # Returns The average of all values that were passed to `__call__`. """ average_value = self._total_value / self._count if self._count > 0 else 0.0 if reset: self.reset() return float(average_value)
16
301
55
356
from allennlp.training.metrics.metric import Metric from allennlp.nn.util import dist_reduce_sum @Metric.register("average") class Average(Metric): """ This [`Metric`](./metric.md) breaks with the typical `Metric` API and just stores values that were computed in some fashion outside of a `Metric`. If you...
from allennlp.training.metrics.metric import Metric from allennlp.nn.util import dist_reduce_sum @Metric.register("average") class Average(Metric): """ This [`Metric`](./metric.md) breaks with the typical `Metric` API and just stores values that were computed in some fashion outside of a `Metric`. If you...
9,122
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/training/metrics/f1_measure.py
65,67
7,75
_false_negatives
F1Measure
67,75
67,75
@Metric.register("f1") class F1Measure(FBetaMeasure): """ Computes Precision, Recall and F1 with respect to a given `positive_label`. For example, for a BIO tagging scheme, you would pass the classification index of the tag you are interested in, resulting in the Precision, Recall and F1 score being ...
@Metric.register("f1") class F1Measure(FBetaMeasure): """ Computes Precision, Recall and F1 with respect to a given `positive_label`. For example, for a BIO tagging scheme, you would pass the classification index of the tag you are interested in, resulting in the Precision, Recall and F1 score being ...
# When this metric is never called, `self._true_sum` is None, # under which case we return 0.0 for backward compatibility. if self._true_sum is None: return 0.0 else: # `self._true_sum` is the total number of instances under each _true_ class, # includ...
# When this metric is never called, `self._true_sum` is None, # under which case we return 0.0 for backward compatibility. if self._true_sum is None: return 0.0 else: # `self._true_sum` is the total number of instances under each _true_ class, # includ...
50
667
123
790
from typing import Dict from allennlp.training.metrics.metric import Metric from allennlp.training.metrics.fbeta_measure import FBetaMeasure @Metric.register("f1") class F1Measure(FBetaMeasure): """ Computes Precision, Recall and F1 with respect to a given `positive_label`. For example, for a BIO tagging...
from typing import Dict from allennlp.training.metrics.metric import Metric from allennlp.training.metrics.fbeta_measure import FBetaMeasure @Metric.register("f1") class F1Measure(FBetaMeasure): """ Computes Precision, Recall and F1 with respect to a given `positive_label`. For example, for a BIO tagging...
9,123
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/training/metrics/fbeta_verbose_measure.py
78,79
8,155
get_metric
FBetaVerboseMeasure
93,155
79,155
@Metric.register("fbeta_verbose") class FBetaVerboseMeasure(FBetaMeasure): """Compute precision, recall, F-measure and support for each class. This is basically the same as `FBetaMeasure` (the super class) with two differences: - it always returns a dictionary of floats, while `FBetaMeasure` ...
@Metric.register("fbeta_verbose") class FBetaVerboseMeasure(FBetaMeasure): """Compute precision, recall, F-measure and support for each class. This is basically the same as `FBetaMeasure` (the super class) with two differences: - it always returns a dictionary of floats, while `FBetaMeasure` ...
if self._true_positive_sum is None or self._pred_sum is None or self._true_sum is None: raise RuntimeError("You have never called this metric before.") tp_sum = self._true_positive_sum pred_sum = self._pred_sum true_sum = self._true_sum if self._labels is not None: ...
""" # Returns <class>-precision : `float` <class>-recall : `float` <class>-fscore : `float` <avg>-precision : `float` <avg>-recall : `float` <avg>-fscore : `float` where <class> is the index (or the label if `index_to_label` is given) of ...
207
1,010
853
1,863
from typing import List, Dict from allennlp.common.util import nan_safe_tensor_divide from allennlp.training.metrics.metric import Metric from allennlp.training.metrics.fbeta_measure import FBetaMeasure @Metric.register("fbeta_verbose") class FBetaVerboseMeasure(FBetaMeasure): """Compute precision, recall, F-mea...
from typing import List, Dict from allennlp.common.util import nan_safe_tensor_divide from allennlp.training.metrics.metric import Metric from allennlp.training.metrics.fbeta_measure import FBetaMeasure @Metric.register("fbeta_verbose") class FBetaVerboseMeasure(FBetaMeasure): """Compute precision, recall, F-mea...
9,124
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/allennlp/training/metrics/perplexity.py
19,20
7,31
get_metric
Perplexity
25,31
20,31
@Metric.register("perplexity") class Perplexity(Average): """ Perplexity is a common metric used for evaluating how well a language model predicts a sample. Notes ----- Assumes negative log likelihood loss of each batch (base e). Provides the average perplexity of the batches. """ ...
@Metric.register("perplexity") class Perplexity(Average): """ Perplexity is a common metric used for evaluating how well a language model predicts a sample. Notes ----- Assumes negative log likelihood loss of each batch (base e). Provides the average perplexity of the batches. """ ...
average_loss = super().get_metric(reset) if average_loss == 0: return 0.0 # Exponentiate the loss to compute perplexity return math.exp(average_loss)
""" # Returns The accumulated perplexity. """ average_loss = super().get_metric(reset) if average_loss == 0: return 0.0 # Exponentiate the loss to compute perplexity return math.exp(average_loss)
18
133
62
195
import math from allennlp.training.metrics.average import Average from allennlp.training.metrics.metric import Metric @Metric.register("perplexity") class Perplexity(Average): """ Perplexity is a common metric used for evaluating how well a language model predicts a sample. Notes ----- Assum...
import math from allennlp.training.metrics.average import Average from allennlp.training.metrics.metric import Metric @Metric.register("perplexity") class Perplexity(Average): """ Perplexity is a common metric used for evaluating how well a language model predicts a sample. Notes ----- Assum...
9,125
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/benchmarks/data/tokenizers/character_tokenizer_bench.py
15,16
1,17
bench_character_tokenizer
16,17
16,17
from allennlp.data.tokenizers import CharacterTokenizer tokenizer = CharacterTokenizer() passage = ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " "nostrud exercitation ullamco laboris nisi ut...
from allennlp.data.tokenizers import CharacterTokenizer tokenizer = CharacterTokenizer() passage = ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " "nostrud exercitation ullamco laboris nisi ut...
benchmark(tokenizer.tokenize, passage)
benchmark(tokenizer.tokenize, passage)
2
234
13
247
from allennlp.data.tokenizers import CharacterTokenizer tokenizer = CharacterTokenizer() passage = ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " "nostrud exercitation ullamco laboris nisi ut...
from allennlp.data.tokenizers import CharacterTokenizer tokenizer = CharacterTokenizer() passage = ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " "nostrud exercitation ullamco laboris nisi ut...
9,127
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/scripts/ai2_internal/resume_daemon.py
74,75
59,89
is_end_state
BeakerStatus
75,89
75,89
class BeakerStatus(Enum): submitted = "submitted" provisioning = "provisioning" initializing = "initializing" running = "running" terminating = "terminating" preempted = "preempted" succeeded = "succeeded" skipped = "skipped" stopped = "stopped" failed = "failed" def __str__...
class BeakerStatus(Enum): submitted = "submitted" provisioning = "provisioning" initializing = "initializing" running = "running" terminating = "terminating" preempted = "preempted" succeeded = "succeeded" skipped = "skipped" stopped = "stopped" failed = "failed" def __str__...
if self is BeakerStatus.preempted: return True elif self is BeakerStatus.succeeded: return True elif self is BeakerStatus.skipped: return True elif self is BeakerStatus.stopped: return True elif self is BeakerStatus.failed: ...
if self is BeakerStatus.preempted: return True elif self is BeakerStatus.succeeded: return True elif self is BeakerStatus.skipped: return True elif self is BeakerStatus.stopped: return True elif self is BeakerStatus.failed: ...
33
133
106
239
#! /usr/bin/env python3 # Tool to automatically resume preemptible beaker experiments created with run_with_beaker.py. # # Examples # -------- # # Ensure an experiment will be resumed: # resume_daemon.py --action=start --experiment-id=$YOUR_EXPERIMENT_ID # # Stop resuming an experiment: # resume_daemon.py --action=sto...
#! /usr/bin/env python3 # Tool to automatically resume preemptible beaker experiments created with run_with_beaker.py. # # Examples # -------- # # Ensure an experiment will be resumed: # resume_daemon.py --action=start --experiment-id=$YOUR_EXPERIMENT_ID # # Stop resuming an experiment: # resume_daemon.py --action=sto...
9,128
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/scripts/ai2_internal/resume_daemon.py
90,91
89,154
get_status
BeakerWrapper
91,147
91,147
class BeakerWrapper: def get_status(self, experiment_id: str) -> BeakerStatus: FILL_FUNC_BODY def resume(self, experiment_id: str) -> str: command = ["beaker", "experiment", "resume", f"--experiment-name={experiment_id}"] # Small delay to avoid thrashing Beaker. time.sleep(BEAKER_QUERY_IN...
class BeakerWrapper: def get_status(self, experiment_id: str) -> BeakerStatus: FILL_FUNC_BODY def resume(self, experiment_id: str) -> str: command = ["beaker", "experiment", "resume", f"--experiment-name={experiment_id}"] # Small delay to avoid thrashing Beaker. time.sleep(BEAKER_QUERY_IN...
command = ["beaker", "experiment", "inspect", experiment_id] experiment_json = subprocess.check_output(command) # Example output from beaker. # brendanr.local$ beaker experiment inspect ex_g7knlblsjxxk # [ # { # "id": "ex_g7knlblsjxxk", # ...
command = ["beaker", "experiment", "inspect", experiment_id] experiment_json = subprocess.check_output(command) # Example output from beaker. # brendanr.local$ beaker experiment inspect ex_g7knlblsjxxk # [ # { # "id": "ex_g7knlblsjxxk", # ...
189
139
723
862
#! /usr/bin/env python3 # Tool to automatically resume preemptible beaker experiments created with run_with_beaker.py. # # Examples # -------- # # Ensure an experiment will be resumed: # resume_daemon.py --action=start --experiment-id=$YOUR_EXPERIMENT_ID # # Stop resuming an experiment: # resume_daemon.py --action=sto...
#! /usr/bin/env python3 # Tool to automatically resume preemptible beaker experiments created with run_with_beaker.py. # # Examples # -------- # # Ensure an experiment will be resumed: # resume_daemon.py --action=start --experiment-id=$YOUR_EXPERIMENT_ID # # Stop resuming an experiment: # resume_daemon.py --action=sto...
9,130
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/scripts/check_links.py
42,43
1,110
url_ok
44,54
43,54
#!/usr/bin/env python # encoding: UTF-8 """ Goes through all the inline-links in markdown files and reports the breakages. """ import re import sys import pathlib import os from multiprocessing.dummy import Pool from typing import Tuple, NamedTuple, Optional import requests OK_STATUS_CODES = ( 200, 401, #...
#!/usr/bin/env python # encoding: UTF-8 """ Goes through all the inline-links in markdown files and reports the breakages. """ import re import sys import pathlib import os from multiprocessing.dummy import Pool from typing import Tuple, NamedTuple, Optional import requests OK_STATUS_CODES = ( 200, 401, #...
try: result = http_session.head(match_tuple.link, timeout=5, allow_redirects=True) return ( result.ok or result.status_code in OK_STATUS_CODES, f"status code = {result.status_code}", ) except (requests.ConnectionError, requests.Timeout): return False, "con...
"""Check if a URL is reachable.""" try: result = http_session.head(match_tuple.link, timeout=5, allow_redirects=True) return ( result.ok or result.status_code in OK_STATUS_CODES, f"status code = {result.status_code}", ) except (requests.ConnectionError, reques...
25
1,037
109
1,146
#!/usr/bin/env python # encoding: UTF-8 """ Goes through all the inline-links in markdown files and reports the breakages. """ import re import sys import pathlib import os from multiprocessing.dummy import Pool from typing import Tuple, NamedTuple, Optional import requests OK_STATUS_CODES = ( 200, 401, #...
#!/usr/bin/env python # encoding: UTF-8 """ Goes through all the inline-links in markdown files and reports the breakages. """ import re import sys import pathlib import os from multiprocessing.dummy import Pool from typing import Tuple, NamedTuple, Optional import requests OK_STATUS_CODES = ( 200, 401, #...
9,131
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/scripts/get_version.py
32,33
1,46
main
33,44
33,44
#!/usr/bin/env python import argparse from typing import Dict import requests def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("version_type", choices=["stable", "latest", "current"]) return parser.parse_args() def get_current_version() -> str: VERSION: Dict[str, str] = {} ...
#!/usr/bin/env python import argparse from typing import Dict import requests def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("version_type", choices=["stable", "latest", "current"]) return parser.parse_args() def get_current_version() -> str: VERSION: Dict[str, str] = {} ...
opts = parse_args() if opts.version_type == "stable": print(get_stable_version()) elif opts.version_type == "latest": print(get_latest_version()) elif opts.version_type == "current": print(get_current_version()) else: raise NotImplementedError
opts = parse_args() if opts.version_type == "stable": print(get_stable_version()) elif opts.version_type == "latest": print(get_latest_version()) elif opts.version_type == "current": print(get_current_version()) else: raise NotImplementedError
21
300
99
399
#!/usr/bin/env python import argparse from typing import Dict import requests def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("version_type", choices=["stable", "latest", "current"]) return parser.parse_args() def get_current_version() -> str: VERSION: Dict[str, str] = {} ...
#!/usr/bin/env python import argparse from typing import Dict import requests def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("version_type", choices=["stable", "latest", "current"]) return parser.parse_args() def get_current_version() -> str: VERSION: Dict[str, str] = {} ...
9,132
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/scripts/release_notes.py
21,22
1,62
get_change_log_notes
22,47
22,47
# encoding: utf-8 """ Prepares markdown release notes for GitHub releases. """ import os from typing import List from allennlp.version import VERSION TAG = os.environ["TAG"] ADDED_HEADER = "### Added 🎉" CHANGED_HEADER = "### Changed ⚠️" FIXED_HEADER = "### Fixed ✅" REMOVED_HEADER = "### Removed 👋" def get_cha...
# encoding: utf-8 """ Prepares markdown release notes for GitHub releases. """ import os from typing import List from allennlp.version import VERSION TAG = os.environ["TAG"] ADDED_HEADER = "### Added 🎉" CHANGED_HEADER = "### Changed ⚠️" FIXED_HEADER = "### Fixed ✅" REMOVED_HEADER = "### Removed 👋" def get_cha...
in_current_section = False current_section_notes: List[str] = [] with open("CHANGELOG.md") as changelog: for line in changelog: if line.startswith("## "): if line.startswith("## Unreleased"): continue if line.startswith(f"## [{TAG}]"): ...
in_current_section = False current_section_notes: List[str] = [] with open("CHANGELOG.md") as changelog: for line in changelog: if line.startswith("## "): if line.startswith("## Unreleased"): continue if line.startswith(f"## [{TAG}]"): ...
75
283
308
591
# encoding: utf-8 """ Prepares markdown release notes for GitHub releases. """ import os from typing import List from allennlp.version import VERSION TAG = os.environ["TAG"] ADDED_HEADER = "### Added 🎉" CHANGED_HEADER = "### Changed ⚠️" FIXED_HEADER = "### Fixed ✅" REMOVED_HEADER = "### Removed 👋" def get_cha...
# encoding: utf-8 """ Prepares markdown release notes for GitHub releases. """ import os from typing import List from allennlp.version import VERSION TAG = os.environ["TAG"] ADDED_HEADER = "### Added 🎉" CHANGED_HEADER = "### Changed ⚠️" FIXED_HEADER = "### Fixed ✅" REMOVED_HEADER = "### Removed 👋" def get_cha...
9,133
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/scripts/train_fixtures.py
21,22
1,76
train_fixture
22,44
22,44
#!/usr/bin/env python import glob import logging import os import re import shutil import sys import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) from allennlp.commands.test_install import _get_module_root from allennlp.commands.train import train_model_from_file, t...
#!/usr/bin/env python import glob import logging import os import re import shutil import sys import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) from allennlp.commands.test_install import _get_module_root from allennlp.commands.train import train_model_from_file, t...
config_file = config_prefix + config_filename serialization_dir = config_prefix + "serialization" # Train model doesn't like it if we have incomplete serialization # directories, so remove them if they exist. if os.path.exists(serialization_dir): shutil.rmtree(serialization_dir) # train...
config_file = config_prefix + config_filename serialization_dir = config_prefix + "serialization" # Train model doesn't like it if we have incomplete serialization # directories, so remove them if they exist. if os.path.exists(serialization_dir): shutil.rmtree(serialization_dir) # train...
59
585
249
834
#!/usr/bin/env python import glob import logging import os import re import shutil import sys import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) from allennlp.commands.test_install import _get_module_root from allennlp.commands.train import train_model_from_file, t...
#!/usr/bin/env python import glob import logging import os import re import shutil import sys import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) from allennlp.commands.test_install import _get_module_root from allennlp.commands.train import train_model_from_file, t...
9,134
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp
/home/hieuvd/dung_repo/raw/stars_01/allenai_allennlp/allennlp/setup.py
18,19
1,108
parse_requirements_file
19,53
19,53
from collections import defaultdict from setuptools import find_packages, setup # PEP0440 compatible formatted version, see: # https://www.python.org/dev/peps/pep-0440/ # # release markers: # X.Y # X.Y.Z # For bugfix releases # # pre-release markers: # X.YaN # Alpha release # X.YbN # Beta release # X.Y...
from collections import defaultdict from setuptools import find_packages, setup # PEP0440 compatible formatted version, see: # https://www.python.org/dev/peps/pep-0440/ # # release markers: # X.Y # X.Y.Z # For bugfix releases # # pre-release markers: # X.YaN # Alpha release # X.YbN # Beta release # X.Y...
requirements = [] extras = defaultdict(list) with open(path) as requirements_file: import re def fix_url_dependencies(req: str) -> str: """Pip and setuptools disagree about how URL dependencies should be handled.""" m = re.match( r"^(git\+)?(https|ssh...
requirements = [] extras = defaultdict(list) with open(path) as requirements_file: import re def fix_url_dependencies(req: str) -> str: """Pip and setuptools disagree about how URL dependencies should be handled.""" m = re.match( r"^(git\+)?(https|ssh...
107
765
394
1,159
from collections import defaultdict from setuptools import find_packages, setup # PEP0440 compatible formatted version, see: # https://www.python.org/dev/peps/pep-0440/ # # release markers: # X.Y # X.Y.Z # For bugfix releases # # pre-release markers: # X.YaN # Alpha release # X.YbN # Beta release # X.Y...
from collections import defaultdict from setuptools import find_packages, setup # PEP0440 compatible formatted version, see: # https://www.python.org/dev/peps/pep-0440/ # # release markers: # X.Y # X.Y.Z # For bugfix releases # # pre-release markers: # X.YaN # Alpha release # X.YbN # Beta release # X.Y...
9,476
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle/setup.py
23,24
1,62
version_scheme
24,28
24,28
#!/usr/bin/env python # Copyright 2012-2014 Brian May # # This file is part of python-tldap. # # python-tldap is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
#!/usr/bin/env python # Copyright 2012-2014 Brian May # # This file is part of python-tldap. # # python-tldap is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
from setuptools_scm.version import guess_next_dev_version version = guess_next_dev_version(version) return version.lstrip("v")
from setuptools_scm.version import guess_next_dev_version version = guess_next_dev_version(version) return version.lstrip("v")
9
609
47
656
#!/usr/bin/env python # Copyright 2012-2014 Brian May # # This file is part of python-tldap. # # python-tldap is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
#!/usr/bin/env python # Copyright 2012-2014 Brian May # # This file is part of python-tldap. # # python-tldap is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
9,478
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle/sshuttle/client.py
242,243
169,286
start
FirewallClient
243,273
243,273
class FirewallClient: def __init__(self, method_name): self.auto_nets = [] python_path = os.path.dirname(os.path.dirname(__file__)) argvbase = ([sys.executable, sys.argv[0]] + ['-v'] * (helpers.verbose or 0) + ['--method', method_name] + ...
class FirewallClient: def __init__(self, method_name): self.auto_nets = [] python_path = os.path.dirname(os.path.dirname(__file__)) argvbase = ([sys.executable, sys.argv[0]] + ['-v'] * (helpers.verbose or 0) + ['--method', method_name] + ...
self.pfile.write(b'ROUTES\n') for (family, ip, width) in self.subnets_include + self.auto_nets: self.pfile.write(b'%d,%d,0,%s\n' % (family, width, ip.encode("ASCII"))) for (family, ip, width) in self.subnets_exclude: self.pfile.write(b'%d,%d,1...
self.pfile.write(b'ROUTES\n') for (family, ip, width) in self.subnets_include + self.auto_nets: self.pfile.write(b'%d,%d,0,%s\n' % (family, width, ip.encode("ASCII"))) for (family, ip, width) in self.subnets_exclude: self.pfile.write(b'%d,%d,1...
73
1,044
426
1,470
import socket import errno import re import signal import time import subprocess as ssubprocess import sshuttle.helpers as helpers import os import sshuttle.ssnet as ssnet import sshuttle.ssh as ssh import sshuttle.ssyslog as ssyslog import sys import platform from sshuttle.ssnet import SockWrapper, Handler, Proxy, Mux...
import socket import errno import re import signal import time import subprocess as ssubprocess import sshuttle.helpers as helpers import os import sshuttle.ssnet as ssnet import sshuttle.ssh as ssh import sshuttle.ssyslog as ssyslog import sys import platform from sshuttle.ssnet import SockWrapper, Handler, Proxy, Mux...
9,479
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle/sshuttle/client.py
104,105
95,169
setsockopt
MultiListener
105,111
105,111
class MultiListener: def __init__(self, type=socket.SOCK_STREAM, proto=0): self.type = type self.proto = proto self.v6 = None self.v4 = None self.bind_called = False def setsockopt(self, level, optname, value): FILL_FUNC_BODY def add_handler(self, handlers, callback,...
class MultiListener: def __init__(self, type=socket.SOCK_STREAM, proto=0): self.type = type self.proto = proto self.v6 = None self.v4 = None self.bind_called = False def setsockopt(self, level, optname, value): FILL_FUNC_BODY def add_handler(self, handlers, callback,...
assert(self.bind_called) if self.v6: self.v6.setsockopt(level, optname, value) if self.v4: self.v4.setsockopt(level, optname, value)
assert(self.bind_called) if self.v6: self.v6.setsockopt(level, optname, value) if self.v4: self.v4.setsockopt(level, optname, value)
11
747
69
816
import socket import errno import re import signal import time import subprocess as ssubprocess import sshuttle.helpers as helpers import os import sshuttle.ssnet as ssnet import sshuttle.ssh as ssh import sshuttle.ssyslog as ssyslog import sys import platform from sshuttle.ssnet import SockWrapper, Handler, Proxy, Mux...
import socket import errno import re import signal import time import subprocess as ssubprocess import sshuttle.helpers as helpers import os import sshuttle.ssnet as ssnet import sshuttle.ssh as ssh import sshuttle.ssyslog as ssyslog import sys import platform from sshuttle.ssnet import SockWrapper, Handler, Proxy, Mux...
9,480
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle/sshuttle/helpers.py
9,10
1,97
log
10,28
10,28
import sys import socket import errno logprefix = '' verbose = 0 def log(s): FILL_FUNC_BODYdef debug1(s): if verbose >= 1: log(s) def debug2(s): if verbose >= 2: log(s) def debug3(s): if verbose >= 3: log(s) class Fatal(Exception): pass def resolvconf_nameservers(): ...
import sys import socket import errno logprefix = '' verbose = 0 def log(s): FILL_FUNC_BODYdef debug1(s): if verbose >= 1: log(s) def debug2(s): if verbose >= 2: log(s) def debug3(s): if verbose >= 3: log(s) class Fatal(Exception): pass def resolvconf_nameservers(): ...
global logprefix try: sys.stdout.flush() if s.find("\n") != -1: prefix = logprefix s = s.rstrip("\n") for line in s.split("\n"): sys.stderr.write(prefix + line + "\n") prefix = "---> " else: sys.stderr.write(...
global logprefix try: sys.stdout.flush() if s.find("\n") != -1: prefix = logprefix s = s.rstrip("\n") for line in s.split("\n"): sys.stderr.write(prefix + line + "\n") prefix = "---> " else: sys.stderr.write(...
60
538
185
723
import sys import socket import errno logprefix = '' verbose = 0 def log(s): FILL_FUNC_BODYdef debug1(s): if verbose >= 1: log(s) def debug2(s): if verbose >= 2: log(s) def debug3(s): if verbose >= 3: log(s) class Fatal(Exception): pass def resolvconf_nameservers(): ...
import sys import socket import errno logprefix = '' verbose = 0 def log(s): FILL_FUNC_BODYdef debug1(s): if verbose >= 1: log(s) def debug2(s): if verbose >= 2: log(s) def debug3(s): if verbose >= 3: log(s) class Fatal(Exception): pass def resolvconf_nameservers(): ...
9,482
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle/sshuttle/linux.py
30,31
1,63
ipt
31,43
31,43
import socket import subprocess as ssubprocess from sshuttle.helpers import log, debug1, Fatal, family_to_string def nonfatal(func, *args): try: func(*args) except Fatal as e: log('error: %s\n' % e) def ipt_chain_exists(family, table, name): if family == socket.AF_INET6: cmd = 'i...
import socket import subprocess as ssubprocess from sshuttle.helpers import log, debug1, Fatal, family_to_string def nonfatal(func, *args): try: func(*args) except Fatal as e: log('error: %s\n' % e) def ipt_chain_exists(family, table, name): if family == socket.AF_INET6: cmd = 'i...
if family == socket.AF_INET6: argv = ['ip6tables', '-t', table] + list(args) elif family == socket.AF_INET: argv = ['iptables', '-t', table] + list(args) else: raise Exception('Unsupported family "%s"' % family_to_string(family)) debug1('>> %s\n' % ' '.join(argv)) rv = ssubpr...
if family == socket.AF_INET6: argv = ['ip6tables', '-t', table] + list(args) elif family == socket.AF_INET: argv = ['iptables', '-t', table] + list(args) else: raise Exception('Unsupported family "%s"' % family_to_string(family)) debug1('>> %s\n' % ' '.join(argv)) rv = ssubpr...
46
520
161
681
import socket import subprocess as ssubprocess from sshuttle.helpers import log, debug1, Fatal, family_to_string def nonfatal(func, *args): try: func(*args) except Fatal as e: log('error: %s\n' % e) def ipt_chain_exists(family, table, name): if family == socket.AF_INET6: cmd = 'i...
import socket import subprocess as ssubprocess from sshuttle.helpers import log, debug1, Fatal, family_to_string def nonfatal(func, *args): try: func(*args) except Fatal as e: log('error: %s\n' % e) def ipt_chain_exists(family, table, name): if family == socket.AF_INET6: cmd = 'i...
9,483
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle/sshuttle/methods/nat.py
14,15
7,90
setup_firewall
Method
15,65
15,65
class Method(BaseMethod): # We name the chain based on the transproxy port number so that it's # possible to run multiple copies of sshuttle at the same time. Of course, # the multiple copies shouldn't have overlapping subnets, or only the most- # recently-started one will win (because we use "-I OUTP...
class Method(BaseMethod): # We name the chain based on the transproxy port number so that it's # possible to run multiple copies of sshuttle at the same time. Of course, # the multiple copies shouldn't have overlapping subnets, or only the most- # recently-started one will win (because we use "-I OUTP...
# only ipv4 supported with NAT if family != socket.AF_INET: raise Exception( 'Address family "%s" unsupported by nat method_name' % family_to_string(family)) if udp: raise Exception("UDP not supported by nat method_name") table = "...
# only ipv4 supported with NAT if family != socket.AF_INET: raise Exception( 'Address family "%s" unsupported by nat method_name' % family_to_string(family)) if udp: raise Exception("UDP not supported by nat method_name") table = "...
190
400
627
1,027
import socket from sshuttle.helpers import family_to_string from sshuttle.linux import ipt, ipt_ttl, ipt_chain_exists, nonfatal from sshuttle.methods import BaseMethod class Method(BaseMethod): # We name the chain based on the transproxy port number so that it's # possible to run multiple copies of sshuttle ...
import socket from sshuttle.helpers import family_to_string from sshuttle.linux import ipt, ipt_ttl, ipt_chain_exists, nonfatal from sshuttle.methods import BaseMethod class Method(BaseMethod): # We name the chain based on the transproxy port number so that it's # possible to run multiple copies of sshuttle ...
9,486
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle/sshuttle/options.py
104,105
77,216
_gen_usage
Options
105,166
105,166
class Options: """Option parser. When constructed, two strings are mandatory. The first one is the command name showed before error messages. The second one is a string called an optspec that specifies the synopsis and option flags and their description. For more information about optspecs, consult...
class Options: """Option parser. When constructed, two strings are mandatory. The first one is the command name showed before error messages. The second one is a string called an optspec that specifies the synopsis and option flags and their description. For more information about optspecs, consult...
out = [] lines = self.optspec.strip().split('\n') lines.reverse() first_syn = True while lines: l = lines.pop() if l == '--': break out.append('%s: %s\n' % (first_syn and 'usage' or ' or', l)) first_syn = False ...
out = [] lines = self.optspec.strip().split('\n') lines.reverse() first_syn = True while lines: l = lines.pop() if l == '--': break out.append('%s: %s\n' % (first_syn and 'usage' or ' or', l)) first_syn = False ...
195
794
768
1,562
"""Command-line options parser. With the help of an options spec string, easily parse command-line options. """ import sys import os import textwrap import getopt import re import struct class OptDict: def __init__(self): self._opts = {} def __setitem__(self, k, v): if k.startswith('no-') or...
"""Command-line options parser. With the help of an options spec string, easily parse command-line options. """ import sys import os import textwrap import getopt import re import struct class OptDict: def __init__(self): self._opts = {} def __setitem__(self, k, v): if k.startswith('no-') or...
9,487
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle/sshuttle/ssh.py
55,56
1,131
connect
56,131
56,131
import sys import os import re import socket import zlib import imp import subprocess as ssubprocess import sshuttle.helpers as helpers from sshuttle.helpers import debug2 def readfile(name): tokens = name.split(".") f = None token = tokens[0] token_name = [token] token_str = ".".join(token_name)...
import sys import os import re import socket import zlib import imp import subprocess as ssubprocess import sshuttle.helpers as helpers from sshuttle.helpers import debug2 def readfile(name): tokens = name.split(".") f = None token = tokens[0] token_name = [token] token_str = ".".join(token_name)...
portl = [] if (rhostport or '').count(':') > 1: if rhostport.count(']') or rhostport.count('['): result = rhostport.split(']') rhost = result[0].strip('[') if len(result) > 1: result[1] = result[1].strip(':') if result[1] is not '': ...
portl = [] if (rhostport or '').count(':') > 1: if rhostport.count(']') or rhostport.count('['): result = rhostport.split(']') rhost = result[0].strip('[') if len(result) > 1: result[1] = result[1].strip(':') if result[1] is not '': ...
252
406
986
1,392
import sys import os import re import socket import zlib import imp import subprocess as ssubprocess import sshuttle.helpers as helpers from sshuttle.helpers import debug2 def readfile(name): tokens = name.split(".") f = None token = tokens[0] token_name = [token] token_str = ".".join(token_name)...
import sys import os import re import socket import zlib import imp import subprocess as ssubprocess import sshuttle.helpers as helpers from sshuttle.helpers import debug2 def readfile(name): tokens = name.split(".") f = None token = tokens[0] token_name = [token] token_str = ".".join(token_name)...
9,488
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle
/home/hieuvd/dung_repo/raw/stars_01/apenwarr_sshuttle/sshuttle/sshuttle/ssyslog.py
9,10
1,20
start_syslog
10,16
10,16
import sys import os import subprocess as ssubprocess _p = None def start_syslog(): FILL_FUNC_BODYdef stderr_to_syslog(): sys.stdout.flush() sys.stderr.flush() os.dup2(_p.stdin.fileno(), 2)
import sys import os import subprocess as ssubprocess _p = None def start_syslog(): FILL_FUNC_BODYdef stderr_to_syslog(): sys.stdout.flush() sys.stderr.flush() os.dup2(_p.stdin.fileno(), 2)
global _p _p = ssubprocess.Popen(['logger', '-p', 'daemon.notice', '-t', 'sshuttle'], stdin=ssubprocess.PIPE)
global _p _p = ssubprocess.Popen(['logger', '-p', 'daemon.notice', '-t', 'sshuttle'], stdin=ssubprocess.PIPE)
10
87
58
145
import sys import os import subprocess as ssubprocess _p = None def start_syslog(): FILL_FUNC_BODYdef stderr_to_syslog(): sys.stdout.flush() sys.stderr.flush() os.dup2(_p.stdin.fileno(), 2)
import sys import os import subprocess as ssubprocess _p = None def start_syslog(): FILL_FUNC_BODYdef stderr_to_syslog(): sys.stdout.flush() sys.stderr.flush() os.dup2(_p.stdin.fileno(), 2)
9,559
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/backend/report_type/basic_report/basic_report.py
12,13
4,23
run
BasicReport
13,23
13,23
class BasicReport(): def __init__(self, query: str, report_type: str, source_urls, config_path: str, websocket: WebSocket): self.query = query self.report_type = report_type self.source_urls = source_urls self.config_path = config_path self.websocket = websocket ...
class BasicReport(): def __init__(self, query: str, report_type: str, source_urls, config_path: str, websocket: WebSocket): self.query = query self.report_type = report_type self.source_urls = source_urls self.config_path = config_path self.websocket = websocket ...
# Initialize researcher researcher = GPTResearcher(self.query, self.report_type, self.source_urls, self.config_path, self.websocket) # Run research await researcher.conduct_research() # and generate report report = await researcher.write_report()...
# Initialize researcher researcher = GPTResearcher(self.query, self.report_type, self.source_urls, self.config_path, self.websocket) # Run research await researcher.conduct_research() # and generate report report = await researcher.write_report()...
25
112
101
213
from gpt_researcher.master.agent import GPTResearcher from fastapi import WebSocket class BasicReport(): def __init__(self, query: str, report_type: str, source_urls, config_path: str, websocket: WebSocket): self.query = query self.report_type = report_type self.source_urls = source_urls ...
from gpt_researcher.master.agent import GPTResearcher from fastapi import WebSocket class BasicReport(): def __init__(self, query: str, report_type: str, source_urls, config_path: str, websocket: WebSocket): self.query = query self.report_type = report_type self.source_urls = source_urls ...
9,560
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/backend/report_type/detailed_report/detailed_report.py
29,30
10,144
run
DetailedReport
30,51
30,51
class DetailedReport(): def __init__(self, query: str, source_urls, config_path: str, websocket: WebSocket, subtopics=[]): self.query = query self.source_urls = source_urls self.config_path = config_path self.websocket = websocket self.subtopics = subtopics #...
class DetailedReport(): def __init__(self, query: str, source_urls, config_path: str, websocket: WebSocket, subtopics=[]): self.query = query self.source_urls = source_urls self.config_path = config_path self.websocket = websocket self.subtopics = subtopics #...
# Conduct initial research using the main assistant await self._initial_research() # Get list of all subtopics subtopics = await self._get_all_subtopics() # Generate report introduction report_introduction = await self.main_task_assistant.write_introduction() ...
# Conduct initial research using the main assistant await self._initial_research() # Get list of all subtopics subtopics = await self._get_all_subtopics() # Generate report introduction report_introduction = await self.main_task_assistant.write_introduction() ...
72
1,355
227
1,582
import asyncio from fastapi import WebSocket from gpt_researcher.master.agent import GPTResearcher from gpt_researcher.master.functions import (add_source_urls, extract_headers, table_of_contents) class DetailedReport(): def __init__(self, query: str, source_urls, co...
import asyncio from fastapi import WebSocket from gpt_researcher.master.agent import GPTResearcher from gpt_researcher.master.functions import (add_source_urls, extract_headers, table_of_contents) class DetailedReport(): def __init__(self, query: str, source_urls, co...
9,561
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/backend/server.py
40,42
1,66
websocket_endpoint
42,66
42,66
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from pydantic import BaseModel from backend.websocket_manager import WebSocketManager from backend.utils import write_md_to_pdf, write_md_to_word, write_text_to...
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from pydantic import BaseModel from backend.websocket_manager import WebSocketManager from backend.utils import write_md_to_pdf, write_md_to_word, write_text_to...
await manager.connect(websocket) try: while True: data = await websocket.receive_text() if data.startswith("start"): json_data = json.loads(data[6:]) task = json_data.get("task") report_type = json_data.get("report_type") ...
await manager.connect(websocket) try: while True: data = await websocket.receive_text() if data.startswith("start"): json_data = json.loads(data[6:]) task = json_data.get("task") report_type = json_data.get("report_type") ...
86
374
325
699
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from pydantic import BaseModel from backend.websocket_manager import WebSocketManager from backend.utils import write_md_to_pdf, write_md_to_word, write_text_to...
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from pydantic import BaseModel from backend.websocket_manager import WebSocketManager from backend.utils import write_md_to_pdf, write_md_to_word, write_text_to...
9,562
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/backend/utils.py
60,61
1,90
write_md_to_word
69,90
61,90
import aiofiles import urllib import uuid from md2pdf.core import md2pdf import mistune from docx import Document from htmldocx import HtmlToDocx async def write_to_file(filename: str, text: str) -> None: """Asynchronously write text to a file in UTF-8 encoding. Args: filename (str): The filename to w...
import aiofiles import urllib import uuid from md2pdf.core import md2pdf import mistune from docx import Document from htmldocx import HtmlToDocx async def write_to_file(filename: str, text: str) -> None: """Asynchronously write text to a file in UTF-8 encoding. Args: filename (str): The filename to w...
file_path = f"outputs/{filename}.docx" try: # Convert report markdown to HTML html = mistune.html(text) # Create a document object doc = Document() # Convert the html generated from the report to document format HtmlToDocx().add_html_to_document(html, doc) ...
"""Converts Markdown text to a DOCX file and returns the file path. Args: text (str): Markdown text to convert. Returns: str: The encoded file path of the generated DOCX. """ file_path = f"outputs/{filename}.docx" try: # Convert report markdown to HTML html = m...
64
663
211
874
import aiofiles import urllib import uuid from md2pdf.core import md2pdf import mistune from docx import Document from htmldocx import HtmlToDocx async def write_to_file(filename: str, text: str) -> None: """Asynchronously write text to a file in UTF-8 encoding. Args: filename (str): The filename to w...
import aiofiles import urllib import uuid from md2pdf.core import md2pdf import mistune from docx import Document from htmldocx import HtmlToDocx async def write_to_file(filename: str, text: str) -> None: """Asynchronously write text to a file in UTF-8 encoding. Args: filename (str): The filename to w...
9,563
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/backend/websocket_manager.py
61,62
1,80
run_agent
63,80
62,80
# connect any client to gpt-researcher using websocket import asyncio import datetime from typing import Dict, List from fastapi import WebSocket from backend.report_type import BasicReport, DetailedReport from gpt_researcher.utils.enum import ReportType class WebSocketManager: """Manage websockets""" def...
# connect any client to gpt-researcher using websocket import asyncio import datetime from typing import Dict, List from fastapi import WebSocket from backend.report_type import BasicReport, DetailedReport from gpt_researcher.utils.enum import ReportType class WebSocketManager: """Manage websockets""" def...
# measure time start_time = datetime.datetime.now() # add customized JSON config file path here config_path = "" # Instead of running the agent directly run it through the different report type classes if report_type == ReportType.DetailedReport.value: researcher = DetailedReport(query=t...
"""Run the agent.""" # measure time start_time = datetime.datetime.now() # add customized JSON config file path here config_path = "" # Instead of running the agent directly run it through the different report type classes if report_type == ReportType.DetailedReport.value: researcher...
72
577
240
817
# connect any client to gpt-researcher using websocket import asyncio import datetime from typing import Dict, List from fastapi import WebSocket from backend.report_type import BasicReport, DetailedReport from gpt_researcher.utils.enum import ReportType class WebSocketManager: """Manage websockets""" def...
# connect any client to gpt-researcher using websocket import asyncio import datetime from typing import Dict, List from fastapi import WebSocket from backend.report_type import BasicReport, DetailedReport from gpt_researcher.utils.enum import ReportType class WebSocketManager: """Manage websockets""" def...
9,564
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/backend/websocket_manager.py
38,39
13,61
connect
WebSocketManager
40,46
39,46
class WebSocketManager: """Manage websockets""" def __init__(self): """Initialize the WebSocketManager class.""" self.active_connections: List[WebSocket] = [] self.sender_tasks: Dict[WebSocket, asyncio.Task] = {} self.message_queues: Dict[WebSocket, asyncio.Queue] = {} asyn...
class WebSocketManager: """Manage websockets""" def __init__(self): """Initialize the WebSocketManager class.""" self.active_connections: List[WebSocket] = [] self.sender_tasks: Dict[WebSocket, asyncio.Task] = {} self.message_queues: Dict[WebSocket, asyncio.Queue] = {} asyn...
await websocket.accept() self.active_connections.append(websocket) self.message_queues[websocket] = asyncio.Queue() self.sender_tasks[websocket] = asyncio.create_task( self.start_sender(websocket))
"""Connect a websocket.""" await websocket.accept() self.active_connections.append(websocket) self.message_queues[websocket] = asyncio.Queue() self.sender_tasks[websocket] = asyncio.create_task( self.start_sender(websocket))
10
405
84
489
# connect any client to gpt-researcher using websocket import asyncio import datetime from typing import Dict, List from fastapi import WebSocket from backend.report_type import BasicReport, DetailedReport from gpt_researcher.utils.enum import ReportType class WebSocketManager: """Manage websockets""" def...
# connect any client to gpt-researcher using websocket import asyncio import datetime from typing import Dict, List from fastapi import WebSocket from backend.report_type import BasicReport, DetailedReport from gpt_researcher.utils.enum import ReportType class WebSocketManager: """Manage websockets""" def...
9,565
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/cli.py
70,71
1,94
main
75,90
71,90
""" Provides a command line interface for the GPTResearcher class. Usage: ```shell python cli.py "<query>" --report_type <report_type> ``` """ import asyncio import argparse from argparse import RawTextHelpFormatter from uuid import uuid4 from dotenv import load_dotenv from gpt_researcher import GPTResearcher from...
""" Provides a command line interface for the GPTResearcher class. Usage: ```shell python cli.py "<query>" --report_type <report_type> ``` """ import asyncio import argparse from argparse import RawTextHelpFormatter from uuid import uuid4 from dotenv import load_dotenv from gpt_researcher import GPTResearcher from...
researcher = GPTResearcher( query=args.query, report_type=args.report_type) await researcher.conduct_research() report = await researcher.write_report() # Write the report to a file artifact_filepath = f"outputs/{uuid4()}.md" with open(artifact_filepath, "w") as f: f.w...
""" Conduct research on the given query, generate the report, and write it as a markdown file to the output directory. """ researcher = GPTResearcher( query=args.query, report_type=args.report_type) await researcher.conduct_research() report = await researcher.write_report...
31
586
142
728
""" Provides a command line interface for the GPTResearcher class. Usage: ```shell python cli.py "<query>" --report_type <report_type> ``` """ import asyncio import argparse from argparse import RawTextHelpFormatter from uuid import uuid4 from dotenv import load_dotenv from gpt_researcher import GPTResearcher from...
""" Provides a command line interface for the GPTResearcher class. Usage: ```shell python cli.py "<query>" --report_type <report_type> ``` """ import asyncio import argparse from argparse import RawTextHelpFormatter from uuid import uuid4 from dotenv import load_dotenv from gpt_researcher import GPTResearcher from...
9,566
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/examples/sample_report.py
5,6
1,27
main
9,25
6,25
from gpt_researcher import GPTResearcher import asyncio async def main(): FILL_FUNC_BODYif __name__ == "__main__": asyncio.run(main())
from gpt_researcher import GPTResearcher import asyncio async def main(): """ This is a sample script that shows how to run a research report. """ FILL_FUNC_BODYif __name__ == "__main__": asyncio.run(main())
# Query query = "What happened in the latest burning man floods?" # Report Type report_type = "research_report" # Initialize the researcher researcher = GPTResearcher(query=query, report_type=report_type, config_path=None) # Conduct research on the given query await researcher.conduct_...
""" This is a sample script that shows how to run a research report. """ # Query query = "What happened in the latest burning man floods?" # Report Type report_type = "research_report" # Initialize the researcher researcher = GPTResearcher(query=query, report_type=report_type, conf...
46
77
138
215
from gpt_researcher import GPTResearcher import asyncio async def main(): FILL_FUNC_BODYif __name__ == "__main__": asyncio.run(main())
from gpt_researcher import GPTResearcher import asyncio async def main(): """ This is a sample script that shows how to run a research report. """ FILL_FUNC_BODYif __name__ == "__main__": asyncio.run(main())
9,567
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/config/config.py
35,36
6,44
load_config_file
Config
37,44
36,44
class Config: """Config class for GPT Researcher.""" def __init__(self, config_file: str = None): """Initialize the config class.""" self.config_file = config_file if config_file else os.getenv('CONFIG_FILE') self.retriever = os.getenv('SEARCH_RETRIEVER', "tavily") self.embeddin...
class Config: """Config class for GPT Researcher.""" def __init__(self, config_file: str = None): """Initialize the config class.""" self.config_file = config_file if config_file else os.getenv('CONFIG_FILE') self.retriever = os.getenv('SEARCH_RETRIEVER', "tavily") self.embeddin...
if self.config_file is None: return None with open(self.config_file, "r") as f: config = json.load(f) for key, value in config.items(): self.__dict__[key] = value
"""Load the config file.""" if self.config_file is None: return None with open(self.config_file, "r") as f: config = json.load(f) for key, value in config.items(): self.__dict__[key] = value
22
732
72
804
# config file import json import os class Config: """Config class for GPT Researcher.""" def __init__(self, config_file: str = None): """Initialize the config class.""" self.config_file = config_file if config_file else os.getenv('CONFIG_FILE') self.retriever = os.getenv('SEARCH_RETRI...
# config file import json import os class Config: """Config class for GPT Researcher.""" def __init__(self, config_file: str = None): """Initialize the config class.""" self.config_file = config_file if config_file else os.getenv('CONFIG_FILE') self.retriever = os.getenv('SEARCH_RETRI...
9,568
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/context/compression.py
20,21
12,45
_get_contextual_retriever
ContextCompressor
21,35
21,35
class ContextCompressor: def __init__(self, documents, embeddings, max_results=5, **kwargs): self.max_results = max_results self.documents = documents self.kwargs = kwargs self.embeddings = embeddings self.similarity_threshold = 0.38 def _get_contextual_retriever(self): ...
class ContextCompressor: def __init__(self, documents, embeddings, max_results=5, **kwargs): self.max_results = max_results self.documents = documents self.kwargs = kwargs self.embeddings = embeddings self.similarity_threshold = 0.38 def _get_contextual_retriever(self): ...
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100) relevance_filter = EmbeddingsFilter(embeddings=self.embeddings, similarity_threshold=self.similarity_threshold) pipeline_compressor = DocumentCompressorPipeline( ...
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100) relevance_filter = EmbeddingsFilter(embeddings=self.embeddings, similarity_threshold=self.similarity_threshold) pipeline_compressor = DocumentCompressorPipeline( ...
27
277
195
472
from .retriever import SearchAPIRetriever from langchain.retrievers import ( ContextualCompressionRetriever, ) from langchain.retrievers.document_compressors import ( DocumentCompressorPipeline, EmbeddingsFilter, ) from langchain.text_splitter import RecursiveCharacterTextSplitter class ContextCompressor:...
from .retriever import SearchAPIRetriever from langchain.retrievers import ( ContextualCompressionRetriever, ) from langchain.retrievers.document_compressors import ( DocumentCompressorPipeline, EmbeddingsFilter, ) from langchain.text_splitter import RecursiveCharacterTextSplitter class ContextCompressor:...
9,569
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/context/retriever.py
14,17
10,30
_get_relevant_documents
SearchAPIRetriever
17,30
17,30
class SearchAPIRetriever(BaseRetriever): """Search API retriever.""" pages: List[Dict] = [] def _get_relevant_documents( self, query: str, *, run_manager: CallbackManagerForRetrieverRun ) -> List[Document]: FILL_FUNC_BODY
class SearchAPIRetriever(BaseRetriever): """Search API retriever.""" pages: List[Dict] = [] def _get_relevant_documents( self, query: str, *, run_manager: CallbackManagerForRetrieverRun ) -> List[Document]: FILL_FUNC_BODY
docs = [ Document( page_content=page.get("raw_content", ""), metadata={ "title": page.get("title", ""), "source": page.get("url", ""), }, ) for page in self.pages ] retur...
docs = [ Document( page_content=page.get("raw_content", ""), metadata={ "title": page.get("title", ""), "source": page.get("url", ""), }, ) for page in self.pages ] retur...
22
88
94
182
import os from enum import Enum from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForRetrieverRun from langchain.schema import Document from langchain.schema.retriever import BaseRetriever class SearchAPIRetriever(BaseRetriever): """Search API retriever.""" p...
import os from enum import Enum from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForRetrieverRun from langchain.schema import Document from langchain.schema.retriever import BaseRetriever class SearchAPIRetriever(BaseRetriever): """Search API retriever.""" p...
9,570
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/llm_provider/azureopenai/azureopenai.py
68,69
20,86
stream_response
AzureOpenAIProvider
69,86
69,86
class AzureOpenAIProvider: def __init__( self, deployment_name, temperature, max_tokens ): self.deployment_name = deployment_name self.temperature = temperature self.max_tokens = max_tokens self.api_key = self.get_api_key() self.llm = self...
class AzureOpenAIProvider: def __init__( self, deployment_name, temperature, max_tokens ): self.deployment_name = deployment_name self.temperature = temperature self.max_tokens = max_tokens self.api_key = self.get_api_key() self.llm = self...
paragraph = "" response = "" # Streaming the response using the chain astream method from langchain async for chunk in self.llm.astream(messages): content = chunk.content if content is not None: response += content paragraph += con...
paragraph = "" response = "" # Streaming the response using the chain astream method from langchain async for chunk in self.llm.astream(messages): content = chunk.content if content is not None: response += content paragraph += con...
57
406
162
568
import os from colorama import Fore, Style from langchain_openai import AzureChatOpenAI ''' Please note: Needs additional env vars such as: AZURE_OPENAI_ENDPOINT e.g. https://xxxx.openai.azure.com/", AZURE_OPENAI_API_KEY e.g "xxxxxxxxxxxxxxxxxxxxx", OPENAI_API_VERSION, e.g. "2024-03-01-preview" but need...
import os from colorama import Fore, Style from langchain_openai import AzureChatOpenAI ''' Please note: Needs additional env vars such as: AZURE_OPENAI_ENDPOINT e.g. https://xxxx.openai.azure.com/", AZURE_OPENAI_API_KEY e.g "xxxxxxxxxxxxxxxxxxxxx", OPENAI_API_VERSION, e.g. "2024-03-01-preview" but need...
9,571
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/llm_provider/google/google.py
86,87
8,104
stream_response
GoogleProvider
87,104
87,104
class GoogleProvider: def __init__( self, model, temperature, max_tokens ): # May be extended to support more google models in the future self.model = "gemini-pro" self.temperature = temperature self.max_tokens = max_tokens self.api_key = ...
class GoogleProvider: def __init__( self, model, temperature, max_tokens ): # May be extended to support more google models in the future self.model = "gemini-pro" self.temperature = temperature self.max_tokens = max_tokens self.api_key = ...
paragraph = "" response = "" # Streaming the response using the chain astream method from langchain async for chunk in self.llm.astream(messages): content = chunk.content if content is not None: response += content paragraph += con...
paragraph = "" response = "" # Streaming the response using the chain astream method from langchain async for chunk in self.llm.astream(messages): content = chunk.content if content is not None: response += content paragraph += con...
57
731
161
892
import os from colorama import Fore, Style from langchain_core.messages import HumanMessage, SystemMessage from langchain_google_genai import ChatGoogleGenerativeAI class GoogleProvider: def __init__( self, model, temperature, max_tokens ): # May be extended to suppor...
import os from colorama import Fore, Style from langchain_core.messages import HumanMessage, SystemMessage from langchain_google_genai import ChatGoogleGenerativeAI class GoogleProvider: def __init__( self, model, temperature, max_tokens ): # May be extended to suppor...
9,573
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/llm_provider/openai/openai.py
22,23
7,86
get_api_key
OpenAIProvider
28,35
23,35
class OpenAIProvider: def __init__( self, model, temperature, max_tokens ): self.model = model self.temperature = temperature self.max_tokens = max_tokens self.api_key = self.get_api_key() self.base_url = self.get_base_url() self.l...
class OpenAIProvider: def __init__( self, model, temperature, max_tokens ): self.model = model self.temperature = temperature self.max_tokens = max_tokens self.api_key = self.get_api_key() self.base_url = self.get_base_url() self.l...
try: api_key = os.environ["OPENAI_API_KEY"] except KeyError: raise Exception( "OpenAI API key not found. Please set the OPENAI_API_KEY environment variable.") return api_key
""" Gets the OpenAI API key Returns: """ try: api_key = os.environ["OPENAI_API_KEY"] except KeyError: raise Exception( "OpenAI API key not found. Please set the OPENAI_API_KEY environment variable.") return api_key
21
575
71
646
import os from colorama import Fore, Style from langchain_openai import ChatOpenAI class OpenAIProvider: def __init__( self, model, temperature, max_tokens ): self.model = model self.temperature = temperature self.max_tokens = max_tokens self.a...
import os from colorama import Fore, Style from langchain_openai import ChatOpenAI class OpenAIProvider: def __init__( self, model, temperature, max_tokens ): self.model = model self.temperature = temperature self.max_tokens = max_tokens self.a...
9,575
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/retrievers/bing/bing.py
34,35
9,89
search
BingSearch
40,89
35,89
class BingSearch(): """ Bing Search Retriever """ def __init__(self, query): """ Initializes the BingSearch object Args: query: """ self.query = query self.api_key = self.get_api_key() def get_api_key(self): """ Gets the Bi...
class BingSearch(): """ Bing Search Retriever """ def __init__(self, query): """ Initializes the BingSearch object Args: query: """ self.query = query self.api_key = self.get_api_key() def get_api_key(self): """ Gets the Bi...
print("Searching with query {0}...".format(self.query)) """Useful for general internet search queries using the Bing API.""" # Search the query url = "https://api.bing.microsoft.com/v7.0/search" headers = { 'Ocp-Apim-Subscription-Key': self.api_key, 'Content-Ty...
""" Searches the query Returns: """ print("Searching with query {0}...".format(self.query)) """Useful for general internet search queries using the Bing API.""" # Search the query url = "https://api.bing.microsoft.com/v7.0/search" headers = { ...
119
206
440
646
# Bing Search Retriever # libraries import os import requests import json class BingSearch(): """ Bing Search Retriever """ def __init__(self, query): """ Initializes the BingSearch object Args: query: """ self.query = query self.api_key = s...
# Bing Search Retriever # libraries import os import requests import json class BingSearch(): """ Bing Search Retriever """ def __init__(self, query): """ Initializes the BingSearch object Args: query: """ self.query = query self.api_key = s...
9,576
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/retrievers/duckduckgo/duckduckgo.py
13,14
5,22
search
Duckduckgo
20,22
14,22
class Duckduckgo: """ Duckduckgo API Retriever """ def __init__(self, query): self.ddg = DDGS() self.query = query def search(self, max_results=5): FILL_FUNC_BODY
class Duckduckgo: """ Duckduckgo API Retriever """ def __init__(self, query): self.ddg = DDGS() self.query = query def search(self, max_results=5): """ Performs the search :param query: :param max_results: :return: """ FILL_FUNC_BODY
ddgs_gen = self.ddg.text(self.query, region='wt-wt', max_results=max_results) return ddgs_gen
""" Performs the search :param query: :param max_results: :return: """ ddgs_gen = self.ddg.text(self.query, region='wt-wt', max_results=max_results) return ddgs_gen
7
108
43
151
from itertools import islice from duckduckgo_search import DDGS class Duckduckgo: """ Duckduckgo API Retriever """ def __init__(self, query): self.ddg = DDGS() self.query = query def search(self, max_results=5): FILL_FUNC_BODY
from itertools import islice from duckduckgo_search import DDGS class Duckduckgo: """ Duckduckgo API Retriever """ def __init__(self, query): self.ddg = DDGS() self.query = query def search(self, max_results=5): """ Performs the search :param query: ...
9,577
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/retrievers/google/google.py
53,54
10,89
search
GoogleSearch
59,89
54,89
class GoogleSearch: """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ self.query = query self.api_key = self.get_api_key() #GOOGLE_API_KEY self.cx_key = self.get_cx_key() #G...
class GoogleSearch: """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ self.query = query self.api_key = self.get_api_key() #GOOGLE_API_KEY self.cx_key = self.get_cx_key() #G...
"""Useful for general internet search queries using the Google API.""" print("Searching with query {0}...".format(self.query)) url = f"https://www.googleapis.com/customsearch/v1?key={self.api_key}&cx={self.cx_key}&q={self.query}&start=1" resp = requests.get(url) if resp is None:...
""" Searches the query Returns: """ """Useful for general internet search queries using the Google API.""" print("Searching with query {0}...".format(self.query)) url = f"https://www.googleapis.com/customsearch/v1?key={self.api_key}&cx={self.cx_key}&q={self.query...
82
430
304
734
# Tavily API Retriever # libraries import os import requests import json from tavily import TavilyClient class GoogleSearch: """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ self.query ...
# Tavily API Retriever # libraries import os import requests import json from tavily import TavilyClient class GoogleSearch: """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ self.query ...
9,578
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/retrievers/searx/searx.py
37,38
9,48
search
SearxSearch
43,48
38,48
class SearxSearch(): """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ self.query = query self.api_key = self.get_api_key() self.client = TavilyClient(self.api_key) def...
class SearxSearch(): """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ self.query = query self.api_key = self.get_api_key() self.client = TavilyClient(self.api_key) def...
searx = SearxSearchWrapper(searx_host=os.environ["SEARX_URL"]) results = searx.results(self.query, max_results) # Normalizing results to match the format of the other search APIs search_response = [{"href": obj["link"], "body": obj["snippet"]} for obj in results] return search_re...
""" Searches the query Returns: """ searx = SearxSearchWrapper(searx_host=os.environ["SEARX_URL"]) results = searx.results(self.query, max_results) # Normalizing results to match the format of the other search APIs search_response = [{"href": obj["link"],...
31
252
104
356
# Tavily API Retriever # libraries import os from tavily import TavilyClient from langchain_community.utilities import SearxSearchWrapper class SearxSearch(): """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: quer...
# Tavily API Retriever # libraries import os from tavily import TavilyClient from langchain_community.utilities import SearxSearchWrapper class SearxSearch(): """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: quer...
9,579
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/retrievers/serpapi/serpapi.py
36,37
9,79
search
SerpApiSearch
42,79
37,79
class SerpApiSearch(): """ SerpApi Retriever """ def __init__(self, query): """ Initializes the SerpApiSearch object Args: query: """ raise NotImplementedError("SerpApiSearch is not fully implemented yet.") self.query = query self.api_k...
class SerpApiSearch(): """ SerpApi Retriever """ def __init__(self, query): """ Initializes the SerpApiSearch object Args: query: """ raise NotImplementedError("SerpApiSearch is not fully implemented yet.") self.query = query self.api_k...
print("Searching with query {0}...".format(self.query)) """Useful for general internet search queries using SerpApi.""" # Perform the search # TODO: query needs to be url encoded, so the code won't work as is. # Encoding should look something like this (but this is untested): ...
""" Searches the query Returns: """ print("Searching with query {0}...".format(self.query)) """Useful for general internet search queries using SerpApi.""" # Perform the search # TODO: query needs to be url encoded, so the code won't work as is. ...
127
250
380
630
# SerpApi Retriever # libraries import os import requests import json class SerpApiSearch(): """ SerpApi Retriever """ def __init__(self, query): """ Initializes the SerpApiSearch object Args: query: """ raise NotImplementedError("SerpApiSearch is n...
# SerpApi Retriever # libraries import os import requests import json class SerpApiSearch(): """ SerpApi Retriever """ def __init__(self, query): """ Initializes the SerpApiSearch object Args: query: """ raise NotImplementedError("SerpApiSearch is n...
9,580
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/retrievers/serper/serper.py
35,36
9,82
search
SerperSearch
41,82
36,82
class SerperSearch(): """ Google Serper Retriever """ def __init__(self, query): """ Initializes the SerperSearch object Args: query: """ self.query = query self.api_key = self.get_api_key() def get_api_key(self): """ Gets ...
class SerperSearch(): """ Google Serper Retriever """ def __init__(self, query): """ Initializes the SerperSearch object Args: query: """ self.query = query self.api_key = self.get_api_key() def get_api_key(self): """ Gets ...
print("Searching with query {0}...".format(self.query)) """Useful for general internet search queries using the Serp API.""" # Search the query (see https://serper.dev/playground for the format) url = "https://google.serper.dev/search" headers = { 'X-API-KEY': self.api...
""" Searches the query Returns: """ print("Searching with query {0}...".format(self.query)) """Useful for general internet search queries using the Serp API.""" # Search the query (see https://serper.dev/playground for the format) url = "https://google....
110
224
372
596
# Google Serper Retriever # libraries import os import requests import json class SerperSearch(): """ Google Serper Retriever """ def __init__(self, query): """ Initializes the SerperSearch object Args: query: """ self.query = query self.api...
# Google Serper Retriever # libraries import os import requests import json class SerperSearch(): """ Google Serper Retriever """ def __init__(self, query): """ Initializes the SerperSearch object Args: query: """ self.query = query self.api...
9,581
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/retrievers/tavily_news/tavily_news.py
23,24
8,48
get_api_key
TavilyNews
29,37
24,37
class TavilyNews(): """ Tavily News API Retriever Retrieve news articles from the Tavily News API """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ self.query = query self.api_key = self.get_api_key() ...
class TavilyNews(): """ Tavily News API Retriever Retrieve news articles from the Tavily News API """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ self.query = query self.api_key = self.get_api_key() ...
# Get the API key try: api_key = os.environ["TAVILY_API_KEY"] except: raise Exception("Tavily API key not found. Please set the TAVILY_API_KEY environment variable. " "You can get a key at https://app.tavily.com") return api_key
""" Gets the Tavily API key Returns: """ # Get the API key try: api_key = os.environ["TAVILY_API_KEY"] except: raise Exception("Tavily API key not found. Please set the TAVILY_API_KEY environment variable. " "Yo...
32
271
97
368
# Tavily API Retriever # libraries import os from tavily import TavilyClient class TavilyNews(): """ Tavily News API Retriever Retrieve news articles from the Tavily News API """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: ...
# Tavily API Retriever # libraries import os from tavily import TavilyClient class TavilyNews(): """ Tavily News API Retriever Retrieve news articles from the Tavily News API """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: ...
9,582
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/retrievers/tavily_search/tavily_search.py
37,38
9,53
search
TavilySearch
43,53
38,53
class TavilySearch(): """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ self.query = query self.api_key = self.get_api_key() self.client = TavilyClient(self.api_key) de...
class TavilySearch(): """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ self.query = query self.api_key = self.get_api_key() self.client = TavilyClient(self.api_key) de...
try: # Search the query results = self.client.search(self.query, search_depth="advanced", max_results=max_results) # Return the results search_response = [{"href": obj["url"], "body": obj["content"]} for obj in results.get("results", [])] except Exception ...
""" Searches the query Returns: """ try: # Search the query results = self.client.search(self.query, search_depth="advanced", max_results=max_results) # Return the results search_response = [{"href": obj["url"], "body": obj["conten...
50
259
169
428
# Tavily API Retriever # libraries import os from tavily import TavilyClient from duckduckgo_search import DDGS class TavilySearch(): """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ se...
# Tavily API Retriever # libraries import os from tavily import TavilyClient from duckduckgo_search import DDGS class TavilySearch(): """ Tavily API Retriever """ def __init__(self, query): """ Initializes the TavilySearch object Args: query: """ se...
9,583
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/scraper/arxiv/arxiv.py
10,11
4,23
scrape
ArxivScraper
19,23
11,23
class ArxivScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self): FILL_FUNC_BODY
class ArxivScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self): """ The function scrapes relevant documents from Arxiv based on a given link and returns the content of the first document. Returns: ...
query = self.link.split("/")[-1] retriever = ArxivRetriever(load_max_docs=2, doc_content_chars_max=None) docs = retriever.get_relevant_documents(query=query) return docs[0].page_content
""" The function scrapes relevant documents from Arxiv based on a given link and returns the content of the first document. Returns: The code is returning the page content of the first document retrieved by the ArxivRetriever for a given query extracted from th...
12
131
82
213
from langchain_community.retrievers import ArxivRetriever class ArxivScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self): FILL_FUNC_BODY
from langchain_community.retrievers import ArxivRetriever class ArxivScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self): """ The function scrapes relevant documents from Arxiv based on a given link and returns the content...
9,584
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/scraper/beautiful_soup/beautiful_soup.py
40,41
4,54
get_content_from_url
BeautifulSoupScraper
49,54
41,54
class BeautifulSoupScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self): """ This function scrapes content from a webpage by making a GET request, parsing the HTML using BeautifulSoup, and extracting script and style ...
class BeautifulSoupScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self): """ This function scrapes content from a webpage by making a GET request, parsing the HTML using BeautifulSoup, and extracting script and style ...
text = "" tags = ["p", "h1", "h2", "h3", "h4", "h5"] for element in soup.find_all(tags): # Find all the <p> elements text += element.text + "\n" return text
"""Get the text from the soup Args: soup (BeautifulSoup): The soup to get the text from Returns: str: The text from the soup """ text = "" tags = ["p", "h1", "h2", "h3", "h4", "h5"] for element in soup.find_all(tags): # Find all the <p> ...
28
457
74
531
from bs4 import BeautifulSoup class BeautifulSoupScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self): """ This function scrapes content from a webpage by making a GET request, parsing the HTML using BeautifulSoup, ...
from bs4 import BeautifulSoup class BeautifulSoupScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self): """ This function scrapes content from a webpage by making a GET request, parsing the HTML using BeautifulSoup, ...
9,585
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/scraper/newspaper/newspaper.py
10,11
4,43
scrape
NewspaperScraper
21,43
11,43
class NewspaperScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: FILL_FUNC_BODY
class NewspaperScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: """ This Python function scrapes an article from a given link, extracts the title and text content, and returns them concatenated with a colo...
try: article = Article( self.link, language="en", memoize_articles=False, fetch_images=False, ) article.download() article.parse() title = article.title text = article.text ...
""" This Python function scrapes an article from a given link, extracts the title and text content, and returns them concatenated with a colon. Returns: The `scrape` method returns a string that contains the title of the article followed by a colon and the text...
49
179
159
338
from newspaper import Article class NewspaperScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: FILL_FUNC_BODY
from newspaper import Article class NewspaperScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: """ This Python function scrapes an article from a given link, extracts the title and text content, and retur...
9,586
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/scraper/pymupdf/pymupdf.py
10,11
4,22
scrape
PyMuPDFScraper
19,22
11,22
class PyMuPDFScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: FILL_FUNC_BODY
class PyMuPDFScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: """ The `scrape` function uses PyMuPDFLoader to load a document from a given link and returns it as a string. Returns: ...
loader = PyMuPDFLoader(self.link) doc = loader.load() return str(doc)
""" The `scrape` function uses PyMuPDFLoader to load a document from a given link and returns it as a string. Returns: The `scrape` method is returning a string representation of the `doc` object, which is loaded using PyMuPDFLoader from the provided link. ...
8
143
32
175
from langchain_community.document_loaders import PyMuPDFLoader class PyMuPDFScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: FILL_FUNC_BODY
from langchain_community.document_loaders import PyMuPDFLoader class PyMuPDFScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: """ The `scrape` function uses PyMuPDFLoader to load a document from a given link and ...
9,587
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/scraper/scraper.py
41,42
15,96
extract_data_from_link
Scraper
45,57
42,57
class Scraper: """ Scraper class to extract the content from the links """ def __init__(self, urls, user_agent, scraper): """ Initialize the Scraper class. Args: urls: """ self.urls = urls self.session = requests.Session() self.session...
class Scraper: """ Scraper class to extract the content from the links """ def __init__(self, urls, user_agent, scraper): """ Initialize the Scraper class. Args: urls: """ self.urls = urls self.session = requests.Session() self.session...
content = "" try: Scraper = self.get_scraper(link) scraper = Scraper(link, session) content = scraper.scrape() if len(content) < 100: return {"url": link, "raw_content": None} return {"url": link, "raw_content": content} ...
""" Extracts the data from the link """ content = "" try: Scraper = self.get_scraper(link) scraper = Scraper(link, session) content = scraper.scrape() if len(content) < 100: return {"url": link, "raw_content": None}...
37
727
127
854
from concurrent.futures.thread import ThreadPoolExecutor from functools import partial import requests from gpt_researcher.scraper import ( ArxivScraper, BeautifulSoupScraper, NewspaperScraper, PyMuPDFScraper, WebBaseLoaderScraper, ) class Scraper: """ Scraper class to extract the conten...
from concurrent.futures.thread import ThreadPoolExecutor from functools import partial import requests from gpt_researcher.scraper import ( ArxivScraper, BeautifulSoupScraper, NewspaperScraper, PyMuPDFScraper, WebBaseLoaderScraper, ) class Scraper: """ Scraper class to extract the conten...
9,588
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/gpt_researcher/scraper/web_base_loader/web_base_loader.py
10,11
4,34
scrape
WebBaseLoaderScraper
20,34
11,34
class WebBaseLoaderScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: FILL_FUNC_BODY
class WebBaseLoaderScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: """ This Python function scrapes content from a webpage using a WebBaseLoader object and returns the concatenated page content. ...
try: loader = WebBaseLoader(self.link) loader.requests_kwargs = {"verify": False} docs = loader.load() content = "" for doc in docs: content += doc.page_content return content except Exception as e: pr...
""" This Python function scrapes content from a webpage using a WebBaseLoader object and returns the concatenated page content. Returns: The `scrape` method is returning a string variable named `content` which contains the concatenated page content from the doc...
34
162
107
269
from langchain_community.document_loaders import WebBaseLoader class WebBaseLoaderScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: FILL_FUNC_BODY
from langchain_community.document_loaders import WebBaseLoader class WebBaseLoaderScraper: def __init__(self, link, session=None): self.link = link self.session = session def scrape(self) -> str: """ This Python function scrapes content from a webpage using a WebBaseLoader ob...
9,589
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/multi_agents/agents/publisher.py
19,20
9,58
generate_layout
PublisherAgent
20,44
20,44
class PublisherAgent: def __init__(self, output_dir: str): self.output_dir = output_dir async def publish_research_report(self, research_state: dict, publish_formats: dict): layout = self.generate_layout(research_state) await self.write_report_by_formats(layout, publish_formats) ...
class PublisherAgent: def __init__(self, output_dir: str): self.output_dir = output_dir async def publish_research_report(self, research_state: dict, publish_formats: dict): layout = self.generate_layout(research_state) await self.write_report_by_formats(layout, publish_formats) ...
sections = '\n\n'.join(f"{value}" for subheader in research_state.get("research_data") for key, value in subheader.items()) references = '\n'.join(f"{reference}" for reference in research_state.get("sources")) headers = research_s...
sections = '\n\n'.join(f"{value}" for subheader in research_state.get("research_data") for key, value in subheader.items()) references = '\n'.join(f"{reference}" for reference in research_state.get("sources")) headers = research_s...
45
367
253
620
from .utils.file_formats import \ write_md_to_pdf, \ write_md_to_word, \ write_text_to_md from .utils.views import print_agent_output class PublisherAgent: def __init__(self, output_dir: str): self.output_dir = output_dir async def publish_research_report(self, research_state: dict, publ...
from .utils.file_formats import \ write_md_to_pdf, \ write_md_to_word, \ write_text_to_md from .utils.views import print_agent_output class PublisherAgent: def __init__(self, output_dir: str): self.output_dir = output_dir async def publish_research_report(self, research_state: dict, publ...
9,590
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/multi_agents/agents/reviewer.py
12,13
8,63
review_draft
ReviewerAgent
18,50
13,50
class ReviewerAgent: def __init__(self): pass def review_draft(self, draft_state: dict): FILL_FUNC_BODY def run(self, draft_state: dict): task = draft_state.get("task") guidelines = task.get("guidelines") to_follow_guidelines = task.get("follow_guidelines") review = N...
class ReviewerAgent: def __init__(self): pass def review_draft(self, draft_state: dict): """ Review a draft article :param draft_state: :return: """ FILL_FUNC_BODY def run(self, draft_state: dict): task = draft_state.get("task") guidelines = ta...
task = draft_state.get("task") guidelines = '- '.join(guideline for guideline in task.get("guidelines")) revision_notes = draft_state.get("revision_notes") revise_prompt = f"""The reviser has already revised the draft based on your previous review notes with the following feedback: {rev...
""" Review a draft article :param draft_state: :return: """ task = draft_state.get("task") guidelines = '- '.join(guideline for guideline in task.get("guidelines")) revision_notes = draft_state.get("revision_notes") revise_prompt = f"""The reviser...
177
265
394
659
from .utils.views import print_agent_output from .utils.llms import call_model TEMPLATE = """You are an expert research article reviewer. \ Your goal is to review research drafts and provide feedback to the reviser only based on specific guidelines. \ """ class ReviewerAgent: def __init__(self): pass ...
from .utils.views import print_agent_output from .utils.llms import call_model TEMPLATE = """You are an expert research article reviewer. \ Your goal is to review research drafts and provide feedback to the reviser only based on specific guidelines. \ """ class ReviewerAgent: def __init__(self): pass ...
9,591
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/multi_agents/agents/reviser.py
18,19
14,51
revise_draft
ReviserAgent
24,44
19,44
class ReviserAgent: def __init__(self): pass def revise_draft(self, draft_state: dict): FILL_FUNC_BODY def run(self, draft_state: dict): draft_title = draft_state.get("title") print_agent_output(f"Rewriting draft based on feedback...", agent="REVISOR") revision = self.revise_...
class ReviserAgent: def __init__(self): pass def revise_draft(self, draft_state: dict): """ Review a draft article :param draft_state: :return: """ FILL_FUNC_BODY def run(self, draft_state: dict): draft_title = draft_state.get("title") print_ag...
review = draft_state.get("review") task = draft_state.get("task") draft_report = draft_state.get("draft") prompt = [{ "role": "system", "content": "You are an expert writer. Your goal is to revise drafts based on reviewer notes." }, { "role": "...
""" Review a draft article :param draft_state: :return: """ review = draft_state.get("review") task = draft_state.get("task") draft_report = draft_state.get("draft") prompt = [{ "role": "system", "content": "You are an exper...
112
208
279
487
from .utils.views import print_agent_output from .utils.llms import call_model import json sample_revision_notes = """ { "draft": { draft title: The revised draft that you are submitting for review }, "revision_notes": Your message to the reviewer about the changes you made to the draft based on their feed...
from .utils.views import print_agent_output from .utils.llms import call_model import json sample_revision_notes = """ { "draft": { draft title: The revised draft that you are submitting for review }, "revision_notes": Your message to the reviewer about the changes you made to the draft based on their feed...
9,592
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/multi_agents/agents/utils/file_formats.py
10,11
1,99
write_to_file
17,24
11,24
import aiofiles import urllib import uuid import mistune from md2pdf.core import md2pdf from docx import Document from htmldocx import HtmlToDocx async def write_to_file(filename: str, text: str) -> None: FILL_FUNC_BODYasync def write_text_to_md(text: str, path: str) -> str: """Writes text to a Markdown file and ...
import aiofiles import urllib import uuid import mistune from md2pdf.core import md2pdf from docx import Document from htmldocx import HtmlToDocx async def write_to_file(filename: str, text: str) -> None: """Asynchronously write text to a file in UTF-8 encoding. Args: filename (str): The filename to ...
# Convert text to UTF-8, replacing any problematic characters text_utf8 = text.encode('utf-8', errors='replace').decode('utf-8') async with aiofiles.open(filename, "w", encoding='utf-8') as file: await file.write(text_utf8)
"""Asynchronously write text to a file in UTF-8 encoding. Args: filename (str): The filename to write to. text (str): The text to write. """ # Convert text to UTF-8, replacing any problematic characters text_utf8 = text.encode('utf-8', errors='replace').decode('utf-8') async wi...
22
825
90
915
import aiofiles import urllib import uuid import mistune from md2pdf.core import md2pdf from docx import Document from htmldocx import HtmlToDocx async def write_to_file(filename: str, text: str) -> None: FILL_FUNC_BODYasync def write_text_to_md(text: str, path: str) -> str: """Writes text to a Markdown file and ...
import aiofiles import urllib import uuid import mistune from md2pdf.core import md2pdf from docx import Document from htmldocx import HtmlToDocx async def write_to_file(filename: str, text: str) -> None: """Asynchronously write text to a file in UTF-8 encoding. Args: filename (str): The filename to ...
9,593
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/multi_agents/agents/utils/llms.py
5,6
1,16
call_model
6,16
6,16
from langchain.adapters.openai import convert_openai_messages from langchain_openai import ChatOpenAI def call_model(prompt: list, model: str, max_retries: int = 2, response_format: str = None) -> str: FILL_FUNC_BODY
from langchain.adapters.openai import convert_openai_messages from langchain_openai import ChatOpenAI def call_model(prompt: list, model: str, max_retries: int = 2, response_format: str = None) -> str: FILL_FUNC_BODY
optional_params = {} if response_format == 'json': optional_params = { "response_format": {"type": "json_object"} } lc_messages = convert_openai_messages(prompt) response = ChatOpenAI(model=model, max_retries=max_retries, model_kwargs=optional_params).invoke(lc_messages).co...
optional_params = {} if response_format == 'json': optional_params = { "response_format": {"type": "json_object"} } lc_messages = convert_openai_messages(prompt) response = ChatOpenAI(model=model, max_retries=max_retries, model_kwargs=optional_params).invoke(lc_messages).co...
24
77
111
188
from langchain.adapters.openai import convert_openai_messages from langchain_openai import ChatOpenAI def call_model(prompt: list, model: str, max_retries: int = 2, response_format: str = None) -> str: FILL_FUNC_BODY
from langchain.adapters.openai import convert_openai_messages from langchain_openai import ChatOpenAI def call_model(prompt: list, model: str, max_retries: int = 2, response_format: str = None) -> str: FILL_FUNC_BODY
9,594
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/multi_agents/agents/utils/views.py
15,16
1,17
print_agent_output
16,17
16,17
from colorama import Fore, Style from enum import Enum class AgentColor(Enum): RESEARCHER = Fore.LIGHTBLUE_EX EDITOR = Fore.YELLOW WRITER = Fore.LIGHTGREEN_EX PUBLISHER = Fore.MAGENTA REVIEWER = Fore.CYAN REVISOR = Fore.LIGHTWHITE_EX MASTER = Fore.LIGHTYELLOW_EX def print_agent_output(ou...
from colorama import Fore, Style from enum import Enum class AgentColor(Enum): RESEARCHER = Fore.LIGHTBLUE_EX EDITOR = Fore.YELLOW WRITER = Fore.LIGHTGREEN_EX PUBLISHER = Fore.MAGENTA REVIEWER = Fore.CYAN REVISOR = Fore.LIGHTWHITE_EX MASTER = Fore.LIGHTYELLOW_EX def print_agent_output(ou...
print(f"{AgentColor[agent].value}{agent}: {output}{Style.RESET_ALL}")
print(f"{AgentColor[agent].value}{agent}: {output}{Style.RESET_ALL}")
2
155
27
182
from colorama import Fore, Style from enum import Enum class AgentColor(Enum): RESEARCHER = Fore.LIGHTBLUE_EX EDITOR = Fore.YELLOW WRITER = Fore.LIGHTGREEN_EX PUBLISHER = Fore.MAGENTA REVIEWER = Fore.CYAN REVISOR = Fore.LIGHTWHITE_EX MASTER = Fore.LIGHTYELLOW_EX def print_agent_output(ou...
from colorama import Fore, Style from enum import Enum class AgentColor(Enum): RESEARCHER = Fore.LIGHTBLUE_EX EDITOR = Fore.YELLOW WRITER = Fore.LIGHTGREEN_EX PUBLISHER = Fore.MAGENTA REVIEWER = Fore.CYAN REVISOR = Fore.LIGHTWHITE_EX MASTER = Fore.LIGHTYELLOW_EX def print_agent_output(ou...
9,595
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/multi_agents/main.py
13,14
1,23
main
14,21
14,21
from dotenv import load_dotenv from agents import MasterAgent import asyncio import json import os # Run with LangSmith if API key is set if os.environ.get("LANGCHAIN_API_KEY"): os.environ["LANGCHAIN_TRACING_V2"] = "true" load_dotenv() async def main(): FILL_FUNC_BODYif __name__ == "__main__": asyncio.run(ma...
from dotenv import load_dotenv from agents import MasterAgent import asyncio import json import os # Run with LangSmith if API key is set if os.environ.get("LANGCHAIN_API_KEY"): os.environ["LANGCHAIN_TRACING_V2"] = "true" load_dotenv() async def main(): FILL_FUNC_BODYif __name__ == "__main__": asyncio.run(ma...
with open('task.json', 'r') as f: task = json.load(f) master_agent = MasterAgent(task) research_report = await master_agent.run() print(research_report)
with open('task.json', 'r') as f: task = json.load(f) master_agent = MasterAgent(task) research_report = await master_agent.run() print(research_report)
16
123
67
190
from dotenv import load_dotenv from agents import MasterAgent import asyncio import json import os # Run with LangSmith if API key is set if os.environ.get("LANGCHAIN_API_KEY"): os.environ["LANGCHAIN_TRACING_V2"] = "true" load_dotenv() async def main(): FILL_FUNC_BODYif __name__ == "__main__": asyncio.run(ma...
from dotenv import load_dotenv from agents import MasterAgent import asyncio import json import os # Run with LangSmith if API key is set if os.environ.get("LANGCHAIN_API_KEY"): os.environ["LANGCHAIN_TRACING_V2"] = "true" load_dotenv() async def main(): FILL_FUNC_BODYif __name__ == "__main__": asyncio.run(ma...
9,596
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/scraping/processing/html.py
8,9
1,34
extract_hyperlinks
18,24
9,24
"""HTML processing functions""" from __future__ import annotations from bs4 import BeautifulSoup from requests.compat import urljoin def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> list[tuple[str, str]]: FILL_FUNC_BODYdef format_hyperlinks(hyperlinks: list[tuple[str, str]]) -> list[str]: """Format ...
"""HTML processing functions""" from __future__ import annotations from bs4 import BeautifulSoup from requests.compat import urljoin def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> list[tuple[str, str]]: """Extract hyperlinks from a BeautifulSoup object Args: soup (BeautifulSoup): The ...
return [ (link.text, urljoin(base_url, link["href"])) for link in soup.find_all("a", href=True) ]
"""Extract hyperlinks from a BeautifulSoup object Args: soup (BeautifulSoup): The BeautifulSoup object base_url (str): The base URL Returns: List[Tuple[str, str]]: The extracted hyperlinks """ return [ (link.text, urljoin(base_url, link["href"])) for link in...
11
262
51
313
"""HTML processing functions""" from __future__ import annotations from bs4 import BeautifulSoup from requests.compat import urljoin def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> list[tuple[str, str]]: FILL_FUNC_BODYdef format_hyperlinks(hyperlinks: list[tuple[str, str]]) -> list[str]: """Format ...
"""HTML processing functions""" from __future__ import annotations from bs4 import BeautifulSoup from requests.compat import urljoin def extract_hyperlinks(soup: BeautifulSoup, base_url: str) -> list[tuple[str, str]]: """Extract hyperlinks from a BeautifulSoup object Args: soup (BeautifulSoup): The ...
9,597
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher
/home/hieuvd/dung_repo/raw/stars_01/assafelovic_gpt-researcher/gpt-researcher/scraping/scrape_skills.py
19,20
1,32
scrape_pdf_with_arxiv
29,32
20,32
from langchain.document_loaders import PyMuPDFLoader from langchain.retrievers import ArxivRetriever def scrape_pdf_with_pymupdf(url) -> str: """Scrape a pdf with pymupdf Args: url (str): The url of the pdf to scrape Returns: str: The text scraped from the pdf """ loader = PyMuPD...
from langchain.document_loaders import PyMuPDFLoader from langchain.retrievers import ArxivRetriever def scrape_pdf_with_pymupdf(url) -> str: """Scrape a pdf with pymupdf Args: url (str): The url of the pdf to scrape Returns: str: The text scraped from the pdf """ loader = PyMuPD...
retriever = ArxivRetriever(load_max_docs=2, doc_content_chars_max=None) docs = retriever.get_relevant_documents(query=query) return docs[0].page_content
"""Scrape a pdf with arxiv default document length of 70000 about ~15 pages or None for no limit Args: query (str): The query to search for Returns: str: The text scraped from the pdf """ retriever = ArxivRetriever(load_max_docs=2, doc_content_chars_max=None) docs = retriev...
9
232
66
298
from langchain.document_loaders import PyMuPDFLoader from langchain.retrievers import ArxivRetriever def scrape_pdf_with_pymupdf(url) -> str: """Scrape a pdf with pymupdf Args: url (str): The url of the pdf to scrape Returns: str: The text scraped from the pdf """ loader = PyMuPD...
from langchain.document_loaders import PyMuPDFLoader from langchain.retrievers import ArxivRetriever def scrape_pdf_with_pymupdf(url) -> str: """Scrape a pdf with pymupdf Args: url (str): The url of the pdf to scrape Returns: str: The text scraped from the pdf """ loader = PyMuPD...
9,598
/home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn
/home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn/autosklearn/evaluation/util.py
9,12
1,57
read_queue
12,37
12,37
from typing import Any, Dict, List, Optional, Tuple, Union import multiprocessing import queue __all__ = ["read_queue"] def read_queue( queue_: multiprocessing.Queue, ) -> List[Dict[str, Union[str, bool, int, float, List, Dict, Tuple]]]: FILL_FUNC_BODYdef empty_queue(queue_: multiprocessing.Queue) -> None: ...
from typing import Any, Dict, List, Optional, Tuple, Union import multiprocessing import queue __all__ = ["read_queue"] def read_queue( queue_: multiprocessing.Queue, ) -> List[Dict[str, Union[str, bool, int, float, List, Dict, Tuple]]]: FILL_FUNC_BODYdef empty_queue(queue_: multiprocessing.Queue) -> None: ...
stack = [] while True: try: return_value = queue_.get(timeout=1) except queue.Empty: break # Check if there is a special placeholder value which tells us that # we don't have to wait until the queue times out in order to # retrieve the final value...
stack = [] while True: try: return_value = queue_.get(timeout=1) except queue.Empty: break # Check if there is a special placeholder value which tells us that # we don't have to wait until the queue times out in order to # retrieve the final value...
70
262
198
460
from typing import Any, Dict, List, Optional, Tuple, Union import multiprocessing import queue __all__ = ["read_queue"] def read_queue( queue_: multiprocessing.Queue, ) -> List[Dict[str, Union[str, bool, int, float, List, Dict, Tuple]]]: FILL_FUNC_BODYdef empty_queue(queue_: multiprocessing.Queue) -> None: ...
from typing import Any, Dict, List, Optional, Tuple, Union import multiprocessing import queue __all__ = ["read_queue"] def read_queue( queue_: multiprocessing.Queue, ) -> List[Dict[str, Union[str, bool, int, float, List, Dict, Tuple]]]: FILL_FUNC_BODYdef empty_queue(queue_: multiprocessing.Queue) -> None: ...
9,599
/home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn
/home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn/autosklearn/metalearning/mismbo.py
15,18
1,38
suggest_via_metalearning
18,38
18,38
# -*- encoding: utf-8 -*- import time from autosklearn.constants import ( MULTICLASS_CLASSIFICATION, MULTILABEL_CLASSIFICATION, TASK_TYPES_TO_STRING, ) from autosklearn.metalearning.optimizers.metalearn_optimizer.metalearner import ( MetaLearningOptimizer, ) def suggest_via_metalearning( meta_ba...
# -*- encoding: utf-8 -*- import time from autosklearn.constants import ( MULTICLASS_CLASSIFICATION, MULTILABEL_CLASSIFICATION, TASK_TYPES_TO_STRING, ) from autosklearn.metalearning.optimizers.metalearn_optimizer.metalearner import ( MetaLearningOptimizer, ) def suggest_via_metalearning( meta_ba...
if task == MULTILABEL_CLASSIFICATION: task = MULTICLASS_CLASSIFICATION task = TASK_TYPES_TO_STRING[task] logger.info(task) start = time.time() ml = MetaLearningOptimizer( dataset_name=dataset_name, configuration_space=meta_base.configuration_space, meta_base=meta_...
if task == MULTILABEL_CLASSIFICATION: task = MULTICLASS_CLASSIFICATION task = TASK_TYPES_TO_STRING[task] logger.info(task) start = time.time() ml = MetaLearningOptimizer( dataset_name=dataset_name, configuration_space=meta_base.configuration_space, meta_base=meta_...
37
158
219
377
# -*- encoding: utf-8 -*- import time from autosklearn.constants import ( MULTICLASS_CLASSIFICATION, MULTILABEL_CLASSIFICATION, TASK_TYPES_TO_STRING, ) from autosklearn.metalearning.optimizers.metalearn_optimizer.metalearner import ( MetaLearningOptimizer, ) def suggest_via_metalearning( meta_ba...
# -*- encoding: utf-8 -*- import time from autosklearn.constants import ( MULTICLASS_CLASSIFICATION, MULTILABEL_CLASSIFICATION, TASK_TYPES_TO_STRING, ) from autosklearn.metalearning.optimizers.metalearn_optimizer.metalearner import ( MetaLearningOptimizer, ) def suggest_via_metalearning( meta_ba...
9,600
/home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn
/home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn/autosklearn/metalearning/optimizers/metalearn_optimizer/metalearn_optimizer_parser.py
1,2
1,3
manipulate_config
2,3
2,3
def manipulate_config(config): FILL_FUNC_BODY
def manipulate_config(config): FILL_FUNC_BODY
return config
return config
2
19
5
24
def manipulate_config(config): FILL_FUNC_BODY
def manipulate_config(config): FILL_FUNC_BODY
9,601
/home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn
/home/hieuvd/dung_repo/raw/stars_01/automl_auto-sklearn/auto-sklearn/autosklearn/pipeline/components/data_preprocessing/rescaling/none.py
21,25
11,46
get_properties
NoRescalingComponent
25,46
25,46
class NoRescalingComponent(Rescaling, AutoSklearnPreprocessingAlgorithm): def fit( self, X: PIPELINE_DATA_DTYPE, y: Optional[PIPELINE_DATA_DTYPE] = None ) -> "AutoSklearnPreprocessingAlgorithm": self.preprocessor = "passthrough" return self def transform(self, X: PIPELINE_DATA_DTYPE...
class NoRescalingComponent(Rescaling, AutoSklearnPreprocessingAlgorithm): def fit( self, X: PIPELINE_DATA_DTYPE, y: Optional[PIPELINE_DATA_DTYPE] = None ) -> "AutoSklearnPreprocessingAlgorithm": self.preprocessor = "passthrough" return self def transform(self, X: PIPELINE_DATA_DTYPE...
return { "shortname": "NoRescaling", "name": "NoRescaling", "handles_missing_values": False, "handles_nominal_values": False, "handles_numerical_features": True, "prefers_data_scaled": False, "prefers_data_normalized": False, ...
return { "shortname": "NoRescaling", "name": "NoRescaling", "handles_missing_values": False, "handles_nominal_values": False, "handles_numerical_features": True, "prefers_data_scaled": False, "prefers_data_normalized": False, ...
49
192
258
450
from typing import Dict, Optional, Tuple, Union from autosklearn.pipeline.base import DATASET_PROPERTIES_TYPE, PIPELINE_DATA_DTYPE from autosklearn.pipeline.components.base import AutoSklearnPreprocessingAlgorithm from autosklearn.pipeline.components.data_preprocessing.rescaling.abstract_rescaling import ( # noqa: E5...
from typing import Dict, Optional, Tuple, Union from autosklearn.pipeline.base import DATASET_PROPERTIES_TYPE, PIPELINE_DATA_DTYPE from autosklearn.pipeline.components.base import AutoSklearnPreprocessingAlgorithm from autosklearn.pipeline.components.data_preprocessing.rescaling.abstract_rescaling import ( # noqa: E5...