code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get_best_server(self, servers=None):
"""Perform a speedtest.net "ping" to determine which speedtest.net
server has the lowest latency
"""
if not servers:
if not self.closest:
servers = self.get_closest_servers()
servers = self.closest
... | Perform a speedtest.net "ping" to determine which speedtest.net
server has the lowest latency
| get_best_server | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def download(self, callback=do_nothing, threads=None):
"""Test download speed against speedtest.net
A ``threads`` value of ``None`` will fall back to those dictated
by the speedtest.net configuration
"""
urls = []
for size in self.config['sizes']['download']:
... | Test download speed against speedtest.net
A ``threads`` value of ``None`` will fall back to those dictated
by the speedtest.net configuration
| download | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def upload(self, callback=do_nothing, pre_allocate=True, threads=None):
"""Test upload speed against speedtest.net
A ``threads`` value of ``None`` will fall back to those dictated
by the speedtest.net configuration
"""
sizes = []
for size in self.config['sizes']['uploa... | Test upload speed against speedtest.net
A ``threads`` value of ``None`` will fall back to those dictated
by the speedtest.net configuration
| upload | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def ctrl_c(shutdown_event):
"""Catch Ctrl-C key sequence and set a SHUTDOWN_EVENT for our threaded
operations
"""
def inner(signum, frame):
shutdown_event.set()
printer('\nCancelling...', error=True)
sys.exit(0)
return inner | Catch Ctrl-C key sequence and set a SHUTDOWN_EVENT for our threaded
operations
| ctrl_c | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def parse_args():
"""Function to handle building and parsing of command line arguments"""
description = (
'Command line interface for testing internet bandwidth using '
'speedtest.net.\n'
'------------------------------------------------------------'
'--------------\n'
'h... | Function to handle building and parsing of command line arguments | parse_args | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def validate_optional_args(args):
"""Check if an argument was provided that depends on a module that may
not be part of the Python standard library.
If such an argument is supplied, and the module does not exist, exit
with an error stating which module is missing.
"""
optional_args = {
... | Check if an argument was provided that depends on a module that may
not be part of the Python standard library.
If such an argument is supplied, and the module does not exist, exit
with an error stating which module is missing.
| validate_optional_args | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def printer(string, quiet=False, debug=False, error=False, **kwargs):
"""Helper function print a string with various features"""
if debug and not DEBUG:
return
if debug:
if sys.stdout.isatty():
out = '\033[1;30mDEBUG: %s\033[0m' % string
else:
out = 'DEBUG: ... | Helper function print a string with various features | printer | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def shell():
"""Run the full speedtest.net test"""
global DEBUG
shutdown_event = threading.Event()
signal.signal(signal.SIGINT, ctrl_c(shutdown_event))
args = parse_args()
# Print the version and exit
if args.version:
version()
if not args.download and not args.upload:
... | Run the full speedtest.net test | shell | python | sivel/speedtest-cli | speedtest.py | https://github.com/sivel/speedtest-cli/blob/master/speedtest.py | Apache-2.0 |
def from_sub_models_config(
cls,
text_encoder_config: PretrainedConfig,
audio_encoder_config: PretrainedConfig,
decoder_config: ParlerTTSDecoderConfig,
**kwargs,
):
r"""
Instantiate a [`ParlerTTSConfig`] (or a derived class) from text encoder, audio encoder an... |
Instantiate a [`ParlerTTSConfig`] (or a derived class) from text encoder, audio encoder and decoder
configurations.
Returns:
[`ParlerTTSConfig`]: An instance of a configuration object
| from_sub_models_config | python | huggingface/parler-tts | parler_tts/configuration_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/configuration_parler_tts.py | Apache-2.0 |
def apply_delay_pattern_mask(input_ids, decoder_pad_token_mask):
"""Apply a delay pattern mask to the decoder input ids, only preserving predictions where
the mask is set to -1, and otherwise setting to the value detailed in the mask."""
seq_len = input_ids.shape[-1]
decoder_pad_token_mask = decoder_pad... | Apply a delay pattern mask to the decoder input ids, only preserving predictions where
the mask is set to -1, and otherwise setting to the value detailed in the mask. | apply_delay_pattern_mask | python | huggingface/parler-tts | parler_tts/modeling_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/modeling_parler_tts.py | Apache-2.0 |
def build_delay_pattern_mask(
input_ids: torch.LongTensor, bos_token_id: int, pad_token_id: int, max_length: int, num_codebooks: int
):
"""Build a delayed pattern mask to the input_ids. Each codebook is offset by the previous codebook by
one, giving a delayed pattern mask at the start of sequence and end of... | Build a delayed pattern mask to the input_ids. Each codebook is offset by the previous codebook by
one, giving a delayed pattern mask at the start of sequence and end of sequence. Take the example where there
are 4 codebooks and a max sequence length of 8, we have the delayed pattern mask of shape `(codebooks,
... | build_delay_pattern_mask | python | huggingface/parler-tts | parler_tts/modeling_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/modeling_parler_tts.py | Apache-2.0 |
def apply_rotary_pos_emb(x, cos, sin, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
x (`torch.Tensor`): The tensor over which to apply the rope embeddings
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): Th... | Applies Rotary Position Embedding to the query and key tensors.
Args:
x (`torch.Tensor`): The tensor over which to apply the rope embeddings
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
unsqueeze_dim (`in... | apply_rotary_pos_emb | python | huggingface/parler-tts | parler_tts/modeling_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/modeling_parler_tts.py | Apache-2.0 |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
cos: Optional[torch.LongTensor] = None,
sin: Optional[torch.LongTensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[to... |
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
... | forward | python | huggingface/parler-tts | parler_tts/modeling_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/modeling_parler_tts.py | Apache-2.0 |
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.LongTensor] = None,
... |
labels (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks)`, *optional*):
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All lab... | forward | python | huggingface/parler-tts | parler_tts/modeling_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/modeling_parler_tts.py | Apache-2.0 |
def build_delay_pattern_mask(
self, input_ids: torch.LongTensor, bos_token_id: int, pad_token_id: int, max_length: int = None
):
"""Build a delayed pattern mask to the input_ids. Each codebook is offset by the previous codebook by
one, giving a delayed pattern mask at the start of sequence a... | Build a delayed pattern mask to the input_ids. Each codebook is offset by the previous codebook by
one, giving a delayed pattern mask at the start of sequence and end of sequence. Take the example where there
are 4 codebooks and a max sequence length of 8, we have the delayed pattern mask of shape `(cod... | build_delay_pattern_mask | python | huggingface/parler-tts | parler_tts/modeling_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/modeling_parler_tts.py | Apache-2.0 |
def generate(
self,
inputs: Optional[torch.Tensor] = None,
generation_config: Optional[GenerationConfig] = None,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
synced_gpus: Optional[bool] = None,
s... |
Generates sequences of token ids for models with a language modeling head.
<Tip warning={true}>
Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
model's default generation configuration. You can override any `generation_con... | generate | python | huggingface/parler-tts | parler_tts/modeling_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/modeling_parler_tts.py | Apache-2.0 |
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
r"""
Example:
```python
>>> from parler_tts import ParlerTTSForConditionalGeneration
>>> model = ParlerTTSForConditionalGeneration.from_pretrained("parler-tts/parler-tts-mini-v1")
```"""
... |
Example:
```python
>>> from parler_tts import ParlerTTSForConditionalGeneration
>>> model = ParlerTTSForConditionalGeneration.from_pretrained("parler-tts/parler-tts-mini-v1")
``` | from_pretrained | python | huggingface/parler-tts | parler_tts/modeling_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/modeling_parler_tts.py | Apache-2.0 |
def from_sub_models_pretrained(
cls,
text_encoder_pretrained_model_name_or_path: str = None,
audio_encoder_pretrained_model_name_or_path: str = None,
decoder_pretrained_model_name_or_path: str = None,
*model_args,
**kwargs,
) -> PreTrainedModel:
r"""
I... |
Instantiate a text encoder, an audio encoder, and a Parler-TTS decoder from one, two or three base classes of the
library from pretrained model checkpoints.
The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
the model, you n... | from_sub_models_pretrained | python | huggingface/parler-tts | parler_tts/modeling_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/modeling_parler_tts.py | Apache-2.0 |
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.BoolTensor] = None,
input_values: Optional[torch.FloatTensor] = None,
padding_mask: Optional[torch.BoolTensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
... |
Returns:
Examples:
```python
>>> from transformers import AutoProcessor, ParlerTTSForConditionalGeneration
>>> import torch
>>> processor = AutoProcessor.from_pretrained("parler-tts/parler-tts-mini-v1")
>>> model = ParlerTTSForConditionalGeneration.from_pretrai... | forward | python | huggingface/parler-tts | parler_tts/modeling_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/modeling_parler_tts.py | Apache-2.0 |
def generate(
self,
inputs: Optional[torch.Tensor] = None,
generation_config: Optional[GenerationConfig] = None,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
synced_gpus: Optional[bool] = None,
s... |
Generates sequences of token ids for models with a language modeling head.
<Tip warning={true}>
Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
model's default generation configuration. You can override any `generation_co... | generate | python | huggingface/parler-tts | parler_tts/modeling_parler_tts.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/modeling_parler_tts.py | Apache-2.0 |
def encode(
self, input_values, padding_mask=None, bandwidth=None, return_dict=None, n_quantizers=None, sample_rate=None
):
"""
Encodes the input audio waveform into discrete codes.
Args:
input_values (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`):
... |
Encodes the input audio waveform into discrete codes.
Args:
input_values (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`):
Float values of the input audio waveform.
padding_mask (`torch.Tensor` of shape `(batch_size, channels, sequence_length)... | encode | python | huggingface/parler-tts | parler_tts/dac_wrapper/modeling_dac.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/dac_wrapper/modeling_dac.py | Apache-2.0 |
def decode(
self,
audio_codes,
audio_scales,
padding_mask=None,
return_dict=None,
):
"""
Decodes the given frames into an output audio waveform.
Note that the output might be a bit bigger than the input. In that case, any extra steps at the end can be... |
Decodes the given frames into an output audio waveform.
Note that the output might be a bit bigger than the input. In that case, any extra steps at the end can be
trimmed.
Args:
audio_codes (`torch.FloatTensor` of shape `(batch_size, nb_chunks, chunk_length)`, *optional*)... | decode | python | huggingface/parler-tts | parler_tts/dac_wrapper/modeling_dac.py | https://github.com/huggingface/parler-tts/blob/master/parler_tts/dac_wrapper/modeling_dac.py | Apache-2.0 |
def load_all_codec_checkpoints(output_dir=None) -> List[str]:
"""Helper function to load and concat all checkpoints."""
checkpoints_sorted = sorted_codec_checkpoints(output_dir=output_dir)
datasets = [load_from_disk(checkpoint) for checkpoint in checkpoints_sorted]
datasets = concatenate_datasets(datase... | Helper function to load and concat all checkpoints. | load_all_codec_checkpoints | python | huggingface/parler-tts | training/utils.py | https://github.com/huggingface/parler-tts/blob/master/training/utils.py | Apache-2.0 |
def setup_module():
"""
Setup steps for tests in this module
"""
assert root.joinpath("setup.sh").exists(), "setup.sh not found"
if root.joinpath(".env").exists():
shutil.move(str(root.joinpath(".env")), str(root.joinpath(".env.bak"))) |
Setup steps for tests in this module
| setup_module | python | fauxpilot/fauxpilot | tests/python_backend/test_setup.py | https://github.com/fauxpilot/fauxpilot/blob/master/tests/python_backend/test_setup.py | MIT |
def teardown_module():
"""
Teardown steps for tests in this module
"""
if root.joinpath(".env.bak").exists():
shutil.move(str(root.joinpath(".env.bak")), str(root.joinpath(".env")))
try:
if test_models_dir:
shutil.rmtree(test_models_dir)
except Exception as exc:
... |
Teardown steps for tests in this module
| teardown_module | python | fauxpilot/fauxpilot | tests/python_backend/test_setup.py | https://github.com/fauxpilot/fauxpilot/blob/master/tests/python_backend/test_setup.py | MIT |
def enter_input(proc: pexpect.spawn, expect: str, input_s: str, timeout: int = 5) -> str:
"""
Helper function to enter input for a given prompt. Returns consumed output.
"""
try:
proc.expect(expect, timeout=timeout)
except pexpect.exceptions.TIMEOUT as exc:
raise AssertionError(
... |
Helper function to enter input for a given prompt. Returns consumed output.
| enter_input | python | fauxpilot/fauxpilot | tests/python_backend/test_setup.py | https://github.com/fauxpilot/fauxpilot/blob/master/tests/python_backend/test_setup.py | MIT |
def run_common_setup_steps(n_gpus: int = 0) -> pexpect.spawn:
"""
Helper function to run common setup steps.
"""
proc = pexpect.pty_spawn.spawn(
"./setup.sh 2>&1", encoding="utf-8", cwd=str(root),
)
proc.ignorecase = True
enter_input(proc, r".*Enter number of GPUs[^:]+: ?", str(n_gp... |
Helper function to run common setup steps.
| run_common_setup_steps | python | fauxpilot/fauxpilot | tests/python_backend/test_setup.py | https://github.com/fauxpilot/fauxpilot/blob/master/tests/python_backend/test_setup.py | MIT |
def run_inference(
prompt: str, model: str = "py-model", port: int = 5000, return_all: bool = False,
**kwargs
) -> Union[str, Dict]:
"""
Invokes the copilot proxy with the given prompt and returns the completion
"""
endpoint = f"http://localhost:{port}/v1/engines/codegen/completions"
data = ... |
Invokes the copilot proxy with the given prompt and returns the completion
| run_inference | python | fauxpilot/fauxpilot | tests/python_backend/test_setup.py | https://github.com/fauxpilot/fauxpilot/blob/master/tests/python_backend/test_setup.py | MIT |
def test_python_backend(n_gpus: int):
"""
Step 1: run $root/setup.sh while passing appropriate options via stdin
Step 2: run docker-compose up with test.env sourced
Step 3: call :5000 with appropriate request
"""
proc = run_common_setup_steps(n_gpus)
choices = enter_input(proc, r".*Choose y... |
Step 1: run $root/setup.sh while passing appropriate options via stdin
Step 2: run docker-compose up with test.env sourced
Step 3: call :5000 with appropriate request
| test_python_backend | python | fauxpilot/fauxpilot | tests/python_backend/test_setup.py | https://github.com/fauxpilot/fauxpilot/blob/master/tests/python_backend/test_setup.py | MIT |
def main():
"""Main function to handle user input and start advertising."""
show_menu()
selected_option = int(input("Enter the option number you want: "))
interval = int(input("Enter the advertising interval (e.g., 200): "))
loop_interval = int(input("Enter the loop interval to reset the BLE adapter... | Main function to handle user input and start advertising. | main | python | ECTO-1A/AppleJuice | Pico_Pi_W_MicroPython/Cli_Version/main.py | https://github.com/ECTO-1A/AppleJuice/blob/master/Pico_Pi_W_MicroPython/Cli_Version/main.py | Apache-2.0 |
def convert_date(date):
"""
transform a date string to datetime.date object.
:param day, string, e.g. 2016-01-01, 20160101 or 2016/01/01
:return: object of datetime.date(such as 2016-01-01) or None
"""
if isinstance(date, datetime.date):
return date
elif isinstance(date, str):
... |
transform a date string to datetime.date object.
:param day, string, e.g. 2016-01-01, 20160101 or 2016/01/01
:return: object of datetime.date(such as 2016-01-01) or None
| convert_date | python | waditu/tushare | tushare/futures/domestic_cons.py | https://github.com/waditu/tushare/blob/master/tushare/futures/domestic_cons.py | BSD-3-Clause |
def merge_pages(self, replacements):
"""
Duplicate template page. Creates a copy of the template for each item
in the list, does a merge, and separates the them by page breaks.
"""
for part in self.parts.values():
root = part.getroot()
tag = root.tag
... |
Duplicate template page. Creates a copy of the template for each item
in the list, does a merge, and separates the them by page breaks.
| merge_pages | python | waditu/tushare | tushare/util/mailmerge.py | https://github.com/waditu/tushare/blob/master/tushare/util/mailmerge.py | BSD-3-Clause |
def with_default_config(
cls,
memory: DiskMemory,
execution_env: DiskExecutionEnv,
ai: AI = None,
code_gen_fn: CodeGenType = gen_code,
improve_fn: ImproveType = improve_fn,
process_code_fn: CodeProcessor = execute_entrypoint,
preprompts_holder: PrepromptsH... |
Creates a new instance of CliAgent with default configurations for memory, execution environment,
AI, and other functional parameters.
Parameters
----------
memory : DiskMemory
An instance of DiskMemory for storing and retrieving information.
execution_env :... | with_default_config | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/cli_agent.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/cli_agent.py | MIT |
def init(self, prompt: Prompt) -> FilesDict:
"""
Generates a new piece of code using the AI and step bundle based on the provided prompt.
Parameters
----------
prompt : str
A string prompt that guides the code generation process.
Returns
-------
... |
Generates a new piece of code using the AI and step bundle based on the provided prompt.
Parameters
----------
prompt : str
A string prompt that guides the code generation process.
Returns
-------
FilesDict
An instance of the `FilesDict`... | init | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/cli_agent.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/cli_agent.py | MIT |
def improve(
self,
files_dict: FilesDict,
prompt: Prompt,
execution_command: Optional[str] = None,
diff_timeout=3,
) -> FilesDict:
"""
Improves an existing piece of code using the AI and step bundle based on the provided prompt.
Parameters
---... |
Improves an existing piece of code using the AI and step bundle based on the provided prompt.
Parameters
----------
files_dict : FilesDict
An instance of `FilesDict` containing the code to be improved.
prompt : str
A string prompt that guides the code im... | improve | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/cli_agent.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/cli_agent.py | MIT |
def send_learning(learning: Learning):
"""
Send the learning data to RudderStack for analysis.
Parameters
----------
learning : Learning
An instance of the Learning class containing the data to be sent.
Notes
-----
This function is only called if consent is given to share data.... |
Send the learning data to RudderStack for analysis.
Parameters
----------
learning : Learning
An instance of the Learning class containing the data to be sent.
Notes
-----
This function is only called if consent is given to share data.
Data is not shared to a third party. It i... | send_learning | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/collect.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/collect.py | MIT |
def collect_learnings(
prompt: Prompt,
model: str,
temperature: float,
config: any,
memory: DiskMemory,
review: Review,
):
"""
Collect the learning data and send it to RudderStack for analysis.
Parameters
----------
prompt : str
The initial prompt or question that wa... |
Collect the learning data and send it to RudderStack for analysis.
Parameters
----------
prompt : str
The initial prompt or question that was provided to the model.
model : str
The name of the model used for generating the response.
temperature : float
The temperature s... | collect_learnings | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/collect.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/collect.py | MIT |
def collect_and_send_human_review(
prompt: Prompt,
model: str,
temperature: float,
config: Tuple[str, ...],
memory: DiskMemory,
):
"""
Collects human feedback on the code and sends it for analysis.
Parameters
----------
prompt : str
The initial prompt or question that wa... |
Collects human feedback on the code and sends it for analysis.
Parameters
----------
prompt : str
The initial prompt or question that was provided to the model.
model : str
The name of the model used for generating the response.
temperature : float
The temperature setti... | collect_and_send_human_review | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/collect.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/collect.py | MIT |
def __init__(self, project_path: Union[str, Path]):
"""
Initializes the FileSelector with a given project path.
Parameters
----------
project_path : Union[str, Path]
The path to the project directory where file selection is to be performed.
"""
self.p... |
Initializes the FileSelector with a given project path.
Parameters
----------
project_path : Union[str, Path]
The path to the project directory where file selection is to be performed.
| __init__ | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def ask_for_files(self, skip_file_selection=False) -> tuple[FilesDict, bool]:
"""
Prompts the user to select files for context improvement.
This method supports selection from the terminal or using a previously saved list.
In test mode, it retrieves files from a predefined TOML configur... |
Prompts the user to select files for context improvement.
This method supports selection from the terminal or using a previously saved list.
In test mode, it retrieves files from a predefined TOML configuration.
Returns
-------
FilesDict
A dictionary with f... | ask_for_files | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def editor_file_selector(
self, input_path: Union[str, Path], init: bool = True
) -> List[str]:
"""
Provides an interactive file selection interface using a .toml file.
Parameters
----------
input_path : Union[str, Path]
The path where file selection is t... |
Provides an interactive file selection interface using a .toml file.
Parameters
----------
input_path : Union[str, Path]
The path where file selection is to be performed.
init : bool, optional
Indicates whether to initialize the .toml file with the file ... | editor_file_selector | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def open_with_default_editor(self, file_path: Union[str, Path]):
"""
Opens a file with the system's default text editor.
Parameters
----------
file_path : Union[str, Path]
The path to the file to be opened in the text editor.
"""
editors = [
... |
Opens a file with the system's default text editor.
Parameters
----------
file_path : Union[str, Path]
The path to the file to be opened in the text editor.
| open_with_default_editor | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def is_utf8(self, file_path: Union[str, Path]) -> bool:
"""
Checks if the file at the given path is UTF-8 encoded.
Parameters
----------
file_path : Union[str, Path]
The path to the file to be checked.
Returns
-------
bool
True if... |
Checks if the file at the given path is UTF-8 encoded.
Parameters
----------
file_path : Union[str, Path]
The path to the file to be checked.
Returns
-------
bool
True if the file is UTF-8 encoded, False otherwise.
| is_utf8 | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def get_files_from_toml(
self, input_path: Union[str, Path], toml_file: Union[str, Path]
) -> List[str]:
"""
Retrieves a list of selected files from a .toml configuration file.
Parameters
----------
input_path : Union[str, Path]
The path where file select... |
Retrieves a list of selected files from a .toml configuration file.
Parameters
----------
input_path : Union[str, Path]
The path where file selection was performed.
toml_file : Union[str, Path]
The path to the .toml file containing the file selection.
... | get_files_from_toml | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def merge_file_lists(
self, existing_files: Dict[str, Any], new_files: Dict[str, Any]
) -> Dict[str, Any]:
"""
Merges two lists of files, preserving the selection status.
Parameters
----------
existing_files : Dict[str, Any]
The dictionary of existing fil... |
Merges two lists of files, preserving the selection status.
Parameters
----------
existing_files : Dict[str, Any]
The dictionary of existing files with their properties.
new_files : Dict[str, Any]
The dictionary of new files with their properties.
... | merge_file_lists | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def should_filter_file(self, file_path: Path, filters: List[str]) -> bool:
"""
Determines if a file should be ignored based on .gitignore rules.
"""
for f in filters:
if fnmatch.fnmatchcase(str(file_path), f):
return True
return False |
Determines if a file should be ignored based on .gitignore rules.
| should_filter_file | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def get_current_files(self, project_path: Union[str, Path]) -> List[str]:
"""
Generates a list of all files in the project directory. Will use .gitignore files if project_path is a git repository.
Parameters
----------
project_path : Union[str, Path]
The path to the ... |
Generates a list of all files in the project directory. Will use .gitignore files if project_path is a git repository.
Parameters
----------
project_path : Union[str, Path]
The path to the project directory.
Returns
-------
List[str]
A l... | get_current_files | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def __init__(
self, path: Union[str, Path], parent_path: "DisplayablePath", is_last: bool
):
"""
Initializes a DisplayablePath object with a given path and parent.
Parameters
----------
path : Union[str, Path]
The file system path to be displayed.
... |
Initializes a DisplayablePath object with a given path and parent.
Parameters
----------
path : Union[str, Path]
The file system path to be displayed.
parent_path : DisplayablePath
The parent path in the tree structure.
is_last : bool
... | __init__ | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def display_name(self) -> str:
"""
Get the display name of the file or directory.
"""
if self.path.is_dir():
return self.path.name + "/"
return self.path.name |
Get the display name of the file or directory.
| display_name | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def make_tree(
cls, root: Union[str, Path], parent=None, is_last=False, criteria=None
) -> Generator["DisplayablePath", None, None]:
"""
Creates a tree of DisplayablePath objects from a root directory.
Parameters
----------
root : Union[str, Path]
The roo... |
Creates a tree of DisplayablePath objects from a root directory.
Parameters
----------
root : Union[str, Path]
The root directory from which to start creating the tree.
parent : DisplayablePath, optional
The parent path in the tree structure.
is_... | make_tree | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def displayable(self) -> str:
"""
Returns a string representation of the path for display in a tree-like structure.
Returns
-------
str
The displayable string representation of the file or directory.
"""
if self.parent is None:
return self... |
Returns a string representation of the path for display in a tree-like structure.
Returns
-------
str
The displayable string representation of the file or directory.
| displayable | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/file_selector.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/file_selector.py | MIT |
def human_review_input() -> Optional[Review]:
"""
Interactively prompts the user to review the generated code and returns their feedback encapsulated in a Review object.
This function will first check if the user has given consent to collect their feedback. If consent is given, it will ask the user a serie... |
Interactively prompts the user to review the generated code and returns their feedback encapsulated in a Review object.
This function will first check if the user has given consent to collect their feedback. If consent is given, it will ask the user a series of questions about the generated code's performance... | human_review_input | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/learning.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/learning.py | MIT |
def check_collection_consent() -> bool:
"""
Checks if the user has previously given consent to store their data for feedback collection.
This function looks for a file that stores the user's consent status. If the file exists and contains 'true', consent is assumed. If the file does not exist or does not c... |
Checks if the user has previously given consent to store their data for feedback collection.
This function looks for a file that stores the user's consent status. If the file exists and contains 'true', consent is assumed. If the file does not exist or does not contain 'true', the function will prompt the use... | check_collection_consent | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/learning.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/learning.py | MIT |
def extract_learning(
prompt: Prompt,
model: str,
temperature: float,
config: Tuple[str, ...],
memory: DiskMemory,
review: Review,
) -> Learning:
"""
Constructs a Learning object containing the session's metadata and user feedback.
Parameters
----------
prompt : str
... |
Constructs a Learning object containing the session's metadata and user feedback.
Parameters
----------
prompt : str
The initial prompt provided to the GPT Engineer.
model : str
The name of the model used during the session.
temperature : float
The temperature setting u... | extract_learning | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/learning.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/learning.py | MIT |
def get_session() -> str:
"""
Retrieves or generates a unique identifier for the current user session.
This function attempts to read a unique user ID from a temporary file. If the file does not exist, it generates a new random ID, writes it to the file, and returns it. This ID is used to uniquely identify... |
Retrieves or generates a unique identifier for the current user session.
This function attempts to read a unique user ID from a temporary file. If the file does not exist, it generates a new random ID, writes it to the file, and returns it. This ID is used to uniquely identify the user's session.
Returns... | get_session | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/learning.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/learning.py | MIT |
def load_env_if_needed():
"""
Load environment variables if the OPENAI_API_KEY is not already set.
This function checks if the OPENAI_API_KEY environment variable is set,
and if not, it attempts to load it from a .env file in the current working
directory. It then sets the openai.api_key for use in... |
Load environment variables if the OPENAI_API_KEY is not already set.
This function checks if the OPENAI_API_KEY environment variable is set,
and if not, it attempts to load it from a .env file in the current working
directory. It then sets the openai.api_key for use in the application.
| load_env_if_needed | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/main.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/main.py | MIT |
def load_prompt(
input_repo: DiskMemory,
improve_mode: bool,
prompt_file: str,
image_directory: str,
entrypoint_prompt_file: str = "",
) -> Prompt:
"""
Load or request a prompt from the user based on the mode.
Parameters
----------
input_repo : DiskMemory
The disk memory... |
Load or request a prompt from the user based on the mode.
Parameters
----------
input_repo : DiskMemory
The disk memory object where prompts and other data are stored.
improve_mode : bool
Flag indicating whether the application is in improve mode.
Returns
-------
str
... | load_prompt | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/main.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/main.py | MIT |
def get_preprompts_path(use_custom_preprompts: bool, input_path: Path) -> Path:
"""
Get the path to the preprompts, using custom ones if specified.
Parameters
----------
use_custom_preprompts : bool
Flag indicating whether to use custom preprompts.
input_path : Path
The path to ... |
Get the path to the preprompts, using custom ones if specified.
Parameters
----------
use_custom_preprompts : bool
Flag indicating whether to use custom preprompts.
input_path : Path
The path to the project directory.
Returns
-------
Path
The path to the direct... | get_preprompts_path | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/main.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/main.py | MIT |
def main(
project_path: str = typer.Argument(".", help="path"),
model: str = typer.Option(
os.environ.get("MODEL_NAME", "gpt-4o"), "--model", "-m", help="model id string"
),
temperature: float = typer.Option(
0.1,
"--temperature",
"-t",
help="Controls randomness: ... |
The main entry point for the CLI tool that generates or improves a project.
This function sets up the CLI tool, loads environment variables, initializes
the AI, and processes the user's request to generate or improve a project
based on the provided arguments.
Parameters
----------
project... | main | python | AntonOsika/gpt-engineer | gpt_engineer/applications/cli/main.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/applications/cli/main.py | MIT |
def run(
agent: BaseAgent,
benchmark: Benchmark,
verbose=False,
) -> List[TaskResult]:
"""
Runs the benchmark tasks using the provided agent and returns a list of TaskResult objects.
Parameters
----------
agent : BaseAgent
The agent to use for running the benchmark tasks.
be... |
Runs the benchmark tasks using the provided agent and returns a list of TaskResult objects.
Parameters
----------
agent : BaseAgent
The agent to use for running the benchmark tasks.
benchmark : Benchmark
The benchmark containing the tasks to run.
verbose : bool, default=False
... | run | python | AntonOsika/gpt-engineer | gpt_engineer/benchmark/run.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/benchmark/run.py | MIT |
def get_agent(path):
"""
Dynamically imports and returns the default configuration agent from the given path.
Parameters
----------
path : str
The file path to the module containing the default configuration agent.
Returns
-------
BaseAgent
An instance of the imported d... |
Dynamically imports and returns the default configuration agent from the given path.
Parameters
----------
path : str
The file path to the module containing the default configuration agent.
Returns
-------
BaseAgent
An instance of the imported default configuration agent.
... | get_agent | python | AntonOsika/gpt-engineer | gpt_engineer/benchmark/__main__.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/benchmark/__main__.py | MIT |
def main(
path_to_agent: Annotated[
str,
typer.Argument(
help="python file that contains a function called 'default_config_agent'"
),
],
bench_config: Annotated[
str, typer.Argument(help="optional task name in benchmark")
] = os.path.join(os.path.dirname(__fil... |
The main function that runs the specified benchmarks with the given agent and outputs the results to the console.
Parameters
----------
path_to_agent : str
The file path to the Python module that contains a function called 'default_config_agent'.
bench_config : str, default=default_bench_c... | main | python | AntonOsika/gpt-engineer | gpt_engineer/benchmark/__main__.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/benchmark/__main__.py | MIT |
def get_benchmark(name: str, config: BenchConfig) -> Benchmark:
"""
Retrieves a Benchmark object by name. Raises ValueError if the benchmark is unknown.
Parameters
----------
name : str
The name of the benchmark to retrieve.
config : BenchConfig
Configuration object for the benc... |
Retrieves a Benchmark object by name. Raises ValueError if the benchmark is unknown.
Parameters
----------
name : str
The name of the benchmark to retrieve.
config : BenchConfig
Configuration object for the benchmarks.
Returns
-------
Benchmark
The Benchmark ob... | get_benchmark | python | AntonOsika/gpt-engineer | gpt_engineer/benchmark/benchmarks/load.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/benchmark/benchmarks/load.py | MIT |
def load_apps(config: AppsConfig) -> Benchmark:
"""
Loads the APPS benchmark, which consists of a series coding problems.
Returns
-------
Benchmark
A Benchmark object containing a list of Task objects for the APPS evaluation.
"""
dataset = _get_dataset()
tasks = []
problems ... |
Loads the APPS benchmark, which consists of a series coding problems.
Returns
-------
Benchmark
A Benchmark object containing a list of Task objects for the APPS evaluation.
| load_apps | python | AntonOsika/gpt-engineer | gpt_engineer/benchmark/benchmarks/apps/load.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/benchmark/benchmarks/apps/load.py | MIT |
def load_gptme(config: GptmeConfig) -> Benchmark:
"""
Loads the GPT-Me benchmark, which consists of a series of tasks for evaluation.
Returns
-------
Benchmark
A Benchmark object containing a list of Task objects for the GPT-Me evaluation.
"""
return Benchmark(
name="gptme",... |
Loads the GPT-Me benchmark, which consists of a series of tasks for evaluation.
Returns
-------
Benchmark
A Benchmark object containing a list of Task objects for the GPT-Me evaluation.
| load_gptme | python | AntonOsika/gpt-engineer | gpt_engineer/benchmark/benchmarks/gptme/load.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/benchmark/benchmarks/gptme/load.py | MIT |
def load_mbpp(config: MbppConfig) -> Benchmark:
"""
Loads the MBPP benchmark, which consists of a series coding problems.
Returns
-------
Benchmark
A Benchmark object containing a list of Task objects for the MBPP evaluation.
"""
dataset = _get_dataset()
tasks = []
problems ... |
Loads the MBPP benchmark, which consists of a series coding problems.
Returns
-------
Benchmark
A Benchmark object containing a list of Task objects for the MBPP evaluation.
| load_mbpp | python | AntonOsika/gpt-engineer | gpt_engineer/benchmark/benchmarks/mbpp/load.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/benchmark/benchmarks/mbpp/load.py | MIT |
def __init__(
self,
model_name="gpt-4-turbo",
temperature=0.1,
azure_endpoint=None,
streaming=True,
vision=False,
):
"""
Initialize the AI class.
Parameters
----------
model_name : str, optional
The name of the mode... |
Initialize the AI class.
Parameters
----------
model_name : str, optional
The name of the model to use, by default "gpt-4".
temperature : float, optional
The temperature to use for the model, by default 0.1.
| __init__ | python | AntonOsika/gpt-engineer | gpt_engineer/core/ai.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/ai.py | MIT |
def start(self, system: str, user: Any, *, step_name: str) -> List[Message]:
"""
Start the conversation with a system message and a user message.
Parameters
----------
system : str
The content of the system message.
user : str
The content of the u... |
Start the conversation with a system message and a user message.
Parameters
----------
system : str
The content of the system message.
user : str
The content of the user message.
step_name : str
The name of the step.
Returns
... | start | python | AntonOsika/gpt-engineer | gpt_engineer/core/ai.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/ai.py | MIT |
def _extract_content(self, content):
"""
Extracts text content from a message, supporting both string and list types.
Parameters
----------
content : Union[str, List[dict]]
The content of a message, which could be a string or a list.
Returns
-------
... |
Extracts text content from a message, supporting both string and list types.
Parameters
----------
content : Union[str, List[dict]]
The content of a message, which could be a string or a list.
Returns
-------
str
The extracted text content... | _extract_content | python | AntonOsika/gpt-engineer | gpt_engineer/core/ai.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/ai.py | MIT |
def _collapse_text_messages(self, messages: List[Message]):
"""
Combine consecutive messages of the same type into a single message, where if the message content
is a list type, the first text element's content is taken. This method keeps `combined_content` as a string.
This method iter... |
Combine consecutive messages of the same type into a single message, where if the message content
is a list type, the first text element's content is taken. This method keeps `combined_content` as a string.
This method iterates through the list of messages, combining consecutive messages of th... | _collapse_text_messages | python | AntonOsika/gpt-engineer | gpt_engineer/core/ai.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/ai.py | MIT |
def next(
self,
messages: List[Message],
prompt: Optional[str] = None,
*,
step_name: str,
) -> List[Message]:
"""
Advances the conversation by sending message history
to LLM and updating with the response.
Parameters
----------
... |
Advances the conversation by sending message history
to LLM and updating with the response.
Parameters
----------
messages : List[Message]
The list of messages in the conversation.
prompt : Optional[str], optional
The prompt to use, by default No... | next | python | AntonOsika/gpt-engineer | gpt_engineer/core/ai.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/ai.py | MIT |
def deserialize_messages(jsondictstr: str) -> List[Message]:
"""
Deserialize a JSON string to a list of messages.
Parameters
----------
jsondictstr : str
The JSON string to deserialize.
Returns
-------
List[Message]
The deserializ... |
Deserialize a JSON string to a list of messages.
Parameters
----------
jsondictstr : str
The JSON string to deserialize.
Returns
-------
List[Message]
The deserialized list of messages.
| deserialize_messages | python | AntonOsika/gpt-engineer | gpt_engineer/core/ai.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/ai.py | MIT |
def _create_chat_model(self) -> BaseChatModel:
"""
Create a chat model with the specified model name and temperature.
Parameters
----------
model : str
The name of the model to create.
temperature : float
The temperature to use for the model.
... |
Create a chat model with the specified model name and temperature.
Parameters
----------
model : str
The name of the model to create.
temperature : float
The temperature to use for the model.
Returns
-------
BaseChatModel
... | _create_chat_model | python | AntonOsika/gpt-engineer | gpt_engineer/core/ai.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/ai.py | MIT |
def chat_to_files_dict(chat: str) -> FilesDict:
"""
Converts a chat string containing file paths and code blocks into a FilesDict object.
Args:
- chat (str): The chat string containing file paths and code blocks.
Returns:
- FilesDict: A dictionary with file paths as keys and code blocks as val... |
Converts a chat string containing file paths and code blocks into a FilesDict object.
Args:
- chat (str): The chat string containing file paths and code blocks.
Returns:
- FilesDict: A dictionary with file paths as keys and code blocks as values.
| chat_to_files_dict | python | AntonOsika/gpt-engineer | gpt_engineer/core/chat_to_files.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/chat_to_files.py | MIT |
def apply_diffs(diffs: Dict[str, Diff], files: FilesDict) -> FilesDict:
"""
Applies diffs to the provided files.
Args:
- diffs (Dict[str, Diff]): A dictionary of diffs to apply, keyed by filename.
- files (FilesDict): The original files to which diffs will be applied.
Returns:
- FilesDict:... |
Applies diffs to the provided files.
Args:
- diffs (Dict[str, Diff]): A dictionary of diffs to apply, keyed by filename.
- files (FilesDict): The original files to which diffs will be applied.
Returns:
- FilesDict: The updated files after applying diffs.
| apply_diffs | python | AntonOsika/gpt-engineer | gpt_engineer/core/chat_to_files.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/chat_to_files.py | MIT |
def parse_diffs(diff_string: str, diff_timeout=3) -> dict:
"""
Parses a diff string in the unified git diff format.
Args:
- diff_string (str): The diff string to parse.
Returns:
- dict: A dictionary of Diff objects keyed by filename.
"""
# Regex to match individual diff blocks
diff... |
Parses a diff string in the unified git diff format.
Args:
- diff_string (str): The diff string to parse.
Returns:
- dict: A dictionary of Diff objects keyed by filename.
| parse_diffs | python | AntonOsika/gpt-engineer | gpt_engineer/core/chat_to_files.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/chat_to_files.py | MIT |
def parse_diff_block(diff_block: str) -> dict:
"""
Parses a block of diff text into a Diff object.
Args:
- diff_block (str): A single block of diff text.
Returns:
- dict: A dictionary containing a single Diff object keyed by the post-edit filename.
"""
lines = diff_block.strip().split(... |
Parses a block of diff text into a Diff object.
Args:
- diff_block (str): A single block of diff text.
Returns:
- dict: A dictionary containing a single Diff object keyed by the post-edit filename.
| parse_diff_block | python | AntonOsika/gpt-engineer | gpt_engineer/core/chat_to_files.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/chat_to_files.py | MIT |
def parse_hunk_header(header_line) -> Tuple[int, int, int, int]:
"""
Parses the header of a hunk from a diff.
Args:
- header_line (str): The header line of a hunk.
Returns:
- tuple: A tuple containing start and length information for pre- and post-edit.
"""
pattern = re.compile(r"^@@ -... |
Parses the header of a hunk from a diff.
Args:
- header_line (str): The header line of a hunk.
Returns:
- tuple: A tuple containing start and length information for pre- and post-edit.
| parse_hunk_header | python | AntonOsika/gpt-engineer | gpt_engineer/core/chat_to_files.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/chat_to_files.py | MIT |
def add_retained_line(self, line, index) -> None:
"""Adds a retained line to the hunk at the specified index."""
self.lines.insert(index, (RETAIN, line))
self.category_counts[RETAIN] += 1 | Adds a retained line to the hunk at the specified index. | add_retained_line | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def relabel_line(self, index, new_label) -> None:
"""Changes the label of a line at the specified index."""
old_label = self.lines[index][0]
self.lines[index] = (new_label, self.lines[index][1])
self.category_counts[old_label] -= 1
self.category_counts[new_label] += 1 | Changes the label of a line at the specified index. | relabel_line | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def pop_line(self, line, index) -> None:
"""Removes a line from the hunk at the specified index."""
self.lines.pop(index)
assert self.category_counts[line[0]] > 0
self.category_counts[line[0]] -= 1 | Removes a line from the hunk at the specified index. | pop_line | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def add_lines(self, new_lines) -> None:
"""Adds multiple lines to the hunk."""
for line in new_lines:
self.lines.append(line)
self.category_counts[line[0]] += 1 | Adds multiple lines to the hunk. | add_lines | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def hunk_to_string(self) -> str:
"""Converts the hunk to a string representation."""
string = f"@@ -{self.start_line_pre_edit},{self.hunk_len_pre_edit} +{self.start_line_post_edit},{self.hunk_len_post_edit} @@\n"
for line_type, line_content in self.lines:
line_prefix = (
... | Converts the hunk to a string representation. | hunk_to_string | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def make_forward_block(self, hunk_ind: int, forward_block_len) -> str:
"""Creates a block of lines for forward comparison."""
forward_lines = [
line[1] for line in self.lines[hunk_ind:] if not line[0] == ADD
]
forward_block = "\n".join(forward_lines[0:forward_block_len])
... | Creates a block of lines for forward comparison. | make_forward_block | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def check_start_line(self, lines_dict: dict) -> bool:
"""Check if the starting line of a hunk is present in the original code and returns a boolean value accordingly."""
if self.is_new_file:
# this hunk cannot be falsified and is by definition true
return True
if self.sta... | Check if the starting line of a hunk is present in the original code and returns a boolean value accordingly. | check_start_line | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def find_start_line(self, lines_dict: dict, problems: list) -> bool:
"""Finds the starting line of the hunk in the original code and returns a boolean value accordingly. If the starting line is not found, it appends a problem message to the problems list."""
# ToDo handle the case where the start line ... | Finds the starting line of the hunk in the original code and returns a boolean value accordingly. If the starting line is not found, it appends a problem message to the problems list. | find_start_line | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def validate_lines(self, lines_dict: dict, problems: list) -> bool:
"""Validates the lines of the hunk against the original file and returns a boolean value accordingly. If the lines do not match, it appends a problem message to the problems list."""
hunk_ind = 0
file_ind = self.start_line_pre_e... | Validates the lines of the hunk against the original file and returns a boolean value accordingly. If the lines do not match, it appends a problem message to the problems list. | validate_lines | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def validate_and_correct(
self,
lines_dict: dict,
problems: list,
) -> bool:
"""
Validates and corrects the hunk based on the original lines.
This function attempts to validate the hunk by comparing its lines to the original file and making corrections
where ... |
Validates and corrects the hunk based on the original lines.
This function attempts to validate the hunk by comparing its lines to the original file and making corrections
where necessary. It also identifies problems such as non-matching lines or incorrect line types.
| validate_and_correct | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def is_new_file(self) -> bool:
"""Determines if the diff represents a new file."""
if self.filename_pre == "/dev/null":
return True
return any(hunk.is_new_file for hunk in self.hunks) | Determines if the diff represents a new file. | is_new_file | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def diff_to_string(self) -> str:
"""Converts the diff to a string representation."""
string = f"--- {self.filename_pre}\n+++ {self.filename_post}\n"
for hunk in self.hunks:
string += hunk.hunk_to_string()
return string.strip() | Converts the diff to a string representation. | diff_to_string | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def validate_and_correct(self, lines_dict: dict) -> List[str]:
"""Validates and corrects each hunk in the diff."""
problems = []
past_hunk = None
cut_lines_dict = lines_dict.copy()
for hunk in self.hunks:
if past_hunk is not None:
# make sure to not cu... | Validates and corrects each hunk in the diff. | validate_and_correct | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def count_ratio(str1, str2) -> float:
"""
Computes the ratio of common characters to the length of the longer string, ignoring spaces and case.
Parameters:
- str1, str2 (str): The strings to compare.
Returns:
- float: The ratio of common characters to the length of the longer string.
"""
... |
Computes the ratio of common characters to the length of the longer string, ignoring spaces and case.
Parameters:
- str1, str2 (str): The strings to compare.
Returns:
- float: The ratio of common characters to the length of the longer string.
| count_ratio | python | AntonOsika/gpt-engineer | gpt_engineer/core/diff.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/diff.py | MIT |
def __setitem__(self, key: Union[str, Path], value: str):
"""
Set the code content for the given filename, enforcing type checks on the key and value.
Overrides the dictionary's __setitem__ to enforce type checks on the key and value.
The key must be a string or a Path object, and the v... |
Set the code content for the given filename, enforcing type checks on the key and value.
Overrides the dictionary's __setitem__ to enforce type checks on the key and value.
The key must be a string or a Path object, and the value must be a string representing
the code content.
... | __setitem__ | python | AntonOsika/gpt-engineer | gpt_engineer/core/files_dict.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/files_dict.py | MIT |
def to_chat(self):
"""
Formats the items of the object (assuming file name and content pairs)
into a string suitable for chat display.
Returns
-------
str
A string representation of the files.
"""
chat_str = ""
for file_name, file_cont... |
Formats the items of the object (assuming file name and content pairs)
into a string suitable for chat display.
Returns
-------
str
A string representation of the files.
| to_chat | python | AntonOsika/gpt-engineer | gpt_engineer/core/files_dict.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/files_dict.py | MIT |
def to_log(self):
"""
Formats the items of the object (assuming file name and content pairs)
into a string suitable for log display.
Returns
-------
str
A string representation of the files.
"""
log_str = ""
for file_name, file_content... |
Formats the items of the object (assuming file name and content pairs)
into a string suitable for log display.
Returns
-------
str
A string representation of the files.
| to_log | python | AntonOsika/gpt-engineer | gpt_engineer/core/files_dict.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/files_dict.py | MIT |
def file_to_lines_dict(file_content: str) -> dict:
"""
Converts file content into a dictionary where each line number is a key
and the corresponding line content is the value.
Parameters
----------
file_name : str
The name of the file.
file_content : str
The content of the f... |
Converts file content into a dictionary where each line number is a key
and the corresponding line content is the value.
Parameters
----------
file_name : str
The name of the file.
file_content : str
The content of the file.
Returns
-------
dict
A dictionar... | file_to_lines_dict | python | AntonOsika/gpt-engineer | gpt_engineer/core/files_dict.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/files_dict.py | MIT |
def lint_python(self, content, config):
"""Lint Python files using the `black` library, handling all exceptions silently and logging them.
This function attempts to format the code and returns the formatted code if successful.
If any error occurs during formatting, it logs the error and returns ... | Lint Python files using the `black` library, handling all exceptions silently and logging them.
This function attempts to format the code and returns the formatted code if successful.
If any error occurs during formatting, it logs the error and returns the original content.
| lint_python | python | AntonOsika/gpt-engineer | gpt_engineer/core/linting.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/linting.py | MIT |
def lint_files(self, files_dict: FilesDict, config: dict = None) -> FilesDict:
"""
Lints files based on their extension using registered linting functions.
Parameters
----------
files_dict : FilesDict
The dictionary of file names to their respective source code conte... |
Lints files based on their extension using registered linting functions.
Parameters
----------
files_dict : FilesDict
The dictionary of file names to their respective source code content.
config : dict, optional
A dictionary of configuration options for ... | lint_files | python | AntonOsika/gpt-engineer | gpt_engineer/core/linting.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/linting.py | MIT |
def to_toml(self, config_file: Path | str, save=True) -> str:
"""Write the configuration to a TOML file."""
if isinstance(config_file, str):
config_file = Path(config_file)
# Load the TOMLDocument and overwrite it with the new values
config = read_config(config_file)
... | Write the configuration to a TOML file. | to_toml | python | AntonOsika/gpt-engineer | gpt_engineer/core/project_config.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/project_config.py | MIT |
def num_tokens_for_base64_image(
self, image_base64: str, detail: str = "high"
) -> int:
"""
Calculate the token size for a base64 encoded image based on OpenAI's token calculation rules.
Parameters:
- image_base64 (str): The base64 encoded string of the image.
- det... |
Calculate the token size for a base64 encoded image based on OpenAI's token calculation rules.
Parameters:
- image_base64 (str): The base64 encoded string of the image.
- detail (str): The detail level of the image, 'low' or 'high'.
Returns:
- int: The token size of th... | num_tokens_for_base64_image | python | AntonOsika/gpt-engineer | gpt_engineer/core/token_usage.py | https://github.com/AntonOsika/gpt-engineer/blob/master/gpt_engineer/core/token_usage.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.