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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25,236 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/dphubert/pruning_utils.py | 43,44 | 1,52 | prune_layer_norm | 45,52 | 44,52 | """Utility functions for pruning."""
from typing import Union
import torch
import torch.nn as nn
def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: str):
"Prune linear layer in place."
# NOTE: weight: (out_features, in_features), bias: (out_features,)
if dim == "input":
dim =... | """Utility functions for pruning."""
from typing import Union
import torch
import torch.nn as nn
def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: str):
"Prune linear layer in place."
# NOTE: weight: (out_features, in_features), bias: (out_features,)
if dim == "input":
dim =... | layernorm.weight = nn.Parameter(layernorm.weight.index_select(0, index).clone().detach())
layernorm.bias = nn.Parameter(layernorm.bias.index_select(0, index).clone().detach())
if isinstance(layernorm, nn.LayerNorm):
layernorm.normalized_shape = (len(index),)
elif isinstance(layernorm, nn.GroupNo... | """Prune layer norm or group norm in place."""
layernorm.weight = nn.Parameter(layernorm.weight.index_select(0, index).clone().detach())
layernorm.bias = nn.Parameter(layernorm.bias.index_select(0, index).clone().detach())
if isinstance(layernorm, nn.LayerNorm):
layernorm.normalized_shape = (len... | 23 | 502 | 151 | 653 | """Utility functions for pruning."""
from typing import Union
import torch
import torch.nn as nn
def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: str):
"Prune linear layer in place."
# NOTE: weight: (out_features, in_features), bias: (out_features,)
if dim == "input":
dim =... | """Utility functions for pruning."""
from typing import Union
import torch
import torch.nn as nn
def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: str):
"Prune linear layer in place."
# NOTE: weight: (out_features, in_features), bias: (out_features,)
if dim == "input":
dim =... | |
25,237 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/dphubert/utils/import_huggingface_wavlm.py | 66,67 | 1,130 | _build | 67,93 | 67,93 | """Import Hugging Face transformers's wav2vec2.0 pretrained weights to torchaudios's format.
Originally from:
https://github.com/pytorch/audio/blob/main/torchaudio/models/wav2vec2/utils/import_huggingface.py
"""
import logging
from typing import Any, Dict
from torch.nn import Module
from ..model import Wav2Vec2Mod... | """Import Hugging Face transformers's wav2vec2.0 pretrained weights to torchaudios's format.
Originally from:
https://github.com/pytorch/audio/blob/main/torchaudio/models/wav2vec2/utils/import_huggingface.py
"""
import logging
from typing import Any, Dict
from torch.nn import Module
from ..model import Wav2Vec2Mod... | is_for_ctc = original.__class__.__name__ in ["Wav2Vec2ForCTC", "WavLMForCTC"]
if is_for_ctc:
aux_num_out = original.config.vocab_size
wav2vec2 = original.wav2vec2
else:
_LG.warning(
"The model is not an instance of Wav2Vec2ForCTC or WavLMForCTC. " '"lm_head" module is not... | is_for_ctc = original.__class__.__name__ in ["Wav2Vec2ForCTC", "WavLMForCTC"]
if is_for_ctc:
aux_num_out = original.config.vocab_size
wav2vec2 = original.wav2vec2
else:
_LG.warning(
"The model is not an instance of Wav2Vec2ForCTC or WavLMForCTC. " '"lm_head" module is not... | 86 | 1,518 | 491 | 2,009 | """Import Hugging Face transformers's wav2vec2.0 pretrained weights to torchaudios's format.
Originally from:
https://github.com/pytorch/audio/blob/main/torchaudio/models/wav2vec2/utils/import_huggingface.py
"""
import logging
from typing import Any, Dict
from torch.nn import Module
from ..model import Wav2Vec2Mod... | """Import Hugging Face transformers's wav2vec2.0 pretrained weights to torchaudios's format.
Originally from:
https://github.com/pytorch/audio/blob/main/torchaudio/models/wav2vec2/utils/import_huggingface.py
"""
import logging
from typing import Any, Dict
from torch.nn import Module
from ..model import Wav2Vec2Mod... | |
25,239 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model.py | 87,88 | 75,98 | forward | FeatureExtractor | 88,98 | 88,98 | class FeatureExtractor(nn.Module):
def __init__(self):
super().__init__()
self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
self.norm0 = nn.GroupNorm(512, 512)
self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.c... | class FeatureExtractor(nn.Module):
def __init__(self):
super().__init__()
self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
self.norm0 = nn.GroupNorm(512, 512)
self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.c... | x = t_func.gelu(self.norm0(self.conv0(x)))
x = t_func.gelu(self.conv1(x))
x = t_func.gelu(self.conv2(x))
x = t_func.gelu(self.conv3(x))
x = t_func.gelu(self.conv4(x))
x = t_func.gelu(self.conv5(x))
x = t_func.gelu(self.conv6(x))
return x
| x = t_func.gelu(self.norm0(self.conv0(x)))
x = t_func.gelu(self.conv1(x))
x = t_func.gelu(self.conv2(x))
x = t_func.gelu(self.conv3(x))
x = t_func.gelu(self.conv4(x))
x = t_func.gelu(self.conv5(x))
x = t_func.gelu(self.conv6(x))
return x
| 23 | 319 | 154 | 473 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,240 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model.py | 105,106 | 98,112 | forward | FeatureProjection | 106,112 | 106,112 | class FeatureProjection(nn.Module):
def __init__(self):
super().__init__()
self.norm = nn.LayerNorm(512)
self.projection = nn.Linear(512, 768)
self.dropout = nn.Dropout(0.1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY | class FeatureProjection(nn.Module):
def __init__(self):
super().__init__()
self.norm = nn.LayerNorm(512)
self.projection = nn.Linear(512, 768)
self.dropout = nn.Dropout(0.1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY | x = self.norm(x)
x = self.projection(x)
x = self.dropout(x)
return x
| x = self.norm(x)
x = self.projection(x)
x = self.dropout(x)
return x
| 11 | 114 | 44 | 158 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,241 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model.py | 57,58 | 11,64 | forward | Hubert | 58,64 | 58,64 | class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super().__init__()
self._mask = mask
self.feature_extractor = FeatureExtractor()
self.feature_projection = FeatureProjection()
self.positional_embedding = PositionalConvEmbedding(... | class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super().__init__()
self._mask = mask
self.feature_extractor = FeatureExtractor()
self.feature_projection = FeatureProjection()
self.positional_embedding = PositionalConvEmbedding(... | x, mask = self.encode(x)
x = self.proj(x)
logits = self.logits(x)
return logits, mask
| x, mask = self.encode(x)
x = self.proj(x)
logits = self.logits(x)
return logits, mask
| 13 | 668 | 49 | 717 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,242 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model.py | 68,70 | 64,75 | units | HubertSoft | 70,75 | 70,75 | class HubertSoft(Hubert):
def __init__(self):
super().__init__()
@torch.inference_mode()
def units(self, wav: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY | class HubertSoft(Hubert):
def __init__(self):
super().__init__()
@torch.inference_mode()
def units(self, wav: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY | wav = t_func.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
x, _ = self.encode(wav)
return self.proj(x)
| wav = t_func.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
x, _ = self.encode(wav)
return self.proj(x)
| 19 | 71 | 71 | 142 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,243 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model.py | 124,125 | 112,130 | forward | PositionalConvEmbedding | 125,130 | 125,130 | class PositionalConvEmbedding(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv1d(
768,
768,
kernel_size=128,
padding=128 // 2,
groups=16,
)
self.conv = nn.utils.weight_norm(self.conv, name="weight", dim... | class PositionalConvEmbedding(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv1d(
768,
768,
kernel_size=128,
padding=128 // 2,
groups=16,
)
self.conv = nn.utils.weight_norm(self.conv, name="weight", dim... | x = self.conv(x.transpose(1, 2))
x = t_func.gelu(x[:, :, :-1])
return x.transpose(1, 2)
| x = self.conv(x.transpose(1, 2))
x = t_func.gelu(x[:, :, :-1])
return x.transpose(1, 2)
| 12 | 149 | 59 | 208 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,244 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model.py | 140,147 | 130,155 | forward | TransformerEncoder | 147,155 | 147,155 | class TransformerEncoder(nn.Module):
def __init__(
self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
) -> None:
super(TransformerEncoder, self).__init__()
self.layers = nn.ModuleList(
[copy.deepcopy(encoder_layer) for _ in range(num_layers)]
)
... | class TransformerEncoder(nn.Module):
def __init__(
self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
) -> None:
super(TransformerEncoder, self).__init__()
self.layers = nn.ModuleList(
[copy.deepcopy(encoder_layer) for _ in range(num_layers)]
)
... | output = src
for layer in self.layers[:output_layer]:
output = layer(
output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
)
return output
| output = src
for layer in self.layers[:output_layer]:
output = layer(
output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
)
return output
| 16 | 193 | 66 | 259 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,246 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model_onnx.py | 82,83 | 70,93 | forward | FeatureExtractor | 83,93 | 83,93 | class FeatureExtractor(nn.Module):
def __init__(self):
super().__init__()
self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
self.norm0 = nn.GroupNorm(512, 512)
self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.c... | class FeatureExtractor(nn.Module):
def __init__(self):
super().__init__()
self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
self.norm0 = nn.GroupNorm(512, 512)
self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
self.c... | x = t_func.gelu(self.norm0(self.conv0(x)))
x = t_func.gelu(self.conv1(x))
x = t_func.gelu(self.conv2(x))
x = t_func.gelu(self.conv3(x))
x = t_func.gelu(self.conv4(x))
x = t_func.gelu(self.conv5(x))
x = t_func.gelu(self.conv6(x))
return x
| x = t_func.gelu(self.norm0(self.conv0(x)))
x = t_func.gelu(self.conv1(x))
x = t_func.gelu(self.conv2(x))
x = t_func.gelu(self.conv3(x))
x = t_func.gelu(self.conv4(x))
x = t_func.gelu(self.conv5(x))
x = t_func.gelu(self.conv6(x))
return x
| 23 | 319 | 154 | 473 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,247 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model_onnx.py | 100,101 | 93,107 | forward | FeatureProjection | 101,107 | 101,107 | class FeatureProjection(nn.Module):
def __init__(self):
super().__init__()
self.norm = nn.LayerNorm(512)
self.projection = nn.Linear(512, 768)
self.dropout = nn.Dropout(0.1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY | class FeatureProjection(nn.Module):
def __init__(self):
super().__init__()
self.norm = nn.LayerNorm(512)
self.projection = nn.Linear(512, 768)
self.dropout = nn.Dropout(0.1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY | x = self.norm(x)
x = self.projection(x)
x = self.dropout(x)
return x
| x = self.norm(x)
x = self.projection(x)
x = self.dropout(x)
return x
| 11 | 114 | 44 | 158 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,248 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model_onnx.py | 31,32 | 11,58 | mask | Hubert | 32,38 | 32,38 | class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super().__init__()
self._mask = mask
self.feature_extractor = FeatureExtractor()
self.feature_projection = FeatureProjection()
self.positional_embedding = PositionalConvEmbedding(... | class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
super().__init__()
self._mask = mask
self.feature_extractor = FeatureExtractor()
self.feature_projection = FeatureProjection()
self.positional_embedding = PositionalConvEmbedding(... | mask = None
if self.training and self._mask:
mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2)
x[mask] = self.masked_spec_embed.to(x.dtype)
return x, mask
| mask = None
if self.training and self._mask:
mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2)
x[mask] = self.masked_spec_embed.to(x.dtype)
return x, mask
| 21 | 554 | 89 | 643 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,249 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model_onnx.py | 62,63 | 58,70 | units | HubertSoft | 63,67 | 63,67 | class HubertSoft(Hubert):
def __init__(self):
super().__init__()
def units(self, wav: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY def forward(self, x):
return self.units(x)
| class HubertSoft(Hubert):
def __init__(self):
super().__init__()
def units(self, wav: torch.Tensor) -> torch.Tensor:
FILL_FUNC_BODY def forward(self, x):
return self.units(x)
| wav = t_func.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
x, _ = self.encode(wav)
return self.proj(x)
| wav = t_func.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
x, _ = self.encode(wav)
return self.proj(x)
| 19 | 80 | 69 | 149 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,250 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model_onnx.py | 119,120 | 107,125 | forward | PositionalConvEmbedding | 120,125 | 120,125 | class PositionalConvEmbedding(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv1d(
768,
768,
kernel_size=128,
padding=128 // 2,
groups=16,
)
self.conv = nn.utils.weight_norm(self.conv, name="weight", dim... | class PositionalConvEmbedding(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv1d(
768,
768,
kernel_size=128,
padding=128 // 2,
groups=16,
)
self.conv = nn.utils.weight_norm(self.conv, name="weight", dim... | x = self.conv(x.transpose(1, 2))
x = t_func.gelu(x[:, :, :-1])
return x.transpose(1, 2)
| x = self.conv(x.transpose(1, 2))
x = t_func.gelu(x[:, :, :-1])
return x.transpose(1, 2)
| 12 | 149 | 59 | 208 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,251 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/hubert/hubert_model_onnx.py | 135,142 | 125,150 | forward | TransformerEncoder | 142,150 | 142,150 | class TransformerEncoder(nn.Module):
def __init__(
self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
) -> None:
super(TransformerEncoder, self).__init__()
self.layers = nn.ModuleList(
[copy.deepcopy(encoder_layer) for _ in range(num_layers)]
)
... | class TransformerEncoder(nn.Module):
def __init__(
self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
) -> None:
super(TransformerEncoder, self).__init__()
self.layers = nn.ModuleList(
[copy.deepcopy(encoder_layer) for _ in range(num_layers)]
)
... | output = src
for layer in self.layers[:output_layer]:
output = layer(
output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
)
return output
| output = src
for layer in self.layers[:output_layer]:
output = layer(
output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
)
return output
| 16 | 193 | 66 | 259 | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... | import copy
import random
from typing import Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as t_func
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
class Hubert(nn.Module):
def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
... |
25,252 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/whisper/audio.py | 91,92 | 1,124 | log_mel_spectrogram | 108,124 | 92,124 | from functools import lru_cache
from typing import Union
import ffmpeg
import numpy as np
import torch
import torch.nn.functional as F
from librosa.filters import mel as librosa_mel_fn
from .utils import exact_div
# hard-coded audio hyperparameters
SAMPLE_RATE = 16000
N_FFT = 400
N_MELS = 80
HOP_LENGTH = 160
CHUNK_L... | from functools import lru_cache
from typing import Union
import ffmpeg
import numpy as np
import torch
import torch.nn.functional as F
from librosa.filters import mel as librosa_mel_fn
from .utils import exact_div
# hard-coded audio hyperparameters
SAMPLE_RATE = 16000
N_FFT = 400
N_MELS = 80
HOP_LENGTH = 160
CHUNK_L... | if not torch.is_tensor(audio):
if isinstance(audio, str):
audio = load_audio(audio)
audio = torch.from_numpy(audio)
window = torch.hann_window(N_FFT).to(audio.device)
stft = torch.stft(audio, N_FFT, HOP_LENGTH, window=window, return_complex=True)
magnitudes = stft[..., :-1].... | """
Compute the log-Mel spectrogram of
Parameters
----------
audio: Union[str, np.ndarray, torch.Tensor], shape = (*)
The path to audio or either a NumPy array or Tensor containing the audio waveform in 16 kHz
n_mels: int
The number of Mel-frequency filters, only 80 is supporte... | 56 | 1,259 | 253 | 1,512 | from functools import lru_cache
from typing import Union
import ffmpeg
import numpy as np
import torch
import torch.nn.functional as F
from librosa.filters import mel as librosa_mel_fn
from .utils import exact_div
# hard-coded audio hyperparameters
SAMPLE_RATE = 16000
N_FFT = 400
N_MELS = 80
HOP_LENGTH = 160
CHUNK_L... | from functools import lru_cache
from typing import Union
import ffmpeg
import numpy as np
import torch
import torch.nn.functional as F
from librosa.filters import mel as librosa_mel_fn
from .utils import exact_div
# hard-coded audio hyperparameters
SAMPLE_RATE = 16000
N_FFT = 400
N_MELS = 80
HOP_LENGTH = 160
CHUNK_L... | |
25,253 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/whisper/utils.py | 46,47 | 1,164 | format_timestamp | 47,63 | 47,63 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... | assert seconds >= 0, "non-negative timestamp expected"
milliseconds = round(seconds * 1000.0)
hours = milliseconds // 3_600_000
milliseconds -= hours * 3_600_000
minutes = milliseconds // 60_000
milliseconds -= minutes * 60_000
seconds = milliseconds // 1_000
milliseconds -= seconds *... | assert seconds >= 0, "non-negative timestamp expected"
milliseconds = round(seconds * 1000.0)
hours = milliseconds // 3_600_000
milliseconds -= hours * 3_600_000
minutes = milliseconds // 60_000
milliseconds -= minutes * 60_000
seconds = milliseconds // 1_000
milliseconds -= seconds *... | 55 | 1,467 | 219 | 1,686 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... | |
25,254 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/whisper/utils.py | 76,77 | 63,80 | write_result | ResultWriter | 77,80 | 77,80 | class ResultWriter:
extension: str
def __init__(self, output_dir: str):
self.output_dir = output_dir
def __call__(self, result: dict, audio_path: str):
audio_basename = os.path.basename(audio_path)
output_path = os.path.join(self.output_dir, audio_basename + "." + self.extension)
... | class ResultWriter:
extension: str
def __init__(self, output_dir: str):
self.output_dir = output_dir
def __call__(self, result: dict, audio_path: str):
audio_basename = os.path.basename(audio_path)
output_path = os.path.join(self.output_dir, audio_basename + "." + self.extension)
... | raise NotImplementedError
| raise NotImplementedError
| 2 | 169 | 13 | 182 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... |
25,255 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/whisper/utils.py | 140,141 | 137,144 | write_result | WriteJSON | 141,144 | 141,144 | class WriteJSON(ResultWriter):
extension: str = "json"
def write_result(self, result: dict, file: TextIO):
FILL_FUNC_BODY | class WriteJSON(ResultWriter):
extension: str = "json"
def write_result(self, result: dict, file: TextIO):
FILL_FUNC_BODY | json.dump(result, file)
| json.dump(result, file)
| 2 | 46 | 15 | 61 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... |
25,256 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/whisper/utils.py | 105,106 | 102,118 | write_result | WriteSRT | 106,118 | 106,118 | class WriteSRT(ResultWriter):
extension: str = "srt"
def write_result(self, result: dict, file: TextIO):
FILL_FUNC_BODY | class WriteSRT(ResultWriter):
extension: str = "srt"
def write_result(self, result: dict, file: TextIO):
FILL_FUNC_BODY | for i, segment in enumerate(result["segments"], start=1):
# write srt lines
print(
f"{i}\n"
f"{format_timestamp(segment['start'], always_include_hours=True, decimal_marker=',')} --> "
f"{format_timestamp(segment['end'], always_include_hours... | for i, segment in enumerate(result["segments"], start=1):
# write srt lines
print(
f"{i}\n"
f"{format_timestamp(segment['start'], always_include_hours=True, decimal_marker=',')} --> "
f"{format_timestamp(segment['end'], always_include_hours... | 25 | 48 | 155 | 203 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... |
25,257 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/whisper/utils.py | 129,130 | 118,137 | write_result | WriteTSV | 130,137 | 130,137 | class WriteTSV(ResultWriter):
"""
Write a transcript to a file in TSV (tab-separated values) format containing lines like:
<start time in integer milliseconds>\t<end time in integer milliseconds>\t<transcript text>
Using integer milliseconds as start and end times means there's no chance of interferenc... | class WriteTSV(ResultWriter):
"""
Write a transcript to a file in TSV (tab-separated values) format containing lines like:
<start time in integer milliseconds>\t<end time in integer milliseconds>\t<transcript text>
Using integer milliseconds as start and end times means there's no chance of interferenc... | print("start", "end", "text", sep="\t", file=file)
for segment in result["segments"]:
print(round(1000 * segment['start']), file=file, end="\t")
print(round(1000 * segment['end']), file=file, end="\t")
print(segment['text'].strip().replace("\t", " "), file=file, flush... | print("start", "end", "text", sep="\t", file=file)
for segment in result["segments"]:
print(round(1000 * segment['start']), file=file, end="\t")
print(round(1000 * segment['end']), file=file, end="\t")
print(segment['text'].strip().replace("\t", " "), file=file, flush... | 24 | 172 | 120 | 292 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... |
25,258 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/whisper/utils.py | 83,84 | 80,88 | write_result | WriteTXT | 84,88 | 84,88 | class WriteTXT(ResultWriter):
extension: str = "txt"
def write_result(self, result: dict, file: TextIO):
FILL_FUNC_BODY | class WriteTXT(ResultWriter):
extension: str = "txt"
def write_result(self, result: dict, file: TextIO):
FILL_FUNC_BODY | for segment in result["segments"]:
print(segment['text'].strip(), file=file, flush=True)
| for segment in result["segments"]:
print(segment['text'].strip(), file=file, flush=True)
| 7 | 47 | 36 | 83 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... |
25,259 | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc | /home/hieuvd/dung_repo/raw/stars_01/svc-develop-team_so-vits-svc/so-vits-svc/vencoder/whisper/utils.py | 91,92 | 88,102 | write_result | WriteVTT | 92,102 | 92,102 | class WriteVTT(ResultWriter):
extension: str = "vtt"
def write_result(self, result: dict, file: TextIO):
FILL_FUNC_BODY | class WriteVTT(ResultWriter):
extension: str = "vtt"
def write_result(self, result: dict, file: TextIO):
FILL_FUNC_BODY | print("WEBVTT\n", file=file)
for segment in result["segments"]:
print(
f"{format_timestamp(segment['start'])} --> {format_timestamp(segment['end'])}\n"
f"{segment['text'].strip().replace('-->', '->')}\n",
file=file,
flush=True,
... | print("WEBVTT\n", file=file)
for segment in result["segments"]:
print(
f"{format_timestamp(segment['start'])} --> {format_timestamp(segment['end'])}\n"
f"{segment['text'].strip().replace('-->', '->')}\n",
file=file,
flush=True,
... | 15 | 48 | 110 | 158 | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... | import json
import os
import sys
import zlib
from typing import Callable, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError ... |
25,260 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/docs/public/file_cache.py | 49,50 | 1,108 | file_cache | 54,108 | 50,108 | import hashlib
import inspect
import os
import pickle
from loguru import logger
DISABLE_CACHE = False
MAX_DEPTH = 6
if DISABLE_CACHE:
print("File cache is disabled.")
def recursive_hash(value, depth=0, ignore_params=[]):
"""Hash primitives recursively with maximum depth."""
if depth > MAX_DEPTH:
... | import hashlib
import inspect
import os
import pickle
from loguru import logger
DISABLE_CACHE = False
MAX_DEPTH = 6
if DISABLE_CACHE:
print("File cache is disabled.")
def recursive_hash(value, depth=0, ignore_params=[]):
"""Hash primitives recursively with maximum depth."""
if depth > MAX_DEPTH:
... |
def decorator(func):
if DISABLE_CACHE:
if verbose:
print("Cache is disabled for function: " + func.__name__)
return func
func_source_code_hash = hash_code(inspect.getsource(func))
def wrapper(*args, **kwargs):
cache_dir = "/tmp/file_cache... | """Decorator to cache function output based on its inputs, ignoring specified parameters.
Ignore parameters are used to avoid caching on non-deterministic inputs, such as timestamps.
We can also ignore parameters that are slow to serialize/constant across runs, such as large objects.
"""
def decora... | 159 | 523 | 585 | 1,108 | import hashlib
import inspect
import os
import pickle
from loguru import logger
DISABLE_CACHE = False
MAX_DEPTH = 6
if DISABLE_CACHE:
print("File cache is disabled.")
def recursive_hash(value, depth=0, ignore_params=[]):
"""Hash primitives recursively with maximum depth."""
if depth > MAX_DEPTH:
... | import hashlib
import inspect
import os
import pickle
from loguru import logger
DISABLE_CACHE = False
MAX_DEPTH = 6
if DISABLE_CACHE:
print("File cache is disabled.")
def recursive_hash(value, depth=0, ignore_params=[]):
"""Hash primitives recursively with maximum depth."""
if depth > MAX_DEPTH:
... | |
25,261 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/docs/public/redis_vector_db.py | 62,68 | 1,134 | openai_with_expo_backoff | 68,110 | 68,110 | import hashlib
import json
import multiprocessing
import os
from typing import Generator
import backoff
import numpy as np
import requests
from loguru import logger
from openai import BadRequestError, OpenAI
from redis import Redis
from tiktoken import encoding_for_model
BATCH_SIZE = 512
REDIS_URL = os.environ.get("R... | import hashlib
import json
import multiprocessing
import os
from typing import Generator
import backoff
import numpy as np
import requests
from loguru import logger
from openai import BadRequestError, OpenAI
from redis import Redis
from tiktoken import encoding_for_model
BATCH_SIZE = 512
REDIS_URL = os.environ.get("R... | # 0. If we don't have a redis client, just call openai
if not redis_client:
return openai_call_embedding(batch)
# 1. Get embeddings from redis, using the hash of the text as the key
embeddings: list[np.ndarray] = [None] * len(batch)
cache_keys = [hash_text(text) + CACHE_VERSION for text in b... | # 0. If we don't have a redis client, just call openai
if not redis_client:
return openai_call_embedding(batch)
# 1. Get embeddings from redis, using the hash of the text as the key
embeddings: list[np.ndarray] = [None] * len(batch)
cache_keys = [hash_text(text) + CACHE_VERSION for text in b... | 220 | 1,102 | 620 | 1,722 | import hashlib
import json
import multiprocessing
import os
from typing import Generator
import backoff
import numpy as np
import requests
from loguru import logger
from openai import BadRequestError, OpenAI
from redis import Redis
from tiktoken import encoding_for_model
BATCH_SIZE = 512
REDIS_URL = os.environ.get("R... | import hashlib
import json
import multiprocessing
import os
from typing import Generator
import backoff
import numpy as np
import requests
from loguru import logger
from openai import BadRequestError, OpenAI
from redis import Redis
from tiktoken import encoding_for_model
BATCH_SIZE = 512
REDIS_URL = os.environ.get("R... | |
25,262 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/docs/sdk/src/agent.py | 228,230 | 224,234 | locations | Locations | 230,234 | 230,234 | class Locations(RegexExtractModel):
locations_string: str
_regex = r"<locations>(?P<locations_string>.*?)</locations>"
@property
def locations(self):
FILL_FUNC_BODY | class Locations(RegexExtractModel):
locations_string: str
_regex = r"<locations>(?P<locations_string>.*?)</locations>"
@property
def locations(self):
FILL_FUNC_BODY | return [
location for location in self.locations_string.split("\n") if location
]
| return [
location for location in self.locations_string.split("\n") if location
]
| 10 | 69 | 31 | 100 | import re
from typing import ClassVar, Generic, Literal, Type, TypeVar
import backoff
import tiktoken
from loguru import logger
from openai import OpenAI, RateLimitError
from pydantic import BaseModel
from sweepai.config.server import OPENAI_API_KEY
Self = TypeVar("Self", bound="RegexExtractModel")
client = OpenAI(... | import re
from typing import ClassVar, Generic, Literal, Type, TypeVar
import backoff
import tiktoken
from loguru import logger
from openai import OpenAI, RateLimitError
from pydantic import BaseModel
from sweepai.config.server import OPENAI_API_KEY
Self = TypeVar("Self", bound="RegexExtractModel")
client = OpenAI(... |
25,263 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/docs/sdk/src/agent.py | 38,39 | 31,46 | to_openai | Message | 39,46 | 39,46 | class Message(BaseModel):
role: Literal["system"] | Literal["user"] | Literal["assistant"] | Literal[
"function"
]
content: str | None = None
key: str | None = None
def to_openai(self) -> str:
FILL_FUNC_BODY | class Message(BaseModel):
role: Literal["system"] | Literal["user"] | Literal["assistant"] | Literal[
"function"
]
content: str | None = None
key: str | None = None
def to_openai(self) -> str:
FILL_FUNC_BODY | obj = {
"role": self.role,
"content": self.content,
}
return obj
| obj = {
"role": self.role,
"content": self.content,
}
return obj
| 10 | 84 | 39 | 123 | import re
from typing import ClassVar, Generic, Literal, Type, TypeVar
import backoff
import tiktoken
from loguru import logger
from openai import OpenAI, RateLimitError
from pydantic import BaseModel
from sweepai.config.server import OPENAI_API_KEY
Self = TypeVar("Self", bound="RegexExtractModel")
client = OpenAI(... | import re
from typing import ClassVar, Generic, Literal, Type, TypeVar
import backoff
import tiktoken
from loguru import logger
from openai import OpenAI, RateLimitError
from pydantic import BaseModel
from sweepai.config.server import OPENAI_API_KEY
Self = TypeVar("Self", bound="RegexExtractModel")
client = OpenAI(... |
25,264 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/docs/sdk/src/agent.py | 20,22 | 17,31 | from_string | RegexExtractModel | 22,31 | 22,31 | class RegexExtractModel(BaseModel):
_regex: ClassVar[str]
@classmethod
def from_string(cls: Type[Self], string: str, **kwargs) -> Self:
FILL_FUNC_BODY | class RegexExtractModel(BaseModel):
_regex: ClassVar[str]
@classmethod
def from_string(cls: Type[Self], string: str, **kwargs) -> Self:
FILL_FUNC_BODY | match = re.search(cls._regex, string, re.DOTALL)
if match is None:
raise Exception(f"Did not match {string} with pattern {cls._regex}")
return cls(
**{k: (v if v else None) for k, v in match.groupdict().items()},
**kwargs,
)
| match = re.search(cls._regex, string, re.DOTALL)
if match is None:
raise Exception(f"Did not match {string} with pattern {cls._regex}")
return cls(
**{k: (v if v else None) for k, v in match.groupdict().items()},
**kwargs,
)
| 32 | 61 | 99 | 160 | import re
from typing import ClassVar, Generic, Literal, Type, TypeVar
import backoff
import tiktoken
from loguru import logger
from openai import OpenAI, RateLimitError
from pydantic import BaseModel
from sweepai.config.server import OPENAI_API_KEY
Self = TypeVar("Self", bound="RegexExtractModel")
client = OpenAI(... | import re
from typing import ClassVar, Generic, Literal, Type, TypeVar
import backoff
import tiktoken
from loguru import logger
from openai import OpenAI, RateLimitError
from pydantic import BaseModel
from sweepai.config.server import OPENAI_API_KEY
Self = TypeVar("Self", bound="RegexExtractModel")
client = OpenAI(... |
25,265 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/docs/sdk/src/agent.py | 188,194 | 165,222 | handle_task_with_retries | SweepAgent | 194,222 | 194,222 | class SweepAgent(SweepChatGPT, Generic[R]):
regex_extract_model: ClassVar[Type[R]] = RegexExtractModel
system_prompt: ClassVar[str] = ""
user_prompt: ClassVar[str] = ""
def handle_task(
self,
system_prompt_args: dict[str, str] = {},
user_prompt_args: dict[str, str] = {},
... | class SweepAgent(SweepChatGPT, Generic[R]):
regex_extract_model: ClassVar[Type[R]] = RegexExtractModel
system_prompt: ClassVar[str] = ""
user_prompt: ClassVar[str] = ""
def handle_task(
self,
system_prompt_args: dict[str, str] = {},
user_prompt_args: dict[str, str] = {},
... | if self.system_prompt:
formatted_system_prompt = self.system_prompt.format(**system_prompt_args)
self.messages.append(
Message(role="system", content=formatted_system_prompt)
)
formatted_prompt = self.user_prompt.format(**user_prompt_args)
if s... | if self.system_prompt:
formatted_system_prompt = self.system_prompt.format(**system_prompt_args)
self.messages.append(
Message(role="system", content=formatted_system_prompt)
)
formatted_prompt = self.user_prompt.format(**user_prompt_args)
if s... | 62 | 346 | 329 | 675 | import re
from typing import ClassVar, Generic, Literal, Type, TypeVar
import backoff
import tiktoken
from loguru import logger
from openai import OpenAI, RateLimitError
from pydantic import BaseModel
from sweepai.config.server import OPENAI_API_KEY
Self = TypeVar("Self", bound="RegexExtractModel")
client = OpenAI(... | import re
from typing import ClassVar, Generic, Literal, Type, TypeVar
import backoff
import tiktoken
from loguru import logger
from openai import OpenAI, RateLimitError
from pydantic import BaseModel
from sweepai.config.server import OPENAI_API_KEY
Self = TypeVar("Self", bound="RegexExtractModel")
client = OpenAI(... |
25,266 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/docs/sdk/src/agent.py | 96,102 | 69,162 | call_openai | SweepChatGPT | 102,152 | 102,152 | class SweepChatGPT(BaseModel):
messages: list[Message] = []
model: OpenAIModel = "gpt-4-0613"
temperature: float = 0.1
def chat(
self,
content: str,
model: OpenAIModel | None = None,
message_key: str | None = None,
temperature: float | None = None,
max_to... | class SweepChatGPT(BaseModel):
messages: list[Message] = []
model: OpenAIModel = "gpt-4-0613"
temperature: float = 0.1
def chat(
self,
content: str,
model: OpenAIModel | None = None,
message_key: str | None = None,
temperature: float | None = None,
max_to... | count_tokens = lambda text: len(
tiktoken.encoding_for_model(model).encode(text, disallowed_special=())
)
messages_length = sum(
[count_tokens(message.content or "") for message in self.messages]
)
computed_max_tokens = (model_to_max_tokens[model] - int(me... | count_tokens = lambda text: len(
tiktoken.encoding_for_model(model).encode(text, disallowed_special=())
)
messages_length = sum(
[count_tokens(message.content or "") for message in self.messages]
)
computed_max_tokens = (model_to_max_tokens[model] - int(me... | 127 | 376 | 621 | 997 | import re
from typing import ClassVar, Generic, Literal, Type, TypeVar
import backoff
import tiktoken
from loguru import logger
from openai import OpenAI, RateLimitError
from pydantic import BaseModel
from sweepai.config.server import OPENAI_API_KEY
Self = TypeVar("Self", bound="RegexExtractModel")
client = OpenAI(... | import re
from typing import ClassVar, Generic, Literal, Type, TypeVar
import backoff
import tiktoken
from loguru import logger
from openai import OpenAI, RateLimitError
from pydantic import BaseModel
from sweepai.config.server import OPENAI_API_KEY
Self = TypeVar("Self", bound="RegexExtractModel")
client = OpenAI(... |
25,267 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/agent_utils.py | 9,10 | 1,30 | ensure_additional_messages_length | 10,30 | 10,30 |
# ensure that all additional_messages are 32768 characters at most, if not split them
import textwrap
from sweepai.core.entities import Message
MAX_CHARS = 32000
def ensure_additional_messages_length(additional_messages: list[Message]) -> list[Message]:
FILL_FUNC_BODY |
# ensure that all additional_messages are 32768 characters at most, if not split them
import textwrap
from sweepai.core.entities import Message
MAX_CHARS = 32000
def ensure_additional_messages_length(additional_messages: list[Message]) -> list[Message]:
FILL_FUNC_BODY | for i, additional_message in enumerate(additional_messages):
if len(additional_message.content) > MAX_CHARS:
wrapper = textwrap.TextWrapper(width=MAX_CHARS, replace_whitespace=False)
new_messages = wrapper.wrap(additional_message.content)
# replace the original message wi... | for i, additional_message in enumerate(additional_messages):
if len(additional_message.content) > MAX_CHARS:
wrapper = textwrap.TextWrapper(width=MAX_CHARS, replace_whitespace=False)
new_messages = wrapper.wrap(additional_message.content)
# replace the original message wi... | 53 | 89 | 217 | 306 |
# ensure that all additional_messages are 32768 characters at most, if not split them
import textwrap
from sweepai.core.entities import Message
MAX_CHARS = 32000
def ensure_additional_messages_length(additional_messages: list[Message]) -> list[Message]:
FILL_FUNC_BODY |
# ensure that all additional_messages are 32768 characters at most, if not split them
import textwrap
from sweepai.core.entities import Message
MAX_CHARS = 32000
def ensure_additional_messages_length(additional_messages: list[Message]) -> list[Message]:
FILL_FUNC_BODY | |
25,268 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/assistant_wrapper.py | 48,49 | 1,124 | fix_tool_calls | 49,85 | 49,85 | import json
from typing import Any, Callable, Optional
from loguru import logger
from openai.pagination import SyncCursorPage
from openai.types.chat.chat_completion_message_tool_call import (
ChatCompletionMessageToolCall,
Function,
)
from pydantic import BaseModel
def openai_retry_with_timeout(call, *args, n... | import json
from typing import Any, Callable, Optional
from loguru import logger
from openai.pagination import SyncCursorPage
from openai.types.chat.chat_completion_message_tool_call import (
ChatCompletionMessageToolCall,
Function,
)
from pydantic import BaseModel
def openai_retry_with_timeout(call, *args, n... | if tool_calls is None:
return
fixed_tool_calls = []
for tool_call in tool_calls:
current_function = tool_call.function.name
try:
function_args = json.loads(tool_call.function.arguments)
except json.JSONDecodeError:
logger.error(
f"Err... | if tool_calls is None:
return
fixed_tool_calls = []
for tool_call in tool_calls:
current_function = tool_call.function.name
try:
function_args = json.loads(tool_call.function.arguments)
except json.JSONDecodeError:
logger.error(
f"Err... | 69 | 724 | 402 | 1,126 | import json
from typing import Any, Callable, Optional
from loguru import logger
from openai.pagination import SyncCursorPage
from openai.types.chat.chat_completion_message_tool_call import (
ChatCompletionMessageToolCall,
Function,
)
from pydantic import BaseModel
def openai_retry_with_timeout(call, *args, n... | import json
from typing import Any, Callable, Optional
from loguru import logger
from openai.pagination import SyncCursorPage
from openai.types.chat.chat_completion_message_tool_call import (
ChatCompletionMessageToolCall,
Function,
)
from pydantic import BaseModel
def openai_retry_with_timeout(call, *args, n... | |
25,269 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/assistant_wrapper_test.py | 23,24 | 22,119 | test_multiple_tool_calls | TestFixToolCalls | 24,119 | 24,119 | class TestFixToolCalls(unittest.TestCase):
def test_multiple_tool_calls(self):
FILL_FUNC_BODY | class TestFixToolCalls(unittest.TestCase):
def test_multiple_tool_calls(self):
FILL_FUNC_BODY | # Setup input with multiple tool calls, including more than one 'parallel' tool calls
input_tool_calls = [
ChatCompletionMessageToolCall(
id="1",
type="function",
function={
"name": "parallel",
"arguments... | # Setup input with multiple tool calls, including more than one 'parallel' tool calls
input_tool_calls = [
ChatCompletionMessageToolCall(
id="1",
type="function",
function={
"name": "parallel",
"arguments... | 158 | 39 | 848 | 887 | import json
import unittest
from openai.types.chat.chat_completion_message_tool_call import (
ChatCompletionMessageToolCall,
Function,
)
from sweepai.agents.assistant_wrapper import fix_tool_calls
if __name__ == "__main__":
tool_call = ChatCompletionMessageToolCall(
id="tool_call_id",
fun... | import json
import unittest
from openai.types.chat.chat_completion_message_tool_call import (
ChatCompletionMessageToolCall,
Function,
)
from sweepai.agents.assistant_wrapper import fix_tool_calls
if __name__ == "__main__":
tool_call = ChatCompletionMessageToolCall(
id="tool_call_id",
fun... |
25,270 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/complete_code.py | 57,58 | 56,78 | extract_leftover_comments | ExtractLeftoverComments | 58,78 | 58,78 | class ExtractLeftoverComments(ChatGPT):
def extract_leftover_comments(self, new_code, file_path, request, **kwargs):
FILL_FUNC_BODY | class ExtractLeftoverComments(ChatGPT):
def extract_leftover_comments(self, new_code, file_path, request, **kwargs):
FILL_FUNC_BODY | try:
if not check_comments_presence(file_path, new_code):
return []
self.messages = [
Message(role="system", content=system_message_prompt, key="system")
]
response = self.chat(
user_prompt.format(
... | try:
if not check_comments_presence(file_path, new_code):
return []
self.messages = [
Message(role="system", content=system_message_prompt, key="system")
]
response = self.chat(
user_prompt.format(
... | 42 | 51 | 201 | 252 | """
We should input an updated snippet generated by Sweep, and output the comment that was left in the code
"""
import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
from sweepai.utils.comment_utils import check_comments_presence
... | """
We should input an updated snippet generated by Sweep, and output the comment that was left in the code
"""
import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
from sweepai.utils.comment_utils import check_comments_presence
... |
25,271 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/complete_code.py | 38,40 | 35,56 | from_string | LeftoverComments | 40,56 | 40,56 | class LeftoverComments(RegexMatchableBaseModel):
leftover_comments: list[str] = []
@classmethod
def from_string(cls, leftover_comments_response: str, **kwargs):
FILL_FUNC_BODY | class LeftoverComments(RegexMatchableBaseModel):
leftover_comments: list[str] = []
@classmethod
def from_string(cls, leftover_comments_response: str, **kwargs):
FILL_FUNC_BODY | leftover_comments = []
leftover_comments_pattern = (
r"""<leftover_comment>(\n)?(?P<leftover_comment>.*?)</leftover_comment>"""
)
for match_ in re.finditer(
leftover_comments_pattern, leftover_comments_response, re.DOTALL
):
leftover_comment = ... | leftover_comments = []
leftover_comments_pattern = (
r"""<leftover_comment>(\n)?(?P<leftover_comment>.*?)</leftover_comment>"""
)
for match_ in re.finditer(
leftover_comments_pattern, leftover_comments_response, re.DOTALL
):
leftover_comment = ... | 28 | 70 | 214 | 284 | """
We should input an updated snippet generated by Sweep, and output the comment that was left in the code
"""
import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
from sweepai.utils.comment_utils import check_comments_presence
... | """
We should input an updated snippet generated by Sweep, and output the comment that was left in the code
"""
import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
from sweepai.utils.comment_utils import check_comments_presence
... |
25,272 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/complete_code_test.py | 25,31 | 7,42 | test_extract_leftover_comments_no_comments | TestExtractLeftoverCommentsExtractLeftoverComments | 31,42 | 31,42 | class TestExtractLeftoverCommentsExtractLeftoverComments(unittest.TestCase):
@patch("sweepai.agents.complete_code.check_comments_presence")
@patch("sweepai.agents.complete_code.ExtractLeftoverComments.chat")
@patch("sweepai.agents.complete_code.LeftoverComments.from_string")
def test_extract_leftover_co... | class TestExtractLeftoverCommentsExtractLeftoverComments(unittest.TestCase):
@patch("sweepai.agents.complete_code.check_comments_presence")
@patch("sweepai.agents.complete_code.ExtractLeftoverComments.chat")
@patch("sweepai.agents.complete_code.LeftoverComments.from_string")
def test_extract_leftover_co... | mock_check_comments_presence.return_value = False
extract_leftover_comments = ExtractLeftoverComments(chat_logger=None)
result = extract_leftover_comments.extract_leftover_comments(
"new_code", "file_path", "request"
)
self.assertEqual(result, [])
mock_chat.a... | mock_check_comments_presence.return_value = False
extract_leftover_comments = ExtractLeftoverComments(chat_logger=None)
result = extract_leftover_comments.extract_leftover_comments(
"new_code", "file_path", "request"
)
self.assertEqual(result, [])
mock_chat.a... | 17 | 414 | 130 | 544 | import unittest
from unittest.mock import MagicMock, patch
from sweepai.agents.complete_code import ExtractLeftoverComments
class TestExtractLeftoverCommentsExtractLeftoverComments(unittest.TestCase):
@patch("sweepai.agents.complete_code.check_comments_presence")
@patch("sweepai.agents.complete_code.ExtractL... | import unittest
from unittest.mock import MagicMock, patch
from sweepai.agents.complete_code import ExtractLeftoverComments
class TestExtractLeftoverCommentsExtractLeftoverComments(unittest.TestCase):
@patch("sweepai.agents.complete_code.check_comments_presence")
@patch("sweepai.agents.complete_code.ExtractL... |
25,273 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/distill_issue.py | 43,44 | 1,76 | distill_issue | 44,66 | 44,66 | import re
from github import Github
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
system_prompt = """Your job is to clean up a GitHub issue for a contract developer to resolve.
Respond in the following format:
<distilled_issue>
```
Sections of the markdown file copied verbose.
```
... | import re
from github import Github
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
system_prompt = """Your job is to clean up a GitHub issue for a contract developer to resolve.
Respond in the following format:
<distilled_issue>
```
Sections of the markdown file copied verbose.
```
... | if DISTILLED_SUMMARY_MARKER in text:
return text
chatgpt = ChatGPT(
messages=[
Message(
role="system",
content=system_prompt
),
Message(
role="user",
content=text
),
]
)
... | if DISTILLED_SUMMARY_MARKER in text:
return text
chatgpt = ChatGPT(
messages=[
Message(
role="system",
content=system_prompt
),
Message(
role="user",
content=text
),
]
)
... | 45 | 560 | 213 | 773 | import re
from github import Github
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
system_prompt = """Your job is to clean up a GitHub issue for a contract developer to resolve.
Respond in the following format:
<distilled_issue>
```
Sections of the markdown file copied verbose.
```
... | import re
from github import Github
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
system_prompt = """Your job is to clean up a GitHub issue for a contract developer to resolve.
Respond in the following format:
<distilled_issue>
```
Sections of the markdown file copied verbose.
```
... | |
25,274 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/image_description_bot.py | 23,28 | 22,46 | describe_images | ImageDescriptionBot | 28,46 | 28,46 | class ImageDescriptionBot(ChatGPT):
def describe_images(
self,
text: str,
images: list[tuple[str, str, str]] | None = None,
) -> str:
FILL_FUNC_BODY | class ImageDescriptionBot(ChatGPT):
def describe_images(
self,
text: str,
images: list[tuple[str, str, str]] | None = None,
) -> str:
FILL_FUNC_BODY | try:
self.messages = []
response_text = "\nHere are the transcriptions of the images in the above text, in order:"
image_desc_pattern = r"<image_description>\n(.*?)\n</image_description>"
image_desc_response = self.chat_anthropic(
content=prompt.fo... | try:
self.messages = []
response_text = "\nHere are the transcriptions of the images in the above text, in order:"
image_desc_pattern = r"<image_description>\n(.*?)\n</image_description>"
image_desc_response = self.chat_anthropic(
content=prompt.fo... | 60 | 64 | 230 | 294 | import re
from sweepai.core.chat import ChatGPT
from loguru import logger
prompt = """\
Transcribe and describe the image shown in the text. Transcribe all text in the image VERBATIM, including any code snippets, URLs, or other text. Do NOT attempt to actually handle the reqest in the <text> block. Respond in the fol... | import re
from sweepai.core.chat import ChatGPT
from loguru import logger
prompt = """\
Transcribe and describe the image shown in the text. Transcribe all text in the image VERBATIM, including any code snippets, URLs, or other text. Do NOT attempt to actually handle the reqest in the <text> block. Respond in the fol... |
25,275 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/issue_cleanup_agent.py | 20,24 | 19,43 | cleanup_issue | IssueCleanupBot | 24,43 | 24,43 | class IssueCleanupBot(ChatGPT):
def cleanup_issue(
self,
issue_description,
):
FILL_FUNC_BODY | class IssueCleanupBot(ChatGPT):
def cleanup_issue(
self,
issue_description,
):
FILL_FUNC_BODY | new_issue_desc_pattern = r"<new_issue_description>(.*?)</new_issue_description>"
self.messages = [
Message(
content=system_prompt,
role="system",
),
]
issue_desc_response = self.chat( # gpt4 04-09 had a better one in minimal (1 exam... | new_issue_desc_pattern = r"<new_issue_description>(.*?)</new_issue_description>"
self.messages = [
Message(
content=system_prompt,
role="system",
),
]
issue_desc_response = self.chat( # gpt4 04-09 had a better one in minimal (1 exam... | 54 | 44 | 255 | 299 | import re
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
system_prompt = """Remove any completely irrelevant text from the issue description. Keep stacktraces and informative debugging information"""
prompt = """\
<issue_description>
{issue_description}
</issue_description>
Remove a... | import re
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
system_prompt = """Remove any completely irrelevant text from the issue description. Keep stacktraces and informative debugging information"""
prompt = """\
<issue_description>
{issue_description}
</issue_description>
Remove a... |
25,276 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/pr_description_bot.py | 26,31 | 25,51 | describe_diffs | PRDescriptionBot | 31,51 | 31,51 | class PRDescriptionBot(ChatGPT):
def describe_diffs(
self,
diffs,
pr_title,
):
FILL_FUNC_BODY | class PRDescriptionBot(ChatGPT):
def describe_diffs(
self,
diffs,
pr_title,
):
FILL_FUNC_BODY | self.messages = []
# attempt to generate description 3 times
pr_desc_pattern = r"<pr_description>\n(.*?)\n</pr_description>"
for attempt in [0, 1, 2]:
pr_desc_response = self.chat(
content=prompt.format(
diffs=diffs,
pr_... | self.messages = []
# attempt to generate description 3 times
pr_desc_pattern = r"<pr_description>\n(.*?)\n</pr_description>"
for attempt in [0, 1, 2]:
pr_desc_response = self.chat(
content=prompt.format(
diffs=diffs,
pr_... | 52 | 47 | 223 | 270 | import re
from sweepai.core.chat import ChatGPT
prompt = """\
Write a pull request description that reflects all changes in this pull request. Here are the changes:
<diffs>
{diffs}
</diffs>
Here is the pull request title:
<pr_title>
{pr_title}
</pr_title>
Format your response using the following XML tags:
<pr_descr... | import re
from sweepai.core.chat import ChatGPT
prompt = """\
Write a pull request description that reflects all changes in this pull request. Here are the changes:
<diffs>
{diffs}
</diffs>
Here is the pull request title:
<pr_title>
{pr_title}
</pr_title>
Format your response using the following XML tags:
<pr_descr... |
25,277 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/prune_modify_snippets.py | 85,94 | 84,118 | prune_modify_snippets | PruneModifySnippets | 94,118 | 94,118 | class PruneModifySnippets(ChatGPT):
def prune_modify_snippets(
self,
snippets: list[str],
file_path: str,
changes_made: str,
old_code: str,
request: str,
**kwargs,
) -> list[int]:
FILL_FUNC_BODY | class PruneModifySnippets(ChatGPT):
def prune_modify_snippets(
self,
snippets: list[str],
file_path: str,
changes_made: str,
old_code: str,
request: str,
**kwargs,
) -> list[int]:
FILL_FUNC_BODY | try:
if old_code:
old_code = f"<old_code>\n```\n{old_code}\n```\n</old_code>"
self.messages[0] = Message(
role="system", content=system_message_prompt, key="system"
)
response = self.chat(
user_prompt.format(
... | try:
if old_code:
old_code = f"<old_code>\n```\n{old_code}\n```\n</old_code>"
self.messages[0] = Message(
role="system", content=system_message_prompt, key="system"
)
response = self.chat(
user_prompt.format(
... | 43 | 95 | 251 | 346 | """
Input: snippets output: snippets to keep
"""
import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
system_message_prompt = """You are a genius engineer tasked with identifying only the necessary code snippets for the followin... | """
Input: snippets output: snippets to keep
"""
import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
system_message_prompt = """You are a genius engineer tasked with identifying only the necessary code snippets for the followin... |
25,278 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/agents/prune_modify_snippets.py | 65,67 | 62,84 | from_string | PrunedSnippets | 67,84 | 67,84 | class PrunedSnippets(RegexMatchableBaseModel):
snippet_indices: list[int] = []
@classmethod
def from_string(cls, pruned_snippets_response: str, **kwargs) -> "PrunedSnippets":
FILL_FUNC_BODY | class PrunedSnippets(RegexMatchableBaseModel):
snippet_indices: list[int] = []
@classmethod
def from_string(cls, pruned_snippets_response: str, **kwargs) -> "PrunedSnippets":
FILL_FUNC_BODY | snippet_indices = set()
pruned_snippets_pattern = r"""<index>(\n)?(?P<index>.*?)</index>"""
for match_ in re.finditer(
pruned_snippets_pattern, pruned_snippets_response, re.DOTALL
):
index = match_.group("index").strip("\n")
index = int(index)
... | snippet_indices = set()
pruned_snippets_pattern = r"""<index>(\n)?(?P<index>.*?)</index>"""
for match_ in re.finditer(
pruned_snippets_pattern, pruned_snippets_response, re.DOTALL
):
index = match_.group("index").strip("\n")
index = int(index)
... | 38 | 81 | 219 | 300 | """
Input: snippets output: snippets to keep
"""
import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
system_message_prompt = """You are a genius engineer tasked with identifying only the necessary code snippets for the followin... | """
Input: snippets output: snippets to keep
"""
import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
system_message_prompt = """You are a genius engineer tasked with identifying only the necessary code snippets for the followin... |
25,281 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/api_test.py | 11,12 | 7,23 | test_home | TestAPI | 12,23 | 12,23 | class TestAPI(unittest.TestCase):
def setUp(self):
self.mock_api = unittest.mock.create_autospec(api)
def test_home(self):
FILL_FUNC_BODY | class TestAPI(unittest.TestCase):
def setUp(self):
self.mock_api = unittest.mock.create_autospec(api)
def test_home(self):
FILL_FUNC_BODY | self.mock_api.home.return_value = "<h2>Sweep Webhook is up and running! To get started, copy the URL into the GitHub App settings' webhook field.</h2>"
result = self.mock_api.home()
self.assertEqual(
result,
"<h2>Sweep Webhook is up and running! To get started, copy the U... | self.mock_api.home.return_value = "<h2>Sweep Webhook is up and running! To get started, copy the URL into the GitHub App settings' webhook field.</h2>"
result = self.mock_api.home()
self.assertEqual(
result,
"<h2>Sweep Webhook is up and running! To get started, copy the U... | 59 | 61 | 165 | 226 | import unittest
import unittest.mock
from sweepai import api
class TestAPI(unittest.TestCase):
def setUp(self):
self.mock_api = unittest.mock.create_autospec(api)
def test_home(self):
FILL_FUNC_BODYif __name__ == "__main__":
unittest.main()
| import unittest
import unittest.mock
from sweepai import api
class TestAPI(unittest.TestCase):
def setUp(self):
self.mock_api = unittest.mock.create_autospec(api)
def test_home(self):
FILL_FUNC_BODYif __name__ == "__main__":
unittest.main()
|
25,283 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/cli_test.py | 30,32 | 29,36 | test_run_issue_no_config | TestCLIRunIsssue | 32,36 | 32,36 | class TestCLIRunIsssue(unittest.TestCase):
@patch("os.path.exists", return_value=False)
def test_run_issue_no_config(self, mock_exists):
FILL_FUNC_BODY | class TestCLIRunIsssue(unittest.TestCase):
@patch("os.path.exists", return_value=False)
def test_run_issue_no_config(self, mock_exists):
FILL_FUNC_BODY | with self.assertRaises(ValueError):
run("https://github.com/sweepai/e2e/issues/1")
| with self.assertRaises(ValueError):
run("https://github.com/sweepai/e2e/issues/1")
| 3 | 62 | 40 | 102 | import json
import os
import unittest
from unittest.mock import mock_open, patch
from sweepai.cli import load_config, run
class TestConfigLoading(unittest.TestCase):
@patch.dict(os.environ, {}, clear=True)
@patch("os.path.exists", return_value=True)
@patch(
"builtins.open",
new_callable=m... | import json
import os
import unittest
from unittest.mock import mock_open, patch
from sweepai.cli import load_config, run
class TestConfigLoading(unittest.TestCase):
@patch.dict(os.environ, {}, clear=True)
@patch("os.path.exists", return_value=True)
@patch(
"builtins.open",
new_callable=m... |
25,284 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/cli_test.py | 10,20 | 9,29 | test_load_config | TestConfigLoading | 20,29 | 20,29 | class TestConfigLoading(unittest.TestCase):
@patch.dict(os.environ, {}, clear=True)
@patch("os.path.exists", return_value=True)
@patch(
"builtins.open",
new_callable=mock_open,
read_data=json.dumps(
{"GITHUB_PAT": "test_github_pat", "OPENAI_API_KEY": "test_openai_key"}
... | class TestConfigLoading(unittest.TestCase):
@patch.dict(os.environ, {}, clear=True)
@patch("os.path.exists", return_value=True)
@patch(
"builtins.open",
new_callable=mock_open,
read_data=json.dumps(
{"GITHUB_PAT": "test_github_pat", "OPENAI_API_KEY": "test_openai_key"}
... | with self.assertRaises(KeyError):
os.environ["GITHUB_PAT"]
with self.assertRaises(KeyError):
os.environ["OPENAI_API_KEY"]
load_config()
self.assertEqual(os.environ["GITHUB_PAT"], "test_github_pat")
self.assertEqual(os.environ["OPENAI_API_KEY"], "test_opena... | with self.assertRaises(KeyError):
os.environ["GITHUB_PAT"]
with self.assertRaises(KeyError):
os.environ["OPENAI_API_KEY"]
load_config()
self.assertEqual(os.environ["GITHUB_PAT"], "test_github_pat")
self.assertEqual(os.environ["OPENAI_API_KEY"], "test_opena... | 11 | 150 | 122 | 272 | import json
import os
import unittest
from unittest.mock import mock_open, patch
from sweepai.cli import load_config, run
class TestConfigLoading(unittest.TestCase):
@patch.dict(os.environ, {}, clear=True)
@patch("os.path.exists", return_value=True)
@patch(
"builtins.open",
new_callable=m... | import json
import os
import unittest
from unittest.mock import mock_open, patch
from sweepai.cli import load_config, run
class TestConfigLoading(unittest.TestCase):
@patch.dict(os.environ, {}, clear=True)
@patch("os.path.exists", return_value=True)
@patch(
"builtins.open",
new_callable=m... |
25,287 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/annotate_code_openai.py | 111,113 | 1,155 | get_annotated_source_code | 113,150 | 113,150 | import multiprocessing
import re
from loguru import logger
from tqdm import tqdm
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.logn.cache import file_cache
from sweepai.utils.utils import chunk_code
CLAUDE_MODEL = "claude-3-haiku-20240307"
NUM_WORKERS = 4 # tune based on... | import multiprocessing
import re
from loguru import logger
from tqdm import tqdm
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.logn.cache import file_cache
from sweepai.utils.utils import chunk_code
CLAUDE_MODEL = "claude-3-haiku-20240307"
NUM_WORKERS = 4 # tune based on... | annotated_source_code = source_code
code_chunks = chunk_code(source_code, "test.py", MAX_CHARS=60 * 50)
code_contents = [chunk.get_snippet(False, False) for chunk in code_chunks]
if NUM_WORKERS > 1:
pool = multiprocessing.Pool(processes=NUM_WORKERS)
results = [
pool.apply_as... | annotated_source_code = source_code
code_chunks = chunk_code(source_code, "test.py", MAX_CHARS=60 * 50)
code_contents = [chunk.get_snippet(False, False) for chunk in code_chunks]
if NUM_WORKERS > 1:
pool = multiprocessing.Pool(processes=NUM_WORKERS)
results = [
pool.apply_as... | 134 | 1,391 | 638 | 2,029 | import multiprocessing
import re
from loguru import logger
from tqdm import tqdm
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.logn.cache import file_cache
from sweepai.utils.utils import chunk_code
CLAUDE_MODEL = "claude-3-haiku-20240307"
NUM_WORKERS = 4 # tune based on... | import multiprocessing
import re
from loguru import logger
from tqdm import tqdm
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.logn.cache import file_cache
from sweepai.utils.utils import chunk_code
CLAUDE_MODEL = "claude-3-haiku-20240307"
NUM_WORKERS = 4 # tune based on... | |
25,288 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/annotate_code_openai.py | 49,55 | 48,99 | annotate_code | AnnotateCodeBot | 55,99 | 55,99 | class AnnotateCodeBot(ChatGPT):
def annotate_code(
self,
source_code: str,
issue_text: str,
code_to_annotate: str,
):
FILL_FUNC_BODY | class AnnotateCodeBot(ChatGPT):
def annotate_code(
self,
source_code: str,
issue_text: str,
code_to_annotate: str,
):
FILL_FUNC_BODY | annotate_code_pattern = r"<code_annotation>(.*?)</code_annotation>"
self.messages = [
Message(
content=system_prompt,
role="system",
),
]
try:
code_annotation_response = self.chat_anthropic(
content=user_... | annotate_code_pattern = r"<code_annotation>(.*?)</code_annotation>"
self.messages = [
Message(
content=system_prompt,
role="system",
),
]
try:
code_annotation_response = self.chat_anthropic(
content=user_... | 136 | 66 | 648 | 714 | import multiprocessing
import re
from loguru import logger
from tqdm import tqdm
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.logn.cache import file_cache
from sweepai.utils.utils import chunk_code
CLAUDE_MODEL = "claude-3-haiku-20240307"
NUM_WORKERS = 4 # tune based on... | import multiprocessing
import re
from loguru import logger
from tqdm import tqdm
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.logn.cache import file_cache
from sweepai.utils.utils import chunk_code
CLAUDE_MODEL = "claude-3-haiku-20240307"
NUM_WORKERS = 4 # tune based on... |
25,291 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/chat.py | 98,101 | 84,115 | delete_messages_from_chat | MessageList | 101,115 | 101,115 | class MessageList(BaseModel):
messages: list[Message] = [
Message(
role="system",
content=system_message_prompt,
)
]
@property
def messages_dicts(self):
# Remove the key from the message object before sending to OpenAI
cleaned_messages = [message.... | class MessageList(BaseModel):
messages: list[Message] = [
Message(
role="system",
content=system_message_prompt,
)
]
@property
def messages_dicts(self):
# Remove the key from the message object before sending to OpenAI
cleaned_messages = [message.... | self.messages = [
message
for message in self.messages
if not (
key_to_delete in (message.key or "")
and (
delete_user
and message.role == "user"
or delete_assistant
... | self.messages = [
message
for message in self.messages
if not (
key_to_delete in (message.key or "")
and (
delete_user
and message.role == "user"
or delete_assistant
... | 46 | 153 | 114 | 267 | from math import inf
import os
import re
import time
import traceback
from typing import Any, Iterator, Literal
from anthropic import Anthropic, BadRequestError, AnthropicBedrock
from openai import OpenAI
import backoff
from loguru import logger
from pydantic import BaseModel
from sweepai.agents.agent_utils import en... | from math import inf
import os
import re
import time
import traceback
from typing import Any, Iterator, Literal
from anthropic import Anthropic, BadRequestError, AnthropicBedrock
from openai import OpenAI
import backoff
from loguru import logger
from pydantic import BaseModel
from sweepai.agents.agent_utils import en... |
25,293 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/context_pruning.py | 309,310 | 196,320 | append_relevant_file_paths | RepoContextManager | 310,313 | 310,313 | @dataclass
class RepoContextManager:
dir_obj: DirectoryTree
current_top_tree: str
snippets: list[Snippet]
snippet_scores: dict[str, float]
cloned_repo: ClonedRepo
current_top_snippets: list[Snippet] = field(default_factory=list)
read_only_snippets: list[Snippet] = field(default_factory=list)... | @dataclass
class RepoContextManager:
dir_obj: DirectoryTree
current_top_tree: str
snippets: list[Snippet]
snippet_scores: dict[str, float]
cloned_repo: ClonedRepo
current_top_snippets: list[Snippet] = field(default_factory=list)
read_only_snippets: list[Snippet] = field(default_factory=list)... | # do not use append, it modifies the list in place and will update it for ALL instances of RepoContextManager
self.relevant_file_paths = self.relevant_file_paths + [relevant_file_paths]
| # do not use append, it modifies the list in place and will update it for ALL instances of RepoContextManager
self.relevant_file_paths = self.relevant_file_paths + [relevant_file_paths]
| 25 | 1,585 | 59 | 1,644 | from copy import deepcopy
from math import log
import os
import subprocess
import urllib
from dataclasses import dataclass, field
import networkx as nx
import openai
from loguru import logger
from openai.types.beta.thread import Thread
from openai.types.beta.threads.run import Run
from sweepai.config.client import Sw... | from copy import deepcopy
from math import log
import os
import subprocess
import urllib
from dataclasses import dataclass, field
import networkx as nx
import openai
from loguru import logger
from openai.types.beta.thread import Thread
from openai.types.beta.threads.run import Run
from sweepai.config.client import Sw... |
25,295 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/entities.py | 473,475 | 469,482 | from_string | DiffSummarization | 475,482 | 475,482 | class DiffSummarization(RegexMatchableBaseModel):
content: str
_regex = r"""<file_summaries>(\n)?(?P<content>.*)$"""
@classmethod
def from_string(cls: Type[Self], string: str, **kwargs) -> Self:
FILL_FUNC_BODY | class DiffSummarization(RegexMatchableBaseModel):
content: str
_regex = r"""<file_summaries>(\n)?(?P<content>.*)$"""
@classmethod
def from_string(cls: Type[Self], string: str, **kwargs) -> Self:
FILL_FUNC_BODY | result = super().from_string(string, **kwargs)
result.content = result.content.replace("</file_summaries>", "", 1).strip()
return cls(
content=result.content,
)
| result = super().from_string(string, **kwargs)
result.content = result.content.replace("</file_summaries>", "", 1).strip()
return cls(
content=result.content,
)
| 13 | 86 | 68 | 154 | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... |
25,296 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/entities.py | 128,130 | 124,136 | from_string | ExtractionRequest | 130,136 | 130,136 | class ExtractionRequest(RegexMatchableBaseModel):
use_tools: bool
_regex = r"""<use_tools>\s+(?P<use_tools>.*?)</use_tools>"""
@classmethod
def from_string(cls: Type[Self], string: str, **kwargs) -> Self:
FILL_FUNC_BODY | class ExtractionRequest(RegexMatchableBaseModel):
use_tools: bool
_regex = r"""<use_tools>\s+(?P<use_tools>.*?)</use_tools>"""
@classmethod
def from_string(cls: Type[Self], string: str, **kwargs) -> Self:
FILL_FUNC_BODY | use_tools_pattern = r"""<use_tools>\s+(?P<use_tools>.*?)</use_tools>"""
use_tools_match = re.search(use_tools_pattern, string, re.DOTALL)
use_tools = use_tools_match.groupdict()["use_tools"].strip().lower() == "true"
return cls(use_tools=use_tools)
| use_tools_pattern = r"""<use_tools>\s+(?P<use_tools>.*?)</use_tools>"""
use_tools_match = re.search(use_tools_pattern, string, re.DOTALL)
use_tools = use_tools_match.groupdict()["use_tools"].strip().lower() == "true"
return cls(use_tools=use_tools)
| 15 | 92 | 111 | 203 | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... |
25,297 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/entities.py | 179,181 | 136,287 | from_string | FileChangeRequest | 181,202 | 181,202 | class FileChangeRequest(RegexMatchableBaseModel):
filename: str
instructions: str
change_type: (
Literal["modify"]
| Literal["create"]
| Literal["delete"]
| Literal["rename"]
| Literal["rewrite"]
| Literal["check"]
| Literal["refactor"]
| Liter... | class FileChangeRequest(RegexMatchableBaseModel):
filename: str
instructions: str
change_type: (
Literal["modify"]
| Literal["create"]
| Literal["delete"]
| Literal["rename"]
| Literal["rewrite"]
| Literal["check"]
| Literal["refactor"]
| Liter... | result = super().from_string(string, **kwargs)
result.filename = result.filename.strip("/")
result.instructions = result.instructions.replace("\n*", "\n•")
if result.source_file:
result.source_file = result.source_file.strip()
if " " in result.source_file:
... | result = super().from_string(string, **kwargs)
result.filename = result.filename.strip("/")
result.instructions = result.instructions.replace("\n*", "\n•")
if result.source_file:
result.source_file = result.source_file.strip()
if " " in result.source_file:
... | 56 | 1,428 | 252 | 1,680 | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... |
25,298 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/entities.py | 293,295 | 287,340 | from_string | FileCreation | 295,340 | 295,340 | class FileCreation(RegexMatchableBaseModel):
commit_message: str
code: str
_regex = r"""<new_file(.*?)>(?P<code>.*)</new_file>"""
# Regex updated to support ``` outside of <new_file> tags
@classmethod
def from_string(cls: Type[Self], string: str, **kwargs) -> Self:
FILL_FUNC_BODY | class FileCreation(RegexMatchableBaseModel):
commit_message: str
code: str
_regex = r"""<new_file(.*?)>(?P<code>.*)</new_file>"""
# Regex updated to support ``` outside of <new_file> tags
@classmethod
def from_string(cls: Type[Self], string: str, **kwargs) -> Self:
FILL_FUNC_BODY | re_match = re.search(cls._regex, string, re.DOTALL)
if re_match is None:
logger.info(f"Did not match {string} with pattern {cls._regex}")
raise ValueError("No <new_file> tags or ``` found in code block")
result = cls(
code=re_match.groupdict()["code"].strip(... | re_match = re.search(cls._regex, string, re.DOTALL)
if re_match is None:
logger.info(f"Did not match {string} with pattern {cls._regex}")
raise ValueError("No <new_file> tags or ``` found in code block")
result = cls(
code=re_match.groupdict()["code"].strip(... | 131 | 113 | 563 | 676 | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... |
25,299 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/entities.py | 33,35 | 24,52 | from_tuple | Message | 35,40 | 35,40 | class Message(BaseModel):
role: (
Literal["system"] | Literal["user"] | Literal["assistant"] | Literal["function"]
)
content: str | None = None
name: str | None = None
function_call: dict | None = None
key: str | None = None
@classmethod
def from_tuple(cls, tup: tuple[str | None... | class Message(BaseModel):
role: (
Literal["system"] | Literal["user"] | Literal["assistant"] | Literal["function"]
)
content: str | None = None
name: str | None = None
function_call: dict | None = None
key: str | None = None
@classmethod
def from_tuple(cls, tup: tuple[str | None... | if tup[0] is None:
return cls(role="assistant", content=tup[1])
else:
return cls(role="user", content=tup[0])
| if tup[0] is None:
return cls(role="assistant", content=tup[1])
else:
return cls(role="user", content=tup[0])
| 11 | 211 | 58 | 269 | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... |
25,300 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/entities.py | 511,512 | 497,519 | create_review | MockPR | 512,515 | 512,515 | class MockPR(BaseModel):
# Used to mock a PR object without creating a PR (branch will be created tho)
file_count: int = 0 # Number of files changes
title: str
body: str
pr_head: str
base: Any
head: Any
assignee: Any = None
id: int = -1
state: str = "open"
html_url: str = "... | class MockPR(BaseModel):
# Used to mock a PR object without creating a PR (branch will be created tho)
file_count: int = 0 # Number of files changes
title: str
body: str
pr_head: str
base: Any
head: Any
assignee: Any = None
id: int = -1
state: str = "open"
html_url: str = "... | # Todo: used to prevent erroring in on_review.py file
pass
| # Todo: used to prevent erroring in on_review.py file
pass
| 10 | 154 | 25 | 179 | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... |
25,301 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/entities.py | 69,71 | 66,84 | from_string | RegexMatchableBaseModel | 71,84 | 71,84 | class RegexMatchableBaseModel(BaseModel):
_regex: ClassVar[str]
@classmethod
def from_string(cls: Type[Self], string: str, **kwargs) -> Self:
FILL_FUNC_BODY | class RegexMatchableBaseModel(BaseModel):
_regex: ClassVar[str]
@classmethod
def from_string(cls: Type[Self], string: str, **kwargs) -> Self:
FILL_FUNC_BODY | # match = re.search(file_regex, string, re.DOTALL)
match = re.search(cls._regex, string, re.DOTALL)
if match is None:
logger.warning(f"Did not match {string} with pattern {cls._regex}")
raise RegexMatchError("Did not match")
return cls(
**{k: (v if v e... | # match = re.search(file_regex, string, re.DOTALL)
match = re.search(cls._regex, string, re.DOTALL)
if match is None:
logger.warning(f"Did not match {string} with pattern {cls._regex}")
raise RegexMatchError("Did not match")
return cls(
**{k: (v if v e... | 59 | 62 | 180 | 242 | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... |
25,302 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/entities.py | 438,439 | 354,469 | get_slack_link | Snippet | 439,443 | 439,443 | class Snippet(BaseModel):
# pylint: disable=E1101
"""
Start and end refer to line numbers
"""
content: str = Field(repr=False)
start: int
end: int
file_path: str
score: float = 0.0 # TODO: migrate all usages to use this
def __eq__(self, other):
if isinstance(other, Snip... | class Snippet(BaseModel):
# pylint: disable=E1101
"""
Start and end refer to line numbers
"""
content: str = Field(repr=False)
start: int
end: int
file_path: str
score: float = 0.0 # TODO: migrate all usages to use this
def __eq__(self, other):
if isinstance(other, Snip... | num_lines = self.content.count("\n") + 1
base = commit_id + "/" if commit_id != "main" else ""
return f"<{self.get_url(repo_name, commit_id)}|{base}{self.file_path}#L{max(self.start, 1)}-L{min(self.end, num_lines)}>"
| num_lines = self.content.count("\n") + 1
base = commit_id + "/" if commit_id != "main" else ""
return f"<{self.get_url(repo_name, commit_id)}|{base}{self.file_path}#L{max(self.start, 1)}-L{min(self.end, num_lines)}>"
| 21 | 1,335 | 100 | 1,435 | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... | from __future__ import annotations
import os
import re
import string
from dataclasses import dataclass
from difflib import unified_diff
from typing import Any, ClassVar, Literal, Type, TypeVar
from urllib.parse import quote
from loguru import logger
from pydantic import BaseModel, Field
from sweepai.utils.str_utils ... |
25,303 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/external_searcher.py | 16,17 | 10,47 | extract_summary_from_link | ExternalSearcher | 17,29 | 17,29 | class ExternalSearcher(ChatGPT):
@staticmethod
def extract_links(content: str) -> list[str]:
pattern = r"\b(?:(?:https?|ftp)://|www\.)\S+\b"
return list(set(re.findall(pattern, content)))
def extract_summary_from_link(self, url: str, problem: str) -> str:
FILL_FUNC_BODY @staticmethod
... | class ExternalSearcher(ChatGPT):
@staticmethod
def extract_links(content: str) -> list[str]:
pattern = r"\b(?:(?:https?|ftp)://|www\.)\S+\b"
return list(set(re.findall(pattern, content)))
def extract_summary_from_link(self, url: str, problem: str) -> str:
FILL_FUNC_BODY @staticmethod
... | page_metadata = extract_info(url)
self.messages = [Message(role="system", content=external_search_system_prompt)]
response = self.chat(
external_search_prompt.format(
page_metadata=page_metadata,
problem=problem,
)
)
retur... | page_metadata = extract_info(url)
self.messages = [Message(role="system", content=external_search_system_prompt)]
response = self.chat(
external_search_prompt.format(
page_metadata=page_metadata,
problem=problem,
)
)
retur... | 19 | 318 | 104 | 422 | import re
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.core.prompts import external_search_prompt, external_search_system_prompt
from loguru import logger
from sweepai.utils.html_extractor import extract_info
class ExternalSearcher(ChatGPT):
@staticmethod
def e... | import re
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.core.prompts import external_search_prompt, external_search_system_prompt
from loguru import logger
from sweepai.utils.html_extractor import extract_info
class ExternalSearcher(ChatGPT):
@staticmethod
def e... |
25,304 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/post_merge.py | 65,67 | 60,105 | from_string | IssueTitleAndDescription | 67,105 | 67,105 | class IssueTitleAndDescription(RegexMatchableBaseModel):
changes_required: bool = False
issue_title: str
issue_description: str
@classmethod
def from_string(cls: type["IssueTitleAndDescription"], string: str, **kwargs) -> "IssueTitleAndDescription":
FILL_FUNC_BODY | class IssueTitleAndDescription(RegexMatchableBaseModel):
changes_required: bool = False
issue_title: str
issue_description: str
@classmethod
def from_string(cls: type["IssueTitleAndDescription"], string: str, **kwargs) -> "IssueTitleAndDescription":
FILL_FUNC_BODY | changes_required_pattern = (
r"""<changes_required>(\n)?(?P<changes_required>.*)</changes_required>"""
)
changes_required_match = re.search(changes_required_pattern, string, re.DOTALL)
changes_required = (
changes_required_match.groupdict()["changes_required"].str... | changes_required_pattern = (
r"""<changes_required>(\n)?(?P<changes_required>.*)</changes_required>"""
)
changes_required_match = re.search(changes_required_pattern, string, re.DOTALL)
changes_required = (
changes_required_match.groupdict()["changes_required"].str... | 76 | 87 | 433 | 520 | import re
import traceback
from typing import TypeVar
from sweepai.config.server import DEFAULT_GPT4_MODEL
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
from loguru import logger
system_prompt = """You are a brilliant and meticulous engineer assigned to revie... | import re
import traceback
from typing import TypeVar
from sweepai.config.server import DEFAULT_GPT4_MODEL
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
from loguru import logger
system_prompt = """You are a brilliant and meticulous engineer assigned to revie... |
25,305 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/post_merge.py | 106,107 | 105,137 | check_for_issues | PostMerge | 107,137 | 107,137 | class PostMerge(ChatGPT):
def check_for_issues(self, rule, diff) -> tuple[bool, str, str]:
FILL_FUNC_BODY | class PostMerge(ChatGPT):
def check_for_issues(self, rule, diff) -> tuple[bool, str, str]:
FILL_FUNC_BODY | try:
self.messages = [
Message(
role="system",
content=system_prompt.format(rule=rule),
key="system",
)
]
if self.chat_logger and not self.chat_logger.is_paying_user():
... | try:
self.messages = [
Message(
role="system",
content=system_prompt.format(rule=rule),
key="system",
)
]
if self.chat_logger and not self.chat_logger.is_paying_user():
... | 56 | 45 | 282 | 327 | import re
import traceback
from typing import TypeVar
from sweepai.config.server import DEFAULT_GPT4_MODEL
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
from loguru import logger
system_prompt = """You are a brilliant and meticulous engineer assigned to revie... | import re
import traceback
from typing import TypeVar
from sweepai.config.server import DEFAULT_GPT4_MODEL
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, RegexMatchableBaseModel
from loguru import logger
system_prompt = """You are a brilliant and meticulous engineer assigned to revie... |
25,306 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/pr_reader.py | 51,52 | 35,117 | extract_summary_from_pr_id | PRReader | 52,67 | 52,67 | class PRReader(BaseModel):
repo: Repository
class Config:
arbitrary_types_allowed = True
@staticmethod
def extract_pr_ids(content: str) -> list[str]:
pattern_1 = r" #(?P<pr_id>\d+)"
pattern_2 = (
r"https://github\.com/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/pull/(?P<pr_id>\d+... | class PRReader(BaseModel):
repo: Repository
class Config:
arbitrary_types_allowed = True
@staticmethod
def extract_pr_ids(content: str) -> list[str]:
pattern_1 = r" #(?P<pr_id>\d+)"
pattern_2 = (
r"https://github\.com/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+/pull/(?P<pr_id>\d+... | pr = self.repo.get_pull(int(pr_id))
diff = ""
files = list(islice(pr.get_files(), 51))
for file in files:
path = file.filename
# make sure changes are within allowed directories
if sweep_config and sweep_config.is_file_excluded(path):
c... | pr = self.repo.get_pull(int(pr_id))
diff = ""
files = list(islice(pr.get_files(), 51))
for file in files:
path = file.filename
# make sure changes are within allowed directories
if sweep_config and sweep_config.is_file_excluded(path):
c... | 53 | 897 | 185 | 1,082 | import re
from itertools import islice
from github.Repository import Repository
from pydantic import BaseModel
from loguru import logger
from sweepai.config.client import SweepConfig
summary_format_brief = """# Pull Request #{id_}
## Title: {pr_title}
## Files changed:
{files_touched}
"""
summary_format = """# Pul... | import re
from itertools import islice
from github.Repository import Repository
from pydantic import BaseModel
from loguru import logger
from sweepai.config.client import SweepConfig
summary_format_brief = """# Pull Request #{id_}
## Title: {pr_title}
## Files changed:
{files_touched}
"""
summary_format = """# Pul... |
25,307 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/reflection_utils.py | 349,350 | 348,391 | evaluate_run | EvaluatorAgent | 350,391 | 350,391 | class EvaluatorAgent(ChatGPT):
def evaluate_run(self, problem_statement: str, run_text: str, stored_files: list[str]):
FILL_FUNC_BODY | class EvaluatorAgent(ChatGPT):
def evaluate_run(self, problem_statement: str, run_text: str, stored_files: list[str]):
FILL_FUNC_BODY | self.model = CLAUDE_MODEL
self.messages = [Message(role="system", content=state_eval_prompt)]
formatted_problem_statement = f"This is the task for the contractor to research:\n<task_to_research>\n{problem_statement}\n</task_to_research>"
contractor_stored_files = "\n".join([file for file... | self.model = CLAUDE_MODEL
self.messages = [Message(role="system", content=state_eval_prompt)]
formatted_problem_statement = f"This is the task for the contractor to research:\n<task_to_research>\n{problem_statement}\n</task_to_research>"
contractor_stored_files = "\n".join([file for file... | 157 | 51 | 748 | 799 | import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.utils.diff import generate_diff
response_format = """Respond using the following structured format:
<judgement_on_task>
Provide extensive, highly detailed criteria for evaluating the cont... | import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
from sweepai.utils.diff import generate_diff
response_format = """Respond using the following structured format:
<judgement_on_task>
Provide extensive, highly detailed criteria for evaluating the cont... |
25,309 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/core/repo_parsing_utils.py | 91,92 | 1,162 | file_path_to_chunks | 92,98 | 92,98 | import logging
import multiprocessing
import os
from loguru import logger
from tqdm import tqdm
from sweepai.config.client import SweepConfig
from sweepai.core.entities import Snippet
from sweepai.utils.file_utils import read_file_with_fallback_encodings
from sweepai.utils.utils import Tiktoken, chunk_code
from swee... | import logging
import multiprocessing
import os
from loguru import logger
from tqdm import tqdm
from sweepai.config.client import SweepConfig
from sweepai.core.entities import Snippet
from sweepai.utils.file_utils import read_file_with_fallback_encodings
from sweepai.utils.utils import Tiktoken, chunk_code
from swee... | file_contents = read_file(file_path)
chunks = chunk_code(file_contents, path=file_path)
return chunks
# @file_cache()
| file_contents = read_file(file_path)
chunks = chunk_code(file_contents, path=file_path)
return chunks
# @file_cache()
| 11 | 1,684 | 53 | 1,737 | import logging
import multiprocessing
import os
from loguru import logger
from tqdm import tqdm
from sweepai.config.client import SweepConfig
from sweepai.core.entities import Snippet
from sweepai.utils.file_utils import read_file_with_fallback_encodings
from sweepai.utils.utils import Tiktoken, chunk_code
from swee... | import logging
import multiprocessing
import os
from loguru import logger
from tqdm import tqdm
from sweepai.config.client import SweepConfig
from sweepai.core.entities import Snippet
from sweepai.utils.file_utils import read_file_with_fallback_encodings
from sweepai.utils.utils import Tiktoken, chunk_code
from swee... | |
25,312 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/handlers/on_button_click.py | 23,24 | 1,152 | handle_button_click | 24,85 | 24,85 |
from github.Repository import Repository
from loguru import logger
from sweepai.config.client import (
RESET_FILE,
REVERT_CHANGED_FILES_TITLE,
RULES_LABEL,
RULES_TITLE,
get_blocked_dirs,
)
from sweepai.config.server import MONGODB_URI
from sweepai.core.post_merge import PostMerge
from sweepai.hand... |
from github.Repository import Repository
from loguru import logger
from sweepai.config.client import (
RESET_FILE,
REVERT_CHANGED_FILES_TITLE,
RULES_LABEL,
RULES_TITLE,
get_blocked_dirs,
)
from sweepai.config.server import MONGODB_URI
from sweepai.core.post_merge import PostMerge
from sweepai.hand... | request = IssueCommentRequest(**request_dict)
user_token, gh_client = get_github_client(request_dict["installation"]["id"])
button_list = ButtonList.deserialize(request_dict["comment"]["body"])
selected_buttons = [button.label for button in button_list.get_clicked_buttons()]
repo = gh_client.get_rep... | request = IssueCommentRequest(**request_dict)
user_token, gh_client = get_github_client(request_dict["installation"]["id"])
button_list = ButtonList.deserialize(request_dict["comment"]["body"])
selected_buttons = [button.label for button in button_list.get_clicked_buttons()]
repo = gh_client.get_rep... | 126 | 991 | 685 | 1,676 |
from github.Repository import Repository
from loguru import logger
from sweepai.config.client import (
RESET_FILE,
REVERT_CHANGED_FILES_TITLE,
RULES_LABEL,
RULES_TITLE,
get_blocked_dirs,
)
from sweepai.config.server import MONGODB_URI
from sweepai.core.post_merge import PostMerge
from sweepai.hand... |
from github.Repository import Repository
from loguru import logger
from sweepai.config.client import (
RESET_FILE,
REVERT_CHANGED_FILES_TITLE,
RULES_LABEL,
RULES_TITLE,
get_blocked_dirs,
)
from sweepai.config.server import MONGODB_URI
from sweepai.core.post_merge import PostMerge
from sweepai.hand... | |
25,313 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/handlers/on_button_click_test.py | 6,7 | 1,51 | test_handle_button_click | 7,21 | 7,21 | from unittest.mock import Mock, patch
from sweepai.handlers.on_button_click import handle_button_click
def test_handle_button_click():
FILL_FUNC_BODYdef test_handle_button_click_revert_files():
mock_request_dict = {
"installation": {"id": 1},
"comment": {"body": "test body"},
"repository"... | from unittest.mock import Mock, patch
from sweepai.handlers.on_button_click import handle_button_click
def test_handle_button_click():
FILL_FUNC_BODYdef test_handle_button_click_revert_files():
mock_request_dict = {
"installation": {"id": 1},
"comment": {"body": "test body"},
"repository"... | mock_request_dict = {
"installation": {"id": 1},
"comment": {"body": "test body"},
"repository": {"full_name": "test/repo"},
"issue": {"number": 1},
}
with patch(
"sweepai.handlers.on_button_click.get_github_client"
) as mock_get_github_client:
mock_get_g... | mock_request_dict = {
"installation": {"id": 1},
"comment": {"body": "test body"},
"repository": {"full_name": "test/repo"},
"issue": {"number": 1},
}
with patch(
"sweepai.handlers.on_button_click.get_github_client"
) as mock_get_github_client:
mock_get_g... | 28 | 393 | 151 | 544 | from unittest.mock import Mock, patch
from sweepai.handlers.on_button_click import handle_button_click
def test_handle_button_click():
FILL_FUNC_BODYdef test_handle_button_click_revert_files():
mock_request_dict = {
"installation": {"id": 1},
"comment": {"body": "test body"},
"repository"... | from unittest.mock import Mock, patch
from sweepai.handlers.on_button_click import handle_button_click
def test_handle_button_click():
FILL_FUNC_BODYdef test_handle_button_click_revert_files():
mock_request_dict = {
"installation": {"id": 1},
"comment": {"body": "test body"},
"repository"... | |
25,314 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/handlers/on_check_suite.py | 76,77 | 1,175 | clean_gh_logs | 77,138 | 77,138 | """
This module is responsible for handling the check suite event, called from sweepai/api.py
"""
import io
import re
import time
import zipfile
import requests
from sweepai.config.client import get_gha_enabled
from sweepai.core.entities import PRChangeRequest
from sweepai.logn.cache import file_cache
from sweepai.ut... | """
This module is responsible for handling the check suite event, called from sweepai/api.py
"""
import io
import re
import time
import zipfile
import requests
from sweepai.config.client import get_gha_enabled
from sweepai.core.entities import PRChangeRequest
from sweepai.logn.cache import file_cache
from sweepai.ut... | # Extraction process could be better
MAX_LINES = 500
LINES_TO_KEEP = 100
log_list = logs_str.split("\n")
truncated_logs = [log[log.find(" ") + 1 :] for log in log_list]
logs_str = "\n".join(truncated_logs)
# extract the group and delete everything between group and endgroup
gha_pattern =... | # Extraction process could be better
MAX_LINES = 500
LINES_TO_KEEP = 100
log_list = logs_str.split("\n")
truncated_logs = [log[log.find(" ") + 1 :] for log in log_list]
logs_str = "\n".join(truncated_logs)
# extract the group and delete everything between group and endgroup
gha_pattern =... | 183 | 1,137 | 825 | 1,962 | """
This module is responsible for handling the check suite event, called from sweepai/api.py
"""
import io
import re
import time
import zipfile
import requests
from sweepai.config.client import get_gha_enabled
from sweepai.core.entities import PRChangeRequest
from sweepai.logn.cache import file_cache
from sweepai.ut... | """
This module is responsible for handling the check suite event, called from sweepai/api.py
"""
import io
import re
import time
import zipfile
import requests
from sweepai.config.client import get_gha_enabled
from sweepai.core.entities import PRChangeRequest
from sweepai.logn.cache import file_cache
from sweepai.ut... | |
25,316 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/handlers/on_jira_ticket.py | 27,28 | 1,87 | handle_jira_ticket | 28,87 | 28,87 | import re
from jira import JIRA
from sweepai.handlers.on_ticket import on_ticket
from sweepai.utils.github_utils import get_github_client, get_installation_id
from sweepai.config.server import JIRA_API_TOKEN, JIRA_URL, JIRA_USER_NAME
def extract_repo_name_from_description(description):
repo_full_name = None
p... | import re
from jira import JIRA
from sweepai.handlers.on_ticket import on_ticket
from sweepai.utils.github_utils import get_github_client, get_installation_id
from sweepai.config.server import JIRA_API_TOKEN, JIRA_URL, JIRA_USER_NAME
def extract_repo_name_from_description(description):
repo_full_name = None
p... | # Do something with the JIRA ticket
jira_issue = event["issue"]
# get title, description, comments
title = jira_issue["fields"]["summary"]
description = jira_issue["fields"]["description"]
# comments = issue["fields"]["comment"]["comments"]
# parse github repo from description
# ex: "rep... | # Do something with the JIRA ticket
jira_issue = event["issue"]
# get title, description, comments
title = jira_issue["fields"]["summary"]
description = jira_issue["fields"]["description"]
# comments = issue["fields"]["comment"]["comments"]
# parse github repo from description
# ex: "rep... | 207 | 321 | 760 | 1,081 | import re
from jira import JIRA
from sweepai.handlers.on_ticket import on_ticket
from sweepai.utils.github_utils import get_github_client, get_installation_id
from sweepai.config.server import JIRA_API_TOKEN, JIRA_URL, JIRA_USER_NAME
def extract_repo_name_from_description(description):
repo_full_name = None
p... | import re
from jira import JIRA
from sweepai.handlers.on_ticket import on_ticket
from sweepai.utils.github_utils import get_github_client, get_installation_id
from sweepai.config.server import JIRA_API_TOKEN, JIRA_URL, JIRA_USER_NAME
def extract_repo_name_from_description(description):
repo_full_name = None
p... | |
25,317 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/handlers/on_merge.py | 23,24 | 1,46 | comparison_to_diff | 24,46 | 24,46 | """
This file contains the on_merge handler which is called when a pull request is merged to master.
on_merge is called by sweepai/api.py
"""
from loguru import logger
# change threshold for number of lines changed
CHANGE_BOUNDS = (10, 1500)
# dictionary to map from github repo to the last time a rule was activated
... | """
This file contains the on_merge handler which is called when a pull request is merged to master.
on_merge is called by sweepai/api.py
"""
from loguru import logger
# change threshold for number of lines changed
CHANGE_BOUNDS = (10, 1500)
# dictionary to map from github repo to the last time a rule was activated
... | pr_diffs = []
for file in comparison.files:
diff = file.patch
if (
file.status == "added"
or file.status == "modified"
or file.status == "removed"
):
if any(file.filename.startswith(dir) for dir in blocked_dirs):
continue
... | pr_diffs = []
for file in comparison.files:
diff = file.patch
if (
file.status == "added"
or file.status == "modified"
or file.status == "removed"
):
if any(file.filename.startswith(dir) for dir in blocked_dirs):
continue
... | 65 | 186 | 255 | 441 | """
This file contains the on_merge handler which is called when a pull request is merged to master.
on_merge is called by sweepai/api.py
"""
from loguru import logger
# change threshold for number of lines changed
CHANGE_BOUNDS = (10, 1500)
# dictionary to map from github repo to the last time a rule was activated
... | """
This file contains the on_merge handler which is called when a pull request is merged to master.
on_merge is called by sweepai/api.py
"""
from loguru import logger
# change threshold for number of lines changed
CHANGE_BOUNDS = (10, 1500)
# dictionary to map from github repo to the last time a rule was activated
... | |
25,318 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/handlers/on_review.py | 7,8 | 1,28 | get_pr_diffs | 8,28 | 8,28 | """
Take a PR and provide an AI generated review of the PR.
"""
from sweepai.utils.event_logger import logger
def get_pr_diffs(repo, pr):
FILL_FUNC_BODY | """
Take a PR and provide an AI generated review of the PR.
"""
from sweepai.utils.event_logger import logger
def get_pr_diffs(repo, pr):
FILL_FUNC_BODY | base_sha = pr.base.sha
head_sha = pr.head.sha
comparison = repo.compare(base_sha, head_sha)
file_diffs = comparison.files
pr_diffs = []
for file in file_diffs:
diff = file.patch
if (
file.status == "added"
or file.status == "modified"
or file... | base_sha = pr.base.sha
head_sha = pr.head.sha
comparison = repo.compare(base_sha, head_sha)
file_diffs = comparison.files
pr_diffs = []
for file in file_diffs:
diff = file.patch
if (
file.status == "added"
or file.status == "modified"
or file... | 56 | 55 | 198 | 253 | """
Take a PR and provide an AI generated review of the PR.
"""
from sweepai.utils.event_logger import logger
def get_pr_diffs(repo, pr):
FILL_FUNC_BODY | """
Take a PR and provide an AI generated review of the PR.
"""
from sweepai.utils.event_logger import logger
def get_pr_diffs(repo, pr):
FILL_FUNC_BODY | |
25,321 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/logn/trace_util.py | 5,6 | 1,16 | trace_lines | 6,15 | 6,15 | import linecache
import sys
def trace_lines(frame, event, arg):
FILL_FUNC_BODYsys.settrace(trace_lines)
| import linecache
import sys
def trace_lines(frame, event, arg):
FILL_FUNC_BODYsys.settrace(trace_lines)
| if event == "line":
filename = frame.f_code.co_filename
if "" in filename:
lineno = frame.f_lineno
line = linecache.getline(filename, lineno)
print(f"Executing {filename}:line {lineno}:{line.rstrip()}")
return trace_lines
| if event == "line":
filename = frame.f_code.co_filename
if "" in filename:
lineno = frame.f_lineno
line = linecache.getline(filename, lineno)
print(f"Executing {filename}:line {lineno}:{line.rstrip()}")
return trace_lines
| 23 | 41 | 95 | 136 | import linecache
import sys
def trace_lines(frame, event, arg):
FILL_FUNC_BODYsys.settrace(trace_lines)
| import linecache
import sys
def trace_lines(frame, event, arg):
FILL_FUNC_BODYsys.settrace(trace_lines)
| |
25,322 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/anthropic_client.py | 24,25 | 1,79 | sanitize_anthropic_messages | 25,39 | 25,39 | import copy
import os
from anthropic import Anthropic
from loguru import logger
from openai import OpenAI
from sweepai.config.server import (
DEFAULT_GPT4_MODEL,
OPENAI_API_KEY,
OPENAI_API_TYPE,
PAREA_API_KEY,
)
from parea import Parea
from sweepai.logn.cache import file_cache
parea_client = None
try:... | import copy
import os
from anthropic import Anthropic
from loguru import logger
from openai import OpenAI
from sweepai.config.server import (
DEFAULT_GPT4_MODEL,
OPENAI_API_KEY,
OPENAI_API_TYPE,
PAREA_API_KEY,
)
from parea import Parea
from sweepai.logn.cache import file_cache
parea_client = None
try:... | new_messages = []
for message in messages:
if message["role"] == "system":
message["role"] = "user"
if new_messages and new_messages[-1]["role"] == message["role"]:
new_messages[-1]["content"] += "\n\n" + message["content"].rstrip()
else:
message["cont... | new_messages = []
for message in messages:
if message["role"] == "system":
message["role"] = "user"
if new_messages and new_messages[-1]["role"] == message["role"]:
new_messages[-1]["content"] += "\n\n" + message["content"].rstrip()
else:
message["cont... | 49 | 807 | 171 | 978 | import copy
import os
from anthropic import Anthropic
from loguru import logger
from openai import OpenAI
from sweepai.config.server import (
DEFAULT_GPT4_MODEL,
OPENAI_API_KEY,
OPENAI_API_TYPE,
PAREA_API_KEY,
)
from parea import Parea
from sweepai.logn.cache import file_cache
parea_client = None
try:... | import copy
import os
from anthropic import Anthropic
from loguru import logger
from openai import OpenAI
from sweepai.config.server import (
DEFAULT_GPT4_MODEL,
OPENAI_API_KEY,
OPENAI_API_TYPE,
PAREA_API_KEY,
)
from parea import Parea
from sweepai.logn.cache import file_cache
parea_client = None
try:... | |
25,323 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/anthropic_client.py | 66,67 | 39,79 | parse_role_content_from_response | AnthropicClient | 67,79 | 67,79 | class AnthropicClient:
def __init__(self):
OPENAI_API_TYPE = os.environ.get("OPENAI_API_TYPE", "anthropic")
if OPENAI_API_TYPE != "anthropic":
self.client = OpenAI(api_key=OPENAI_API_KEY, timeout=90)
self.model = DEFAULT_GPT4_MODEL
logger.info(f"Using OpenAI model... | class AnthropicClient:
def __init__(self):
OPENAI_API_TYPE = os.environ.get("OPENAI_API_TYPE", "anthropic")
if OPENAI_API_TYPE != "anthropic":
self.client = OpenAI(api_key=OPENAI_API_KEY, timeout=90)
self.model = DEFAULT_GPT4_MODEL
logger.info(f"Using OpenAI model... | if OPENAI_API_TYPE != "anthropic":
response_message = response.choices[0].message
response_message_dict = response_message.model_dump()
response_contents = response_message_dict.get("content", "")
return response_message_dict['role'], response_contents
els... | if OPENAI_API_TYPE != "anthropic":
response_message = response.choices[0].message
response_message_dict = response_message.model_dump()
response_contents = response_message_dict.get("content", "")
return response_message_dict['role'], response_contents
els... | 35 | 444 | 171 | 615 | import copy
import os
from anthropic import Anthropic
from loguru import logger
from openai import OpenAI
from sweepai.config.server import (
DEFAULT_GPT4_MODEL,
OPENAI_API_KEY,
OPENAI_API_TYPE,
PAREA_API_KEY,
)
from parea import Parea
from sweepai.logn.cache import file_cache
parea_client = None
try:... | import copy
import os
from anthropic import Anthropic
from loguru import logger
from openai import OpenAI
from sweepai.config.server import (
DEFAULT_GPT4_MODEL,
OPENAI_API_KEY,
OPENAI_API_TYPE,
PAREA_API_KEY,
)
from parea import Parea
from sweepai.logn.cache import file_cache
parea_client = None
try:... |
25,324 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/autoimport.py | 28,29 | 1,72 | get_undefined_names | 29,41 | 29,41 | """
Auto imports for Python code.
"""
import os
from io import StringIO
import isort
from importmagic import index
from loguru import logger
from pyflakes.api import check
from pyflakes.reporter import Reporter
def get_module_of_entity(
entity_name: str,
project_name: str,
) -> str | None:
my_index = i... | """
Auto imports for Python code.
"""
import os
from io import StringIO
import isort
from importmagic import index
from loguru import logger
from pyflakes.api import check
from pyflakes.reporter import Reporter
def get_module_of_entity(
entity_name: str,
project_name: str,
) -> str | None:
my_index = i... | output = StringIO()
reporter = Reporter(output, output)
check(code, filename=file_path, reporter=reporter)
undefined_names = []
for line in output.getvalue().splitlines():
if "undefined name" in line:
entity = line.split()[-1].strip("'")
if entity not in undefined_nam... | output = StringIO()
reporter = Reporter(output, output)
check(code, filename=file_path, reporter=reporter)
undefined_names = []
for line in output.getvalue().splitlines():
if "undefined name" in line:
entity = line.split()[-1].strip("'")
if entity not in undefined_nam... | 33 | 504 | 120 | 624 | """
Auto imports for Python code.
"""
import os
from io import StringIO
import isort
from importmagic import index
from loguru import logger
from pyflakes.api import check
from pyflakes.reporter import Reporter
def get_module_of_entity(
entity_name: str,
project_name: str,
) -> str | None:
my_index = i... | """
Auto imports for Python code.
"""
import os
from io import StringIO
import isort
from importmagic import index
from loguru import logger
from pyflakes.api import check
from pyflakes.reporter import Reporter
def get_module_of_entity(
entity_name: str,
project_name: str,
) -> str | None:
my_index = i... | |
25,325 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/buttons.py | 12,13 | 1,98 | create_action_buttons | 14,18 | 13,18 | import re
from typing import List
from sweepai.web.events import Changes
def create_button(label: str, selected: bool = False) -> str:
"""Create a button for the issue body."""
return f"- [{'x' if selected else ' '}] {label}"
def create_action_buttons(labels: List[str], header="## Actions (click)\n") -> st... | import re
from typing import List
from sweepai.web.events import Changes
def create_button(label: str, selected: bool = False) -> str:
"""Create a button for the issue body."""
return f"- [{'x' if selected else ' '}] {label}"
def create_action_buttons(labels: List[str], header="## Actions (click)\n") -> st... | buttons = "\n".join(create_button(label) for label in labels)
return header + buttons
| """Create a list of buttons for the issue body."""
buttons = "\n".join(create_button(label) for label in labels)
return header + buttons
| 11 | 921 | 32 | 953 | import re
from typing import List
from sweepai.web.events import Changes
def create_button(label: str, selected: bool = False) -> str:
"""Create a button for the issue body."""
return f"- [{'x' if selected else ' '}] {label}"
def create_action_buttons(labels: List[str], header="## Actions (click)\n") -> st... | import re
from typing import List
from sweepai.web.events import Changes
def create_button(label: str, selected: bool = False) -> str:
"""Create a button for the issue body."""
return f"- [{'x' if selected else ' '}] {label}"
def create_action_buttons(labels: List[str], header="## Actions (click)\n") -> st... | |
25,326 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/buttons.py | 65,67 | 57,78 | deserialize | ButtonList | 67,74 | 67,74 | class ButtonList:
def __init__(self, title: str = "", buttons: List[Button] = None):
self.title = title
self.buttons = buttons or []
def serialize(self) -> str:
return f"{self.title}\n" + "\n".join(str(button) for button in self.buttons)
@classmethod
def deserialize(cls, messag... | class ButtonList:
def __init__(self, title: str = "", buttons: List[Button] = None):
self.title = title
self.buttons = buttons or []
def serialize(self) -> str:
return f"{self.title}\n" + "\n".join(str(button) for button in self.buttons)
@classmethod
def deserialize(cls, messag... | lines = message.split("\n")
title = lines[0]
button_pattern = r"- \[(?P<state>[ x])\] (?P<label>.+)"
matches = re.findall(button_pattern, message)
buttons = [Button(label, state == "x") for state, label in matches]
return cls(title, buttons)
| lines = message.split("\n")
title = lines[0]
button_pattern = r"- \[(?P<state>[ x])\] (?P<label>.+)"
matches = re.findall(button_pattern, message)
buttons = [Button(label, state == "x") for state, label in matches]
return cls(title, buttons)
| 30 | 154 | 100 | 254 | import re
from typing import List
from sweepai.web.events import Changes
def create_button(label: str, selected: bool = False) -> str:
"""Create a button for the issue body."""
return f"- [{'x' if selected else ' '}] {label}"
def create_action_buttons(labels: List[str], header="## Actions (click)\n") -> st... | import re
from typing import List
from sweepai.web.events import Changes
def create_button(label: str, selected: bool = False) -> str:
"""Create a button for the issue body."""
return f"- [{'x' if selected else ' '}] {label}"
def create_action_buttons(labels: List[str], header="## Actions (click)\n") -> st... |
25,327 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/buttons_test.py | 20,21 | 15,53 | test_create_action_buttons | TestButtons | 21,25 | 21,25 | class TestButtons(unittest.TestCase):
def test_create_button(self):
self.assertEqual(create_button("Test", False), "- [ ] Test")
self.assertEqual(create_button("Test", True), "- [x] Test")
def test_create_action_buttons(self):
FILL_FUNC_BODY def test_get_toggled_state(self):
changes_... | class TestButtons(unittest.TestCase):
def test_create_button(self):
self.assertEqual(create_button("Test", False), "- [ ] Test")
self.assertEqual(create_button("Test", True), "- [x] Test")
def test_create_action_buttons(self):
FILL_FUNC_BODY def test_get_toggled_state(self):
changes_... | labels = ["Test1", "Test2"]
expected_output = "## Actions (click)\n- [ ] Test1\n- [ ] Test2"
self.assertEqual(create_action_buttons(labels), expected_output)
| labels = ["Test1", "Test2"]
expected_output = "## Actions (click)\n- [ ] Test1\n- [ ] Test2"
self.assertEqual(create_action_buttons(labels), expected_output)
| 17 | 439 | 63 | 502 | import unittest
import unittest.mock
from sweepai.utils.buttons import (
Button,
ButtonList,
check_button_activated,
check_button_title_match,
create_action_buttons,
create_button,
get_toggled_state,
)
class TestButtons(unittest.TestCase):
def test_create_button(self):
self.as... | import unittest
import unittest.mock
from sweepai.utils.buttons import (
Button,
ButtonList,
check_button_activated,
check_button_title_match,
create_action_buttons,
create_button,
get_toggled_state,
)
class TestButtons(unittest.TestCase):
def test_create_button(self):
self.as... |
25,328 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/chat_logger.py | 84,85 | 22,189 | _add_successful_ticket | ChatLogger | 85,112 | 85,112 | class ChatLogger(BaseModel):
data: dict
chat_collection: Any = None
ticket_collection: Any = None
_ticket_count_cache = {}
_user_field_cache = {}
expiration: datetime = None
index: int = 0
current_date: str = Field(
default_factory=lambda: datetime.utcnow().strftime("%m/%Y/%d")
... | class ChatLogger(BaseModel):
data: dict
chat_collection: Any = None
ticket_collection: Any = None
_ticket_count_cache = {}
_user_field_cache = {}
expiration: datetime = None
index: int = 0
current_date: str = Field(
default_factory=lambda: datetime.utcnow().strftime("%m/%Y/%d")
... | if self.ticket_collection is None:
logger.error("Ticket Collection Does Not Exist")
return
username = self.data.get("assignee", self.data["username"])
update_fields = {self.current_month: 1, self.current_date: 1}
if gpt3:
key = f"{self.current_month}... | if self.ticket_collection is None:
logger.error("Ticket Collection Does Not Exist")
return
username = self.data.get("assignee", self.data["username"])
update_fields = {self.current_month: 1, self.current_date: 1}
if gpt3:
key = f"{self.current_month}... | 69 | 1,571 | 316 | 1,887 | from datetime import datetime, timedelta
from threading import Thread
from typing import Any
from loguru import logger
from pydantic import BaseModel, Field
from pymongo import MongoClient
from sweepai.config.server import (
IS_SELF_HOSTED,
MONGODB_URI,
)
from sweepai.global_threads import global_threads
glo... | from datetime import datetime, timedelta
from threading import Thread
from typing import Any
from loguru import logger
from pydantic import BaseModel, Field
from pymongo import MongoClient
from sweepai.config.server import (
IS_SELF_HOSTED,
MONGODB_URI,
)
from sweepai.global_threads import global_threads
glo... |
25,330 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/code_tree.py | 24,25 | 9,139 | get_path_to_line | CodeTree | 25,48 | 25,48 | class CodeTree(BaseModel):
code: str
language: str
tree: Tree
class Config:
arbitrary_types_allowed = True
@classmethod
def from_code(cls, code: str, language: str = "python"):
parser = Parser()
parser.set_language(tree_sitter_languages.get_language(language))
t... | class CodeTree(BaseModel):
code: str
language: str
tree: Tree
class Config:
arbitrary_types_allowed = True
@classmethod
def from_code(cls, code: str, language: str = "python"):
parser = Parser()
parser.set_language(tree_sitter_languages.get_language(language))
t... | if max_line == -1:
max_line = min_line
children: list[Node] = self.tree.root_node.children
path: list[Node] = [self.tree.root_node]
while children:
next_children = []
for child in children:
start_line, _ = child.start_point
... | if max_line == -1:
max_line = min_line
children: list[Node] = self.tree.root_node.children
path: list[Node] = [self.tree.root_node]
while children:
next_children = []
for child in children:
start_line, _ = child.start_point
... | 56 | 1,196 | 212 | 1,408 | import ast
import re
import tree_sitter_languages
from pydantic import BaseModel
from tree_sitter import Node, Parser, Tree
class CodeTree(BaseModel):
code: str
language: str
tree: Tree
class Config:
arbitrary_types_allowed = True
@classmethod
def from_code(cls, code: str, language:... | import ast
import re
import tree_sitter_languages
from pydantic import BaseModel
from tree_sitter import Node, Parser, Tree
class CodeTree(BaseModel):
code: str
language: str
tree: Tree
class Config:
arbitrary_types_allowed = True
@classmethod
def from_code(cls, code: str, language:... |
25,331 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/code_tree_test.py | 7,8 | 6,32 | test_get_lines_surrounding | TestCodeTree | 8,32 | 8,32 | class TestCodeTree(unittest.TestCase):
def test_get_lines_surrounding(self):
FILL_FUNC_BODY | class TestCodeTree(unittest.TestCase):
def test_get_lines_surrounding(self):
FILL_FUNC_BODY | code = """import math
def square_root(x):
if x < 0:
raise ValueError("Negative value")
print(
"hello world"
)
return math.sqrt(x)
print(square_root(4))
"""
tree = CodeTree.from_code(code)
# Line inside the 'import' statement
result = tree.get_lines_surr... | code = """import math
def square_root(x):
if x < 0:
raise ValueError("Negative value")
print(
"hello world"
)
return math.sqrt(x)
print(square_root(4))
"""
tree = CodeTree.from_code(code)
# Line inside the 'import' statement
result = tree.get_lines_surr... | 49 | 37 | 196 | 233 | import unittest
from sweepai.utils.code_tree import CodeTree
class TestCodeTree(unittest.TestCase):
def test_get_lines_surrounding(self):
FILL_FUNC_BODYif __name__ == "__main__":
unittest.main()
| import unittest
from sweepai.utils.code_tree import CodeTree
class TestCodeTree(unittest.TestCase):
def test_get_lines_surrounding(self):
FILL_FUNC_BODYif __name__ == "__main__":
unittest.main()
|
25,332 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/cohere_utils.py | 7,14 | 1,22 | cohere_rerank_call | 14,22 | 14,22 |
import cohere
from sweepai.config.server import COHERE_API_KEY
from sweepai.logn.cache import file_cache
@file_cache()
def cohere_rerank_call(
query: str,
documents: list[str],
model='rerank-english-v3.0',
**kwargs,
):
FILL_FUNC_BODY |
import cohere
from sweepai.config.server import COHERE_API_KEY
from sweepai.logn.cache import file_cache
@file_cache()
def cohere_rerank_call(
query: str,
documents: list[str],
model='rerank-english-v3.0',
**kwargs,
):
FILL_FUNC_BODY | # Cohere API call with caching
co = cohere.Client(COHERE_API_KEY)
return co.rerank(
model=model,
query=query,
documents=documents,
**kwargs
) | # Cohere API call with caching
co = cohere.Client(COHERE_API_KEY)
return co.rerank(
model=model,
query=query,
documents=documents,
**kwargs
) | 16 | 98 | 67 | 165 |
import cohere
from sweepai.config.server import COHERE_API_KEY
from sweepai.logn.cache import file_cache
@file_cache()
def cohere_rerank_call(
query: str,
documents: list[str],
model='rerank-english-v3.0',
**kwargs,
):
FILL_FUNC_BODY |
import cohere
from sweepai.config.server import COHERE_API_KEY
from sweepai.logn.cache import file_cache
@file_cache()
def cohere_rerank_call(
query: str,
documents: list[str],
model='rerank-english-v3.0',
**kwargs,
):
FILL_FUNC_BODY | |
25,333 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/comment_utils.py | 5,6 | 1,25 | check_comments_presence | 6,25 | 6,25 | import os
import re
def check_comments_presence(file_path: str, new_code: str) -> bool:
FILL_FUNC_BODY | import os
import re
def check_comments_presence(file_path: str, new_code: str) -> bool:
FILL_FUNC_BODY | _, file_extension = os.path.splitext(file_path)
comment_patterns = {
".py": "#",
".js": "//",
".ts": "//",
".jsx": "//",
".tsx": "//",
".java": "//",
".c": "/*",
".cpp": "//",
".cs": "//",
".php": "//",
".swift": "//",
... | _, file_extension = os.path.splitext(file_path)
comment_patterns = {
".py": "#",
".js": "//",
".ts": "//",
".jsx": "//",
".tsx": "//",
".java": "//",
".c": "/*",
".cpp": "//",
".cs": "//",
".php": "//",
".swift": "//",
... | 46 | 43 | 199 | 242 | import os
import re
def check_comments_presence(file_path: str, new_code: str) -> bool:
FILL_FUNC_BODY | import os
import re
def check_comments_presence(file_path: str, new_code: str) -> bool:
FILL_FUNC_BODY | |
25,334 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/comment_utils_test.py | 7,8 | 6,37 | test_check_comments_presence | TestCommentUtils | 8,37 | 8,37 | class TestCommentUtils(unittest.TestCase):
def test_check_comments_presence(self):
FILL_FUNC_BODY | class TestCommentUtils(unittest.TestCase):
def test_check_comments_presence(self):
FILL_FUNC_BODY | # Test Python file with a comment
self.assertEqual(
check_comments_presence("test.py", "# This is a comment"), True
)
# Test Python file without a comment
self.assertEqual(
check_comments_presence("test.py", 'print("Hello, World!")'), False
)
... | # Test Python file with a comment
self.assertEqual(
check_comments_presence("test.py", "# This is a comment"), True
)
# Test Python file without a comment
self.assertEqual(
check_comments_presence("test.py", 'print("Hello, World!")'), False
)
... | 87 | 36 | 273 | 309 | import unittest
from sweepai.utils.comment_utils import check_comments_presence
class TestCommentUtils(unittest.TestCase):
def test_check_comments_presence(self):
FILL_FUNC_BODYif __name__ == "__main__":
unittest.main()
| import unittest
from sweepai.utils.comment_utils import check_comments_presence
class TestCommentUtils(unittest.TestCase):
def test_check_comments_presence(self):
FILL_FUNC_BODYif __name__ == "__main__":
unittest.main()
|
25,335 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/convert_openai_anthropic.py | 6,7 | 1,131 | convert_openai_function_to_anthropic_prompt | 7,35 | 7,35 | from __future__ import annotations
from dataclasses import dataclass
import re
def convert_openai_function_to_anthropic_prompt(function: dict) -> str:
FILL_FUNC_BODYdef convert_all_functions(functions: list) -> str:
# convert all openai functions to print anthropic prompt
for function in functions:
pr... | from __future__ import annotations
from dataclasses import dataclass
import re
def convert_openai_function_to_anthropic_prompt(function: dict) -> str:
FILL_FUNC_BODYdef convert_all_functions(functions: list) -> str:
# convert all openai functions to print anthropic prompt
for function in functions:
pr... | unformatted_prompt = """<tool_description>
<tool_name>{tool_name}</tool_name>
<description>
{description}
</description>
<parameters>
{parameters}
</parameters>
</tool_description>"""
unformatted_parameter = """<parameter>
<name>{parameter_name}</name>
<type>{parameter_type}</type>
<description>{parameter_descr... | unformatted_prompt = """<tool_description>
<tool_name>{tool_name}</tool_name>
<description>
{description}
</description>
<parameters>
{parameters}
</parameters>
</tool_description>"""
unformatted_parameter = """<parameter>
<name>{parameter_name}</name>
<type>{parameter_type}</type>
<description>{parameter_descr... | 37 | 1,603 | 282 | 1,885 | from __future__ import annotations
from dataclasses import dataclass
import re
def convert_openai_function_to_anthropic_prompt(function: dict) -> str:
FILL_FUNC_BODYdef convert_all_functions(functions: list) -> str:
# convert all openai functions to print anthropic prompt
for function in functions:
pr... | from __future__ import annotations
from dataclasses import dataclass
import re
def convert_openai_function_to_anthropic_prompt(function: dict) -> str:
FILL_FUNC_BODYdef convert_all_functions(functions: list) -> str:
# convert all openai functions to print anthropic prompt
for function in functions:
pr... | |
25,336 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/convert_openai_anthropic.py | 55,57 | 40,88 | mock_function_calls_from_string | AnthropicFunctionCall | 57,88 | 57,88 | @dataclass
class AnthropicFunctionCall:
function_name: str
function_parameters: dict[str, str]
def to_string(self) -> str:
function_call_string = "<invoke>\n"
function_call_string += f"<tool_name>{self.function_name}</tool_name>\n"
function_call_string += "<parameters>\n"
fo... | @dataclass
class AnthropicFunctionCall:
function_name: str
function_parameters: dict[str, str]
def to_string(self) -> str:
function_call_string = "<invoke>\n"
function_call_string += f"<tool_name>{self.function_name}</tool_name>\n"
function_call_string += "<parameters>\n"
fo... | function_calls = []
# Regular expression patterns
function_name_pattern = r'<tool_name>(.*?)</tool_name>'
parameters_pattern = r'<parameters>(.*?)</parameters>'
parameter_pattern = r'<(.*?)>(.*?)<\/\1>'
# Extract function calls
function_call_matches = re... | function_calls = []
# Regular expression patterns
function_name_pattern = r'<tool_name>(.*?)</tool_name>'
parameters_pattern = r'<parameters>(.*?)</parameters>'
parameter_pattern = r'<(.*?)>(.*?)<\/\1>'
# Extract function calls
function_call_matches = re... | 98 | 247 | 427 | 674 | from __future__ import annotations
from dataclasses import dataclass
import re
def convert_openai_function_to_anthropic_prompt(function: dict) -> str:
unformatted_prompt = """<tool_description>
<tool_name>{tool_name}</tool_name>
<description>
{description}
</description>
<parameters>
{parameters}
</parameters>
</... | from __future__ import annotations
from dataclasses import dataclass
import re
def convert_openai_function_to_anthropic_prompt(function: dict) -> str:
unformatted_prompt = """<tool_description>
<tool_name>{tool_name}</tool_name>
<description>
{description}
</description>
<parameters>
{parameters}
</parameters>
</... |
25,337 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/diff_test.py | 32,33 | 13,85 | test_revert_whitespace_changes_non_whitespace_changes | TestDiff | 33,41 | 33,41 | class TestDiff(unittest.TestCase):
def test_revert_whitespace_changes(self):
original_file_str = " line1\n line2\n line3"
modified_file_str = "line1\n line2\n line3"
expected_output = " line1\n line2\n line3"
self.assertEqual(
revert_whitespace_changes(original_... | class TestDiff(unittest.TestCase):
def test_revert_whitespace_changes(self):
original_file_str = " line1\n line2\n line3"
modified_file_str = "line1\n line2\n line3"
expected_output = " line1\n line2\n line3"
self.assertEqual(
revert_whitespace_changes(original_... | original_file_str = "line1\nline2\nline3"
modified_file_str = "line4\nline5\nline6"
expected_output = "line1\nline2\nline3"
self.assertEqual(
revert_whitespace_changes(original_file_str, modified_file_str),
expected_output,
)
| original_file_str = "line1\nline2\nline3"
modified_file_str = "line4\nline5\nline6"
expected_output = "line1\nline2\nline3"
self.assertEqual(
revert_whitespace_changes(original_file_str, modified_file_str),
expected_output,
)
| 14 | 799 | 105 | 904 |
import unittest
from unittest.mock import patch
from sweepai.utils.diff import (
format_contents,
is_markdown,
match_string,
revert_whitespace_changes,
)
class TestDiff(unittest.TestCase):
def test_revert_whitespace_changes(self):
original_file_str = " line1\n line2\n line3"
m... |
import unittest
from unittest.mock import patch
from sweepai.utils.diff import (
format_contents,
is_markdown,
match_string,
revert_whitespace_changes,
)
class TestDiff(unittest.TestCase):
def test_revert_whitespace_changes(self):
original_file_str = " line1\n line2\n line3"
m... |
25,338 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/docker_utils.py | 7,8 | 1,46 | get_latest_docker_version | 8,37 | 8,37 | import urllib
from datetime import datetime, timedelta, timezone
import requests
def get_latest_docker_version():
FILL_FUNC_BODYdef get_docker_badge():
try:
docker_update_duration = get_latest_docker_version()
encoded_duration = urllib.parse.quote(docker_update_duration)
badge_url = f"htt... | import urllib
from datetime import datetime, timedelta, timezone
import requests
def get_latest_docker_version():
FILL_FUNC_BODYdef get_docker_badge():
try:
docker_update_duration = get_latest_docker_version()
encoded_duration = urllib.parse.quote(docker_update_duration)
badge_url = f"htt... | def humanize_time(delta):
seconds = delta.total_seconds()
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
if days > 0:
return f"{int(days)} days ago"
elif hours > 0:
return f"{int(hour... | def humanize_time(delta):
seconds = delta.total_seconds()
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
if days > 0:
return f"{int(days)} days ago"
elif hours > 0:
return f"{int(hour... | 98 | 178 | 400 | 578 | import urllib
from datetime import datetime, timedelta, timezone
import requests
def get_latest_docker_version():
FILL_FUNC_BODYdef get_docker_badge():
try:
docker_update_duration = get_latest_docker_version()
encoded_duration = urllib.parse.quote(docker_update_duration)
badge_url = f"htt... | import urllib
from datetime import datetime, timedelta, timezone
import requests
def get_latest_docker_version():
FILL_FUNC_BODYdef get_docker_badge():
try:
docker_update_duration = get_latest_docker_version()
encoded_duration = urllib.parse.quote(docker_update_duration)
badge_url = f"htt... | |
25,339 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/docker_utils_test.py | 7,8 | 6,13 | test_get_latest_docker_version | TestDockerUtils | 8,13 | 8,13 | class TestDockerUtils(unittest.TestCase):
def test_get_latest_docker_version(self):
FILL_FUNC_BODY | class TestDockerUtils(unittest.TestCase):
def test_get_latest_docker_version(self):
FILL_FUNC_BODY | result = get_latest_docker_version()
self.assertIsInstance(result, str)
self.assertRegex(result, r"\d+ (days|hours|minutes|seconds) ago|just now")
| result = get_latest_docker_version()
self.assertIsInstance(result, str)
self.assertRegex(result, r"\d+ (days|hours|minutes|seconds) ago|just now")
| 10 | 38 | 61 | 99 | import unittest
from sweepai.utils.docker_utils import get_latest_docker_version
class TestDockerUtils(unittest.TestCase):
def test_get_latest_docker_version(self):
FILL_FUNC_BODYif __name__ == "__main__":
unittest.main()
| import unittest
from sweepai.utils.docker_utils import get_latest_docker_version
class TestDockerUtils(unittest.TestCase):
def test_get_latest_docker_version(self):
FILL_FUNC_BODYif __name__ == "__main__":
unittest.main()
|
25,340 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/event_logger.py | 44,45 | 1,92 | loki_sink | 45,89 | 45,89 | import json
from dataclasses import dataclass
from datetime import datetime # Correctly import the datetime class
import requests
from loguru import logger
from sweepai.config.server import ENV, LOKI_URL, POSTHOG_API_KEY
@dataclass
class PosthogClient:
"""
Official Posthog API client has a thread leakage, ... | import json
from dataclasses import dataclass
from datetime import datetime # Correctly import the datetime class
import requests
from loguru import logger
from sweepai.config.server import ENV, LOKI_URL, POSTHOG_API_KEY
@dataclass
class PosthogClient:
"""
Official Posthog API client has a thread leakage, ... | try:
record = message.record
extras = {
**record["extra"],
"level": record["level"].name,
"file": record["file"].path,
"line": record["line"],
}
message = (
f"{record['time'].isoformat()} {record['level'].name}:{record['fi... | try:
record = message.record
extras = {
**record["extra"],
"level": record["level"].name,
"file": record["file"].path,
"line": record["line"],
}
message = (
f"{record['time'].isoformat()} {record['level'].name}:{record['fi... | 93 | 406 | 428 | 834 | import json
from dataclasses import dataclass
from datetime import datetime # Correctly import the datetime class
import requests
from loguru import logger
from sweepai.config.server import ENV, LOKI_URL, POSTHOG_API_KEY
@dataclass
class PosthogClient:
"""
Official Posthog API client has a thread leakage, ... | import json
from dataclasses import dataclass
from datetime import datetime # Correctly import the datetime class
import requests
from loguru import logger
from sweepai.config.server import ENV, LOKI_URL, POSTHOG_API_KEY
@dataclass
class PosthogClient:
"""
Official Posthog API client has a thread leakage, ... | |
25,341 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/event_logger.py | 19,26 | 11,41 | capture | PosthogClient | 26,41 | 26,41 | @dataclass
class PosthogClient:
"""
Official Posthog API client has a thread leakage, so we are using a custom client.
"""
API_KEY: str | None = None
def capture(
self,
distinct_id: str | None = None,
event: str | None = None,
properties: dict[str, str] | None = Non... | @dataclass
class PosthogClient:
"""
Official Posthog API client has a thread leakage, so we are using a custom client.
"""
API_KEY: str | None = None
def capture(
self,
distinct_id: str | None = None,
event: str | None = None,
properties: dict[str, str] | None = Non... | if self.API_KEY is None:
return
url = "https://app.posthog.com/capture/"
headers = {"Content-Type": "application/json"}
payload = {
"api_key": self.API_KEY,
"event": event,
"properties": {"distinct_id": distinct_id, **properties},
... | if self.API_KEY is None:
return
url = "https://app.posthog.com/capture/"
headers = {"Content-Type": "application/json"}
payload = {
"api_key": self.API_KEY,
"event": event,
"properties": {"distinct_id": distinct_id, **properties},
... | 42 | 118 | 168 | 286 | import json
from dataclasses import dataclass
from datetime import datetime # Correctly import the datetime class
import requests
from loguru import logger
from sweepai.config.server import ENV, LOKI_URL, POSTHOG_API_KEY
@dataclass
class PosthogClient:
"""
Official Posthog API client has a thread leakage, ... | import json
from dataclasses import dataclass
from datetime import datetime # Correctly import the datetime class
import requests
from loguru import logger
from sweepai.config.server import ENV, LOKI_URL, POSTHOG_API_KEY
@dataclass
class PosthogClient:
"""
Official Posthog API client has a thread leakage, ... |
25,342 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/file_utils.py | 1,4 | 1,13 | read_file_with_fallback_encodings | 4,13 | 4,13 | def read_file_with_fallback_encodings(
file_path, encodings=["utf-8", "windows-1252", "iso-8859-1"]
):
FILL_FUNC_BODY | def read_file_with_fallback_encodings(
file_path, encodings=["utf-8", "windows-1252", "iso-8859-1"]
):
FILL_FUNC_BODY | for encoding in encodings:
try:
with open(file_path, "r", encoding=encoding) as file:
return file.read()
except UnicodeDecodeError:
continue
raise UnicodeDecodeError(
f"Could not decode {file_path} with any of the specified encodings: {encodings}"
... | for encoding in encodings:
try:
with open(file_path, "r", encoding=encoding) as file:
return file.read()
except UnicodeDecodeError:
continue
raise UnicodeDecodeError(
f"Could not decode {file_path} with any of the specified encodings: {encodings}"
... | 30 | 60 | 98 | 158 | def read_file_with_fallback_encodings(
file_path, encodings=["utf-8", "windows-1252", "iso-8859-1"]
):
FILL_FUNC_BODY | def read_file_with_fallback_encodings(
file_path, encodings=["utf-8", "windows-1252", "iso-8859-1"]
):
FILL_FUNC_BODY | |
25,344 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/fuzzy_diff_test.py | 58,59 | 4,64 | test_fuzzy_matching | TestPatienceFuzzyDiff | 59,64 | 59,64 | class TestPatienceFuzzyDiff(unittest.TestCase):
def test_empty_strings(self):
self.assertEqual(patience_fuzzy_diff("", ""), "")
def test_identical_strings(self):
text = "Line1\nLine2\nLine3"
self.assertEqual(patience_fuzzy_diff(text, text), "")
def test_addition_at_end(self):
... | class TestPatienceFuzzyDiff(unittest.TestCase):
def test_empty_strings(self):
self.assertEqual(patience_fuzzy_diff("", ""), "")
def test_identical_strings(self):
text = "Line1\nLine2\nLine3"
self.assertEqual(patience_fuzzy_diff(text, text), "")
def test_addition_at_end(self):
... | original = "Line1 slightly different\nLine2\nLine3"
modified = "Line1 very different\nLine2\nLine3"
self.assertEqual(patience_fuzzy_diff(original, modified), "- Line1 slightly different\n+ Line1 very different\n Line2\n Line3")
| original = "Line1 slightly different\nLine2\nLine3"
modified = "Line1 very different\nLine2\nLine3"
self.assertEqual(patience_fuzzy_diff(original, modified), "- Line1 slightly different\n+ Line1 very different\n Line2\n Line3")
| 21 | 866 | 85 | 951 | import unittest
from sweepai.utils.fuzzy_diff import patience_fuzzy_diff
class TestPatienceFuzzyDiff(unittest.TestCase):
def test_empty_strings(self):
self.assertEqual(patience_fuzzy_diff("", ""), "")
def test_identical_strings(self):
text = "Line1\nLine2\nLine3"
self.assertEqual(pati... | import unittest
from sweepai.utils.fuzzy_diff import patience_fuzzy_diff
class TestPatienceFuzzyDiff(unittest.TestCase):
def test_empty_strings(self):
self.assertEqual(patience_fuzzy_diff("", ""), "")
def test_identical_strings(self):
text = "Line1\nLine2\nLine3"
self.assertEqual(pati... |
25,347 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/github_utils.py | 541,543 | 507,555 | git_repo | MockClonedRepo | 543,545 | 543,545 | @dataclass
class MockClonedRepo(ClonedRepo):
_repo_dir: str = ""
git_repo: git.Repo | None = None
def __init__(
self,
_repo_dir: str,
repo_full_name: str,
installation_id: str = "",
branch: str | None = None,
token: str | None = None,
repo: Any | None... | @dataclass
class MockClonedRepo(ClonedRepo):
_repo_dir: str = ""
git_repo: git.Repo | None = None
def __init__(
self,
_repo_dir: str,
repo_full_name: str,
installation_id: str = "",
branch: str | None = None,
token: str | None = None,
repo: Any | None... | return git.Repo(self.repo_dir)
| return git.Repo(self.repo_dir)
| 2 | 350 | 17 | 367 | import copy
import datetime
import difflib
import hashlib
import json
import os
import re
import shutil
import subprocess
import tempfile
import time
import traceback
from dataclasses import dataclass
from functools import cached_property
from typing import Any
import git
import requests
from github import Github, Pul... | import copy
import datetime
import difflib
import hashlib
import json
import os
import re
import shutil
import subprocess
import tempfile
import time
import traceback
from dataclasses import dataclass
from functools import cached_property
from typing import Any
import git
import requests
from github import Github, Pul... |
25,348 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/github_utils.py | 578,580 | 555,604 | copy_from_cloned_repo | TemporarilyCopiedClonedRepo | 580,596 | 580,596 | @dataclass
class TemporarilyCopiedClonedRepo(MockClonedRepo):
tmp_dir: tempfile.TemporaryDirectory | None = None
def __init__(
self,
_repo_dir: str,
tmp_dir: tempfile.TemporaryDirectory,
repo_full_name: str,
installation_id: str = "",
branch: str | None = None,
... | @dataclass
class TemporarilyCopiedClonedRepo(MockClonedRepo):
tmp_dir: tempfile.TemporaryDirectory | None = None
def __init__(
self,
_repo_dir: str,
tmp_dir: tempfile.TemporaryDirectory,
repo_full_name: str,
installation_id: str = "",
branch: str | None = None,
... | temp_dir = tempfile.TemporaryDirectory()
new_dir = temp_dir.name + "/" + cloned_repo.repo_full_name.split("/")[1]
print("Copying...")
shutil.copytree(cloned_repo.repo_dir, new_dir)
print("Done copying.")
return cls(
_repo_dir=new_dir,
tmp_dir=temp_... | temp_dir = tempfile.TemporaryDirectory()
new_dir = temp_dir.name + "/" + cloned_repo.repo_full_name.split("/")[1]
print("Copying...")
shutil.copytree(cloned_repo.repo_dir, new_dir)
print("Done copying.")
return cls(
_repo_dir=new_dir,
tmp_dir=temp_... | 26 | 325 | 201 | 526 | import copy
import datetime
import difflib
import hashlib
import json
import os
import re
import shutil
import subprocess
import tempfile
import time
import traceback
from dataclasses import dataclass
from functools import cached_property
from typing import Any
import git
import requests
from github import Github, Pul... | import copy
import datetime
import difflib
import hashlib
import json
import os
import re
import shutil
import subprocess
import tempfile
import time
import traceback
from dataclasses import dataclass
from functools import cached_property
from typing import Any
import git
import requests
from github import Github, Pul... |
25,349 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/github_utils_test.py | 28,30 | 7,62 | test_list_directory_tree | TestClonedRepo | 30,34 | 30,34 | @unittest.skip("Fails")
class TestClonedRepo(unittest.TestCase):
def setUp(self):
self.repo_full_name = "sweepai/sweep"
self.installation_id = "12345"
self.branch = "main"
self.token = "mock_token"
self.cloned_repo = ClonedRepo(
repo_full_name=self.repo_full_name,... | @unittest.skip("Fails")
class TestClonedRepo(unittest.TestCase):
def setUp(self):
self.repo_full_name = "sweepai/sweep"
self.installation_id = "12345"
self.branch = "main"
self.token = "mock_token"
self.cloned_repo = ClonedRepo(
repo_full_name=self.repo_full_name,... | mock_listdir.return_value = ["file1", "file2"]
tree, dir_obj = self.cloned_repo.list_directory_tree()
self.assertEqual(tree.count("\n"), 2)
| mock_listdir.return_value = ["file1", "file2"]
tree, dir_obj = self.cloned_repo.list_directory_tree()
self.assertEqual(tree.count("\n"), 2)
| 10 | 706 | 60 | 766 | import unittest
from unittest.mock import Mock, patch
from sweepai.utils.github_utils import ClonedRepo
@unittest.skip("Fails")
class TestClonedRepo(unittest.TestCase):
def setUp(self):
self.repo_full_name = "sweepai/sweep"
self.installation_id = "12345"
self.branch = "main"
self.... | import unittest
from unittest.mock import Mock, patch
from sweepai.utils.github_utils import ClonedRepo
@unittest.skip("Fails")
class TestClonedRepo(unittest.TestCase):
def setUp(self):
self.repo_full_name = "sweepai/sweep"
self.installation_id = "12345"
self.branch = "main"
self.... |
25,350 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/hash.py | 4,5 | 1,6 | hash_sha256 | 5,6 | 5,6 | import hashlib
def hash_sha256(text: str):
FILL_FUNC_BODY | import hashlib
def hash_sha256(text: str):
FILL_FUNC_BODY | return hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest()
| return hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest()
| 3 | 29 | 28 | 57 | import hashlib
def hash_sha256(text: str):
FILL_FUNC_BODY | import hashlib
def hash_sha256(text: str):
FILL_FUNC_BODY | |
25,351 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/html_extractor.py | 9,10 | 1,65 | parse_html | 10,48 | 10,48 | import re
import requests
from bs4 import BeautifulSoup
# from llama_index import download_loader
def parse_html(html):
FILL_FUNC_BODYdef download_html(url: str) -> str:
# SimpleWebPageReader = download_loader("SimpleWebPageReader")
# loader = SimpleWebPageReader()
# document, *_ = loader.load_data(urls... | import re
import requests
from bs4 import BeautifulSoup
# from llama_index import download_loader
def parse_html(html):
FILL_FUNC_BODYdef download_html(url: str) -> str:
# SimpleWebPageReader = download_loader("SimpleWebPageReader")
# loader = SimpleWebPageReader()
# document, *_ = loader.load_data(urls... | soup = BeautifulSoup(html)
meta_properties = [
"og:description",
"og:site_name",
"og:title",
"og:type",
"og:url",
]
meta = {}
for property_name in meta_properties:
try:
tag = soup.find("meta", property=property_name)
if tag:
... | soup = BeautifulSoup(html)
meta_properties = [
"og:description",
"og:site_name",
"og:title",
"og:type",
"og:url",
]
meta = {}
for property_name in meta_properties:
try:
tag = soup.find("meta", property=property_name)
if tag:
... | 95 | 216 | 378 | 594 | import re
import requests
from bs4 import BeautifulSoup
# from llama_index import download_loader
def parse_html(html):
FILL_FUNC_BODYdef download_html(url: str) -> str:
# SimpleWebPageReader = download_loader("SimpleWebPageReader")
# loader = SimpleWebPageReader()
# document, *_ = loader.load_data(urls... | import re
import requests
from bs4 import BeautifulSoup
# from llama_index import download_loader
def parse_html(html):
FILL_FUNC_BODYdef download_html(url: str) -> str:
# SimpleWebPageReader = download_loader("SimpleWebPageReader")
# loader = SimpleWebPageReader()
# document, *_ = loader.load_data(urls... | |
25,353 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/issue_validator.py | 40,41 | 1,63 | validate_issue | 44,61 | 41,61 | import re
from sweepai.core.chat import ChatGPT
issue_validator_instructions_prompt = """# Instructions
A good issue for Sweep is actionable and it is clear how to resolve it. Here is what Sweep is currently capable of:
- Access to the entire codebase, with a high-quality search engine to find specific code snippets... | import re
from sweepai.core.chat import ChatGPT
issue_validator_instructions_prompt = """# Instructions
A good issue for Sweep is actionable and it is clear how to resolve it. Here is what Sweep is currently capable of:
- Access to the entire codebase, with a high-quality search engine to find specific code snippets... | chat_gpt = ChatGPT.from_system_message_string(
prompt_string=issue_validator_system_prompt,
)
response = chat_gpt.chat_anthropic(
issue_validator_user_prompt.format(
issue=issue
),
model="claude-3-opus-20240229",
temperature=0.0,
)
if "<pass>... | """
Somehow haiku and GPT-4 can't do this consistently.
"""
chat_gpt = ChatGPT.from_system_message_string(
prompt_string=issue_validator_system_prompt,
)
response = chat_gpt.chat_anthropic(
issue_validator_user_prompt.format(
issue=issue
),
model="cla... | 27 | 528 | 195 | 723 | import re
from sweepai.core.chat import ChatGPT
issue_validator_instructions_prompt = """# Instructions
A good issue for Sweep is actionable and it is clear how to resolve it. Here is what Sweep is currently capable of:
- Access to the entire codebase, with a high-quality search engine to find specific code snippets... | import re
from sweepai.core.chat import ChatGPT
issue_validator_instructions_prompt = """# Instructions
A good issue for Sweep is actionable and it is clear how to resolve it. Here is what Sweep is currently capable of:
- Access to the entire codebase, with a high-quality search engine to find specific code snippets... | |
25,354 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/modify_utils.py | 53,54 | 1,100 | manual_code_check | 54,100 | 54,100 | from sweepai.config.client import SweepConfig
# post process rip grep output to be more condensed
def post_process_rg_output(root_directory: str, sweep_config: SweepConfig, output: str):
processed_output = ""
output_lines = output.split("\n")
# empty lines are present at end of output
output_lines = [l... | from sweepai.config.client import SweepConfig
# post process rip grep output to be more condensed
def post_process_rg_output(root_directory: str, sweep_config: SweepConfig, output: str):
processed_output = ""
output_lines = output.split("\n")
# empty lines are present at end of output
output_lines = [l... | code_lines = [line for line in code_snippet.split("\n")]
# special case for single line
if len(code_lines) == 1:
file_lines = file_contents.split("\n")
# check directly
new_code = code_lines[0]
# only continue if it is unique, this will then later fail the uniqueness check
... | code_lines = [line for line in code_snippet.split("\n")]
# special case for single line
if len(code_lines) == 1:
file_lines = file_contents.split("\n")
# check directly
new_code = code_lines[0]
# only continue if it is unique, this will then later fail the uniqueness check
... | 258 | 792 | 652 | 1,444 | from sweepai.config.client import SweepConfig
# post process rip grep output to be more condensed
def post_process_rg_output(root_directory: str, sweep_config: SweepConfig, output: str):
processed_output = ""
output_lines = output.split("\n")
# empty lines are present at end of output
output_lines = [l... | from sweepai.config.client import SweepConfig
# post process rip grep output to be more condensed
def post_process_rg_output(root_directory: str, sweep_config: SweepConfig, output: str):
processed_output = ""
output_lines = output.split("\n")
# empty lines are present at end of output
output_lines = [l... | |
25,355 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/multi_query.py | 78,79 | 1,105 | generate_multi_queries | 79,102 | 79,102 | import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
# TODO: add docs and tests later
system_message = """You are a thorough and meticulous AI assistant helping a user search for relevant files in a codebase to resolve a GitHub issue. The user will provi... | import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
# TODO: add docs and tests later
system_message = """You are a thorough and meticulous AI assistant helping a user search for relevant files in a codebase to resolve a GitHub issue. The user will provi... | chatgpt = ChatGPT(
messages=[
Message(
content=system_message,
role="system",
)
],
)
stripped_input = input_query.strip('\n')
response = chatgpt.chat(
content=f"<github_issue>\n{stripped_input}\n</github_issue>",
mod... | chatgpt = ChatGPT(
messages=[
Message(
content=system_message,
role="system",
)
],
)
stripped_input = input_query.strip('\n')
response = chatgpt.chat(
content=f"<github_issue>\n{stripped_input}\n</github_issue>",
mod... | 55 | 1,277 | 259 | 1,536 | import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
# TODO: add docs and tests later
system_message = """You are a thorough and meticulous AI assistant helping a user search for relevant files in a codebase to resolve a GitHub issue. The user will provi... | import re
from loguru import logger
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message
# TODO: add docs and tests later
system_message = """You are a thorough and meticulous AI assistant helping a user search for relevant files in a codebase to resolve a GitHub issue. The user will provi... | |
25,357 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/openai_listwise_reranker.py | 837,843 | 836,898 | rerank_list_for_query | RerankSnippetsBot | 843,882 | 843,882 | class RerankSnippetsBot(ChatGPT):
def rerank_list_for_query(
self,
user_query,
code_snippets,
prompt_type="default",
):
FILL_FUNC_BODY def format_code_snippets(self, code_snippets: list[Snippet]):
result_str = ""
for idx, snippet in enumerate(code_snippets):
... | class RerankSnippetsBot(ChatGPT):
def rerank_list_for_query(
self,
user_query,
code_snippets,
prompt_type="default",
):
FILL_FUNC_BODY def format_code_snippets(self, code_snippets: list[Snippet]):
result_str = ""
for idx, snippet in enumerate(code_snippets):
... | self.messages = [Message(role="system", content=prompt_mapping[prompt_type])]
# if the regex match fails return the original list
# gpt doesn't add all snippets, we move all of the dropped snippets to the end in the original order
# if we add duplicate snippets, we remove the duplicates
... | self.messages = [Message(role="system", content=prompt_mapping[prompt_type])]
# if the regex match fails return the original list
# gpt doesn't add all snippets, we move all of the dropped snippets to the end in the original order
# if we add duplicate snippets, we remove the duplicates
... | 168 | 256 | 675 | 931 | """This should take a list of snippets and rerank them"""
import re
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, Snippet
from sweepai.logn.cache import file_cache
# use this later
# # Contextual Request Analysis:
# <contextual_request_analysis>
# * Read each code snippet and assign... | """This should take a list of snippets and rerank them"""
import re
from sweepai.core.chat import ChatGPT
from sweepai.core.entities import Message, Snippet
from sweepai.logn.cache import file_cache
# use this later
# # Contextual Request Analysis:
# <contextual_request_analysis>
# * Read each code snippet and assign... |
25,358 | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep | /home/hieuvd/dung_repo/raw/stars_01/sweepai_sweep/sweep/sweepai/utils/openai_proxy_test.py | 27,40 | 9,56 | test_call_openai | TestOpenAIProxyCallOpenai | 40,56 | 40,56 | class TestOpenAIProxyCallOpenai(unittest.TestCase):
@unittest.skip("Breaks")
def setUp(self):
self.proxy = OpenAIProxy()
self.mock_response = MagicMock()
self.mock_response["choices"][0].message.content = "mock content"
self.mock_openai = MagicMock()
type(self.mock_opena... | class TestOpenAIProxyCallOpenai(unittest.TestCase):
@unittest.skip("Breaks")
def setUp(self):
self.proxy = OpenAIProxy()
self.mock_response = MagicMock()
self.mock_response["choices"][0].message.content = "mock content"
self.mock_openai = MagicMock()
type(self.mock_opena... | mock_set_openai_default_api_parameters.return_value = self.mock_response
mock_create_openai_chat_completion.return_value = self.mock_response
mock_openai.return_value = self.mock_openai
mock_logger.return_value = self.mock_logger
mock_random.return_value = self.mock_random
... | mock_set_openai_default_api_parameters.return_value = self.mock_response
mock_create_openai_chat_completion.return_value = self.mock_response
mock_openai.return_value = self.mock_openai
mock_logger.return_value = self.mock_logger
mock_random.return_value = self.mock_random
... | 38 | 453 | 204 | 657 | import unittest
from unittest.mock import MagicMock, PropertyMock, patch
from sweepai.config.server import OPENAI_API_ENGINE_GPT35
from sweepai.utils.openai_proxy import OpenAIProxy
class TestOpenAIProxyCallOpenai(unittest.TestCase):
@unittest.skip("Breaks")
def setUp(self):
self.proxy = OpenAIProxy... | import unittest
from unittest.mock import MagicMock, PropertyMock, patch
from sweepai.config.server import OPENAI_API_ENGINE_GPT35
from sweepai.utils.openai_proxy import OpenAIProxy
class TestOpenAIProxyCallOpenai(unittest.TestCase):
@unittest.skip("Breaks")
def setUp(self):
self.proxy = OpenAIProxy... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.