code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def convert_dir_fs_wav_to_wav(audio_folder, sampling_rate, num_channels): """ This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels. ARGUMENTS: - audio_folder: the path of the folder where the WAVs are stored - sampling_rate: ...
This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels. ARGUMENTS: - audio_folder: the path of the folder where the WAVs are stored - sampling_rate: the sampling rate of the generated WAV files - num_channels: the number ...
convert_dir_fs_wav_to_wav
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioBasicIO.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioBasicIO.py
Apache-2.0
def read_audio_file(input_file): """ This function returns a numpy array that stores the audio samples of a specified WAV of AIFF file """ sampling_rate = 0 signal = np.array([]) if isinstance(input_file, str): extension = os.path.splitext(input_file)[1].lower() if extension...
This function returns a numpy array that stores the audio samples of a specified WAV of AIFF file
read_audio_file
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioBasicIO.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioBasicIO.py
Apache-2.0
def read_aif(path): """ Read audio file with .aif extension """ sampling_rate = -1 signal = np.array([]) try: with aifc.open(path, 'r') as s: nframes = s.getnframes() strsig = s.readframes(nframes) signal = np.fromstring(strsig, np.short).byteswap() ...
Read audio file with .aif extension
read_aif
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioBasicIO.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioBasicIO.py
Apache-2.0
def read_audio_generic(input_file): """ Function to read audio files with the following extensions [".mp3", ".au", ".ogg"], containing PCM (int16 or int32) data """ sampling_rate = -1 signal = np.array([]) try: audiofile = AudioSegment.from_file(input_file) data = np.array([...
Function to read audio files with the following extensions [".mp3", ".au", ".ogg"], containing PCM (int16 or int32) data
read_audio_generic
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioBasicIO.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioBasicIO.py
Apache-2.0
def stereo_to_mono(signal): """ This function converts the input signal (stored in a numpy array) to MONO (if it is STEREO) """ if signal.ndim == 2: if signal.shape[1] == 1: signal = signal.flatten() else: if signal.shape[1] == 2: signal = (si...
This function converts the input signal (stored in a numpy array) to MONO (if it is STEREO)
stereo_to_mono
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioBasicIO.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioBasicIO.py
Apache-2.0
def self_similarity_matrix(feature_vectors): """ This function computes the self-similarity matrix for a sequence of feature vectors. ARGUMENTS: - feature_vectors: a np matrix (nDims x nVectors) whose i-th column corresponds to the i-th feature vector RETURNS: ...
This function computes the self-similarity matrix for a sequence of feature vectors. ARGUMENTS: - feature_vectors: a np matrix (nDims x nVectors) whose i-th column corresponds to the i-th feature vector RETURNS: - sim_matrix: the self-similarity matrix (...
self_similarity_matrix
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def segments_to_labels(start_times, end_times, labels, window): """ This function converts segment endpoints and respective segment labels to fix-sized class labels. ARGUMENTS: - start_times: segment start points (in seconds) - end_times: segment endpoints (in seconds) - labels: ...
This function converts segment endpoints and respective segment labels to fix-sized class labels. ARGUMENTS: - start_times: segment start points (in seconds) - end_times: segment endpoints (in seconds) - labels: segment labels - window: fix-sized window (in seconds) R...
segments_to_labels
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def compute_metrics(confusion_matrix, class_names): """ This function computes the precision, recall and f1 measures, given a confusion matrix """ f1 = [] recall = [] precision = [] n_classes = confusion_matrix.shape[0] if len(class_names) != n_classes: print("Error in comput...
This function computes the precision, recall and f1 measures, given a confusion matrix
compute_metrics
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def read_segmentation_gt(gt_file): """ This function reads a segmentation ground truth file, following a simple CSV format with the following columns: <segment start>,<segment end>,<class label> ARGUMENTS: - gt_file: the path of the CSV segment file RETURNS: - seg_start: a n...
This function reads a segmentation ground truth file, following a simple CSV format with the following columns: <segment start>,<segment end>,<class label> ARGUMENTS: - gt_file: the path of the CSV segment file RETURNS: - seg_start: a np array of segments' start positions ...
read_segmentation_gt
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def plot_segmentation_results(flags_ind, flags_ind_gt, class_names, mt_step, evaluate_only=False): """ This function plots statistics on the classification-segmentation results produced either by the fix-sized supervised method or the HMM method. It also computes the overa...
This function plots statistics on the classification-segmentation results produced either by the fix-sized supervised method or the HMM method. It also computes the overall accuracy achieved by the respective method if ground-truth is available.
plot_segmentation_results
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def train_hmm_compute_statistics(features, labels): """ This function computes the statistics used to train an HMM joint segmentation-classification model using a sequence of sequential features and respective labels ARGUMENTS: - features: a np matrix of feature vectors (numOfDimensions x n_w...
This function computes the statistics used to train an HMM joint segmentation-classification model using a sequence of sequential features and respective labels ARGUMENTS: - features: a np matrix of feature vectors (numOfDimensions x n_wins) - labels: a np array of class indices (n_wins ...
train_hmm_compute_statistics
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def train_hmm_from_file(wav_file, gt_file, hmm_model_name, mid_window, mid_step): """ This function trains a HMM model for segmentation-classification using a single annotated audio file ARGUMENTS: - wav_file: the path of the audio filename - gt_file: the path of the ground trut...
This function trains a HMM model for segmentation-classification using a single annotated audio file ARGUMENTS: - wav_file: the path of the audio filename - gt_file: the path of the ground truth filename (a csv file of the form <segment start in seconds>, ...
train_hmm_from_file
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def train_hmm_from_directory(folder_path, hmm_model_name, mid_window, mid_step): """ This function trains a HMM model for segmentation-classification using a where WAV files and .segment (ground-truth files) are stored ARGUMENTS: - folder_path: the path of the data diretory - hmm_model_nam...
This function trains a HMM model for segmentation-classification using a where WAV files and .segment (ground-truth files) are stored ARGUMENTS: - folder_path: the path of the data diretory - hmm_model_name: the name of the HMM model to be stored - mt_win: mid-term window size ...
train_hmm_from_directory
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def mid_term_file_classification(input_file, model_name, model_type, plot_results=False, gt_file=""): """ This function performs mid-term classification of an audio stream. Towards this end, supervised knowledge is used, i.e. a pre-trained classifier. ARGUMENTS: ...
This function performs mid-term classification of an audio stream. Towards this end, supervised knowledge is used, i.e. a pre-trained classifier. ARGUMENTS: - input_file: path of the input WAV file - model_name: name of the classification model - model_type: ...
mid_term_file_classification
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def speaker_diarization(filename, n_speakers, mid_window=1.0, mid_step=0.1, short_window=0.1, lda_dim=0, plot_res=False): """ ARGUMENTS: - filename: the name of the WAV file to be analyzed - n_speakers the number of speakers (clusters) in ...
ARGUMENTS: - filename: the name of the WAV file to be analyzed - n_speakers the number of speakers (clusters) in the recording (<=0 for unknown) - mid_window (opt) mid-term window size - mid_step (opt) mid-term window step - shor...
speaker_diarization
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def speaker_diarization_evaluation(folder_name, lda_dimensions): """ This function prints the cluster purity and speaker purity for each WAV file stored in a provided directory (.SEGMENT files are needed as ground-truth) ARGUMENTS: - folder_name: the full path of the...
This function prints the cluster purity and speaker purity for each WAV file stored in a provided directory (.SEGMENT files are needed as ground-truth) ARGUMENTS: - folder_name: the full path of the folder where the WAV and segment (ground...
speaker_diarization_evaluation
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def music_thumbnailing(signal, sampling_rate, short_window=1.0, short_step=0.5, thumb_size=10.0, limit_1=0, limit_2=1): """ This function detects instances of the most representative part of a music recording, also called "music thumbnails". A technique similar to the one proposed...
This function detects instances of the most representative part of a music recording, also called "music thumbnails". A technique similar to the one proposed in [1], however a wider set of audio features is used instead of chroma features. In particular the following steps are followed: - Extr...
music_thumbnailing
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioSegmentation.py
Apache-2.0
def classifier_wrapper(classifier, classifier_type, test_sample): """ This function is used as a wrapper to pattern classification. ARGUMENTS: - classifier: a classifier object of type sklearn.svm.SVC or kNN (defined in this library) or sklearn.ensemble. ...
This function is used as a wrapper to pattern classification. ARGUMENTS: - classifier: a classifier object of type sklearn.svm.SVC or kNN (defined in this library) or sklearn.ensemble. RandomForestClassifier or sklearn.ensemble. ...
classifier_wrapper
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def regression_wrapper(model, model_type, test_sample): """ This function is used as a wrapper to pattern classification. ARGUMENTS: - model: regression model - model_type: "svm" or "knn" (TODO) - test_sample: a feature vector (np array) RETURNS: - R:...
This function is used as a wrapper to pattern classification. ARGUMENTS: - model: regression model - model_type: "svm" or "knn" (TODO) - test_sample: a feature vector (np array) RETURNS: - R: regression result (estimated value) EXAMPLE (f...
regression_wrapper
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def train_svm(features, labels, c_param, kernel='linear'): """ Train a multi-class probabilitistic SVM classifier. Note: This function is simply a wrapper to the sklearn functionality for SVM training See function trainSVM_feature() to use a wrapper on both the ...
Train a multi-class probabilitistic SVM classifier. Note: This function is simply a wrapper to the sklearn functionality for SVM training See function trainSVM_feature() to use a wrapper on both the feature extraction and the SVM training (and param...
train_svm
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def train_random_forest(features, labels, n_estimators): """ Train a multi-class random forest classifier. Note: This function is simply a wrapper to the sklearn functionality for model training. See function extract_features_and_train() to use a wrapper on both ...
Train a multi-class random forest classifier. Note: This function is simply a wrapper to the sklearn functionality for model training. See function extract_features_and_train() to use a wrapper on both the feature extraction and the model training (and parameter ...
train_random_forest
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def train_gradient_boosting(features, labels, n_estimators): """ Train a gradient boosting classifier Note: This function is simply a wrapper to the sklearn functionality for model training. See function extract_features_and_train() to use a wrapper on both the ...
Train a gradient boosting classifier Note: This function is simply a wrapper to the sklearn functionality for model training. See function extract_features_and_train() to use a wrapper on both the feature extraction and the model training (and parameter ...
train_gradient_boosting
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def train_extra_trees(features, labels, n_estimators): """ Train an extra tree Note: This function is simply a wrapper to the sklearn functionality for model training. See function extract_features_and_train() to use a wrapper on both the feature extraction and ...
Train an extra tree Note: This function is simply a wrapper to the sklearn functionality for model training. See function extract_features_and_train() to use a wrapper on both the feature extraction and the model training (and parameter tuning) proces...
train_extra_trees
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def extract_features_and_train(paths, mid_window, mid_step, short_window, short_step, classifier_type, model_name, compute_beat=False, train_percentage=0.90, dict_of_ids=None, use_smote=False): ...
This function is used as a wrapper to segment-based audio feature extraction and classifier training. ARGUMENTS: paths: list of paths of directories. Each directory contains a signle audio class whose samples ...
extract_features_and_train
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def feature_extraction_train_regression(folder_name, mid_window, mid_step, short_window, short_step, model_type, model_name, compute_beat=False): """ This function is used as a wrapper to segment-based audio feature extraction a...
This function is used as a wrapper to segment-based audio feature extraction and classifier training. ARGUMENTS: folder_name: path of directory containing the WAV files and Regression CSVs mt_win, mt_step: mid-term window length and step st_win...
feature_extraction_train_regression
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def load_model(model_name, is_regression=False): """ This function loads an SVM model either for classification or training. ARGMUMENTS: - SVMmodel_name: the path of the model to be loaded - is_regression: a flag indigating whereas this model is regressio...
This function loads an SVM model either for classification or training. ARGMUMENTS: - SVMmodel_name: the path of the model to be loaded - is_regression: a flag indigating whereas this model is regression or not
load_model
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def group_split(X, y, train_indeces, test_indeces, split_id): """ This function splits the data in train and test set according to train/test indeces based on LeaveOneGroupOut ARGUMENTS: X: array-like of shape (n_samples, n_features) y: array-like of shape (n_samples,) train_indeces:...
This function splits the data in train and test set according to train/test indeces based on LeaveOneGroupOut ARGUMENTS: X: array-like of shape (n_samples, n_features) y: array-like of shape (n_samples,) train_indeces: The training set indices test_indeces: The testing set indic...
group_split
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def evaluate_classifier(features, class_names, classifier_name, params, parameter_mode, list_of_ids=None, n_exp=-1, train_percentage=0.90, smote=False): """ ARGUMENTS: features: a list ([numOfClasses x 1]) whose elements contain...
ARGUMENTS: features: a list ([numOfClasses x 1]) whose elements containt np matrices of features. Each matrix features[i] of class i is [n_samples x numOfDimensions] class_names: list of class names (strings) classifier_name: svm or knn or ...
evaluate_classifier
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def evaluate_regression(features, labels, n_exp, method_name, params): """ ARGUMENTS: features: np matrices of features [n_samples x numOfDimensions] labels: list of sample labels n_exp: number of cross-validation experiments method_name: "svm" or "randomfores...
ARGUMENTS: features: np matrices of features [n_samples x numOfDimensions] labels: list of sample labels n_exp: number of cross-validation experiments method_name: "svm" or "randomforest" params: list of classifier params to be evaluated RETURNS...
evaluate_regression
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def print_confusion_matrix(cm, class_names): """ This function prints a confusion matrix for a particular classification task. ARGUMENTS: cm: a 2-D np array of the confusion matrix (cm[i,j] is the number of times a sample from class i was clas...
This function prints a confusion matrix for a particular classification task. ARGUMENTS: cm: a 2-D np array of the confusion matrix (cm[i,j] is the number of times a sample from class i was classified in class j) class_names: a list th...
print_confusion_matrix
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def features_to_matrix(features): """ features_to_matrix(features) This function takes a list of feature matrices as argument and returns a single concatenated feature matrix and the respective class labels. ARGUMENTS: - features: a list of feature matrices RETURNS: - f...
features_to_matrix(features) This function takes a list of feature matrices as argument and returns a single concatenated feature matrix and the respective class labels. ARGUMENTS: - features: a list of feature matrices RETURNS: - feature_matrix: a concatenated matrix o...
features_to_matrix
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def compute_class_rec_pre_f1(c_mat): """ Gets recall, precision and f1 PER CLASS, given the confusion matrix :param c_mat: the [n_class x n_class] confusion matrix :return: rec, pre and f1 for each class """ n_class = c_mat.shape[0] rec, pre, f1 = [], [], [] for i in range(n_class): ...
Gets recall, precision and f1 PER CLASS, given the confusion matrix :param c_mat: the [n_class x n_class] confusion matrix :return: rec, pre and f1 for each class
compute_class_rec_pre_f1
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def evaluate_model_for_folders(input_test_folders, model_name, model_type, positive_class, plot=True): """ evaluate_model_for_folders(input_test_folders, model_name, model_type) This function evaluates a model by computing the confusion matrix, the per class performance me...
evaluate_model_for_folders(input_test_folders, model_name, model_type) This function evaluates a model by computing the confusion matrix, the per class performance metrics and by generating a ROC and Precision / Recall diagrams (for a particular class of interest), for a given test dataset. The dat...
evaluate_model_for_folders
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def train_speaker_models(): """ This script is used to train the speaker-related models (NOTE: data paths are hard-coded and NOT included in the library, the models are, however included) import audioTrainTest as aT aT.trainSpeakerModelsScript() """ mt_win = 2.0 mt_step = 2...
This script is used to train the speaker-related models (NOTE: data paths are hard-coded and NOT included in the library, the models are, however included) import audioTrainTest as aT aT.trainSpeakerModelsScript()
train_speaker_models
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioTrainTest.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioTrainTest.py
Apache-2.0
def generateColorMap(): ''' This function generates a 256 jet colormap of HTML-like hex string colors (e.g. FF88AA) ''' Map = cm.jet(np.arange(256)) stringColors = [] for i in range(Map.shape[0]): rgb = (int(255*Map[i][0]), int(255*Map[i][1]), int(255*Map[i][2])) if (sys.vers...
This function generates a 256 jet colormap of HTML-like hex string colors (e.g. FF88AA)
generateColorMap
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioVisualization.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioVisualization.py
Apache-2.0
def text_list_to_colors(names): ''' Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors. ''' # STEP A: compute strings distance between all combnations of strings Dnames = np.zeros( (len(names), len(names)) ) for i in range(len(names))...
Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors.
text_list_to_colors
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioVisualization.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioVisualization.py
Apache-2.0
def text_list_to_colors_simple(names): ''' Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors. ''' uNames = list(set(names)) uNames.sort() textToColor = [ uNames.index(n) for n in names ] textToColor = np.array(textToColor) t...
Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors.
text_list_to_colors_simple
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioVisualization.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioVisualization.py
Apache-2.0
def visualizeFeaturesFolder(folder, dimReductionMethod, priorKnowledge = "none"): ''' This function generates a content visualization for the recordings of the provided path. ARGUMENTS: - folder: path of the folder that contains the WAV files to be processed ...
This function generates a content visualization for the recordings of the provided path. ARGUMENTS: - folder: path of the folder that contains the WAV files to be processed - dimReductionMethod: method used to reduce the dimension of the ...
visualizeFeaturesFolder
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioVisualization.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioVisualization.py
Apache-2.0
def beat_extraction(short_features, window_size, plot=False): """ This function extracts an estimate of the beat rate for a musical signal. ARGUMENTS: - short_features: a np array (n_feats x numOfShortTermWindows) - window_size: window size in seconds RETURNS: - bpm: ...
This function extracts an estimate of the beat rate for a musical signal. ARGUMENTS: - short_features: a np array (n_feats x numOfShortTermWindows) - window_size: window size in seconds RETURNS: - bpm: estimates of beats per minute - ratio: a confidence me...
beat_extraction
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/MidTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/MidTermFeatures.py
Apache-2.0
def directory_feature_extraction(folder_path, mid_window, mid_step, short_window, short_step, compute_beat=True): """ This function extracts the mid-term features of the WAVE files of a particular folder. The resulting feature vector is...
This function extracts the mid-term features of the WAVE files of a particular folder. The resulting feature vector is extracted by long-term averaging the mid-term features. Therefore ONE FEATURE VECTOR is extracted for each WAV file. ARGUMENTS: - folder_path: the path of the...
directory_feature_extraction
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/MidTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/MidTermFeatures.py
Apache-2.0
def multiple_directory_feature_extraction(path_list, mid_window, mid_step, short_window, short_step, compute_beat=False): """ Same as dirWavFeatureExtraction, but instead of a single dir it takes a list of paths as input and...
Same as dirWavFeatureExtraction, but instead of a single dir it takes a list of paths as input and returns a list of feature matrices. EXAMPLE: [features, classNames] = a.dirsWavFeatureExtraction(['audioData/classSegmentsRec/noise', 'audioData/classSegm...
multiple_directory_feature_extraction
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/MidTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/MidTermFeatures.py
Apache-2.0
def directory_feature_extraction_no_avg(folder_path, mid_window, mid_step, short_window, short_step): """ This function extracts the mid-term features of the WAVE files of a particular folder without averaging each file. ARGUMENTS: - folder_path: ...
This function extracts the mid-term features of the WAVE files of a particular folder without averaging each file. ARGUMENTS: - folder_path: the path of the WAVE directory - mid_window, mid_step: mid-term window and step (in seconds) - short_window, short_step: short...
directory_feature_extraction_no_avg
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/MidTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/MidTermFeatures.py
Apache-2.0
def mid_feature_extraction_to_file(file_path, mid_window, mid_step, short_window, short_step, output_file, store_short_features=False, store_csv=False, plot=False): """ This function is used as a wrapper to:...
This function is used as a wrapper to: a) read the content of a WAV file b) perform mid-term feature extraction on that signal c) write the mid-term feature sequences to a np file d) optionally write contents to csv file as well e) optionally write short-term features in csv and np file
mid_feature_extraction_to_file
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/MidTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/MidTermFeatures.py
Apache-2.0
def dc_normalize(sig_array): """Removes DC and normalizes to -1, 1 range""" sig_array_norm = sig_array.copy() sig_array_norm -= sig_array_norm.mean() sig_array_norm /= abs(sig_array_norm).max() + 1e-10 return sig_array_norm
Removes DC and normalizes to -1, 1 range
dc_normalize
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/ShortTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/ShortTermFeatures.py
Apache-2.0
def zero_crossing_rate(frame): """Computes zero crossing rate of frame""" count = len(frame) count_zero = np.sum(np.abs(np.diff(np.sign(frame)))) / 2 return np.float64(count_zero) / np.float64(count - 1.0)
Computes zero crossing rate of frame
zero_crossing_rate
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/ShortTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/ShortTermFeatures.py
Apache-2.0
def spectral_centroid_spread(fft_magnitude, sampling_rate): """Computes spectral centroid of frame (given abs(FFT))""" ind = (np.arange(1, len(fft_magnitude) + 1)) * \ (sampling_rate / (2.0 * len(fft_magnitude))) Xt = fft_magnitude.copy() Xt_max = Xt.max() if Xt_max == 0: Xt = Xt ...
Computes spectral centroid of frame (given abs(FFT))
spectral_centroid_spread
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/ShortTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/ShortTermFeatures.py
Apache-2.0
def spectral_flux(fft_magnitude, previous_fft_magnitude): """ Computes the spectral flux feature of the current frame ARGUMENTS: fft_magnitude: the abs(fft) of the current frame previous_fft_magnitude: the abs(fft) of the previous frame """ # compute the spectral fl...
Computes the spectral flux feature of the current frame ARGUMENTS: fft_magnitude: the abs(fft) of the current frame previous_fft_magnitude: the abs(fft) of the previous frame
spectral_flux
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/ShortTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/ShortTermFeatures.py
Apache-2.0
def chroma_features_init(num_fft, sampling_rate): """ This function initializes the chroma matrices used in the calculation of the chroma features """ freqs = np.array([((f + 1) * sampling_rate) / (2 * num_fft) for f in range(num_fft)]) cp = 27.50 num_chroma = np.round(...
This function initializes the chroma matrices used in the calculation of the chroma features
chroma_features_init
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/ShortTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/ShortTermFeatures.py
Apache-2.0
def chromagram(signal, sampling_rate, window, step, plot=False, show_progress=False): """ Short-term FFT mag for spectogram estimation: Returns: a np array (num_fft x numOfShortTermWindows) ARGUMENTS: signal: the input signal samples sampling_rate: th...
Short-term FFT mag for spectogram estimation: Returns: a np array (num_fft x numOfShortTermWindows) ARGUMENTS: signal: the input signal samples sampling_rate: the sampling freq (in Hz) window: the short-term window size (in samples) step: ...
chromagram
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/ShortTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/ShortTermFeatures.py
Apache-2.0
def spectrogram(signal, sampling_rate, window, step, plot=False, show_progress=False): """ Short-term FFT mag for spectogram estimation: Returns: a np array (numOfShortTermWindows x num_fft) ARGUMENTS: signal: the input signal samples sampling_rate: the s...
Short-term FFT mag for spectogram estimation: Returns: a np array (numOfShortTermWindows x num_fft) ARGUMENTS: signal: the input signal samples sampling_rate: the sampling freq (in Hz) window: the short-term window size (in samples) step: t...
spectrogram
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/ShortTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/ShortTermFeatures.py
Apache-2.0
def feature_extraction(signal, sampling_rate, window, step, deltas=True): """ This function implements the shor-term windowing process. For each short-term window a set of features is extracted. This results to a sequence of feature vectors, stored in a np matrix. ARGUMENTS signal: ...
This function implements the shor-term windowing process. For each short-term window a set of features is extracted. This results to a sequence of feature vectors, stored in a np matrix. ARGUMENTS signal: the input signal samples sampling_rate: the sampling freq (in Hz) ...
feature_extraction
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/ShortTermFeatures.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/ShortTermFeatures.py
Apache-2.0
def peakdet(v, delta, x = None): """ Converted from MATLAB script at http://billauer.co.il/peakdet.html Returns two arrays function [maxtab, mintab]=peakdet(v, delta, x) %PEAKDET Detect peaks in a vector % [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local % maxima ...
Converted from MATLAB script at http://billauer.co.il/peakdet.html Returns two arrays function [maxtab, mintab]=peakdet(v, delta, x) %PEAKDET Detect peaks in a vector % [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local % maxima and minima ("peaks") in the vector V. ...
peakdet
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/utilities.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/utilities.py
Apache-2.0
def create_random_personality(): """You are backstoryGPT. You come up with a backstory for a character incljuding name. Choose a completely random name from the list. Format as follows. Name: <name> Backstory: <3 sentence backstory>'""" # System prompt return "Come up with a backstory about " + random.choice(...
You are backstoryGPT. You come up with a backstory for a character incljuding name. Choose a completely random name from the list. Format as follows. Name: <name> Backstory: <3 sentence backstory>'
create_random_personality
python
MadcowD/ell
docs/ramblings/parsing_example.py
https://github.com/MadcowD/ell/blob/master/docs/ramblings/parsing_example.py
MIT
def create_random_personality(): """You are backstoryGPT. You come up with a backstory for a character incljuding name. Choose a completely random name from the list. Format as follows.""" # System prompt return "Come up with a backstory about " + random.choice(names_list) # User prompt
You are backstoryGPT. You come up with a backstory for a character incljuding name. Choose a completely random name from the list. Format as follows.
create_random_personality
python
MadcowD/ell
docs/ramblings/parsing_example.py
https://github.com/MadcowD/ell/blob/master/docs/ramblings/parsing_example.py
MIT
def lmp(func): """ Decorator that simulates multi-step calls to an LLM API. Prints each step and collects all yields from a generator. Returns the collected values. """ @wraps(func) def wrapper(*args, **kwargs): system_prompt = func.__doc__ print(f"\033[94mSystem: {system_pro...
Decorator that simulates multi-step calls to an LLM API. Prints each step and collects all yields from a generator. Returns the collected values.
lmp
python
MadcowD/ell
docs/ramblings/yield_ell.py
https://github.com/MadcowD/ell/blob/master/docs/ramblings/yield_ell.py
MIT
async def async_lmp(func): """ Async decorator that simulates multi-step calls to an LLM API. Prints each step and collects all yields from an async generator. Returns the collected values. """ @wraps(func) async def wrapper(*args, **kwargs): system_prompt = func.__doc__ prin...
Async decorator that simulates multi-step calls to an LLM API. Prints each step and collects all yields from an async generator. Returns the collected values.
async_lmp
python
MadcowD/ell
docs/ramblings/yield_ell.py
https://github.com/MadcowD/ell/blob/master/docs/ramblings/yield_ell.py
MIT
def choose_which_is_a_better_piece_of_writing(poem : str, story : str) -> str: """You are a literature critic choose the better piece of literature""" return f""" A: {poem} B: {story} Choose the better piece of literature"""
You are a literature critic choose the better piece of literature
choose_which_is_a_better_piece_of_writing
python
MadcowD/ell
examples/diamond_depencies.py
https://github.com/MadcowD/ell/blob/master/examples/diamond_depencies.py
MIT
def hello(world : str): """Your goal is to be really mean to the other guy while saying hello""" name = world.capitalize() number_of_chars_in_name = get_random_length() return f"Say hello to {name} in {number_of_chars_in_name} characters or more!"
Your goal is to be really mean to the other guy while saying hello
hello
python
MadcowD/ell
examples/hello_postgres.py
https://github.com/MadcowD/ell/blob/master/examples/hello_postgres.py
MIT
def buy_lottery_ticket(number: int = Field(description="Number to play in the lottery (0-16).")): """Buy a lottery ticket with the given number.""" if VERBOSE: sys.stderr.write(f"Calling tool: buy_lottery_ticket({number})\n") return f"Bought lottery ticket with number {number}"
Buy a lottery ticket with the given number.
buy_lottery_ticket
python
MadcowD/ell
examples/llm_lottery.py
https://github.com/MadcowD/ell/blob/master/examples/llm_lottery.py
MIT
def check_lottery_result(number: int = Field(description="Number to check against the lottery result.")): """Check if the given number wins the lottery.""" if VERBOSE: sys.stderr.write(f"Calling tool: check_lottery_result({number})\n") if number == WINNING_NUMBER: return "Congratulations! Yo...
Check if the given number wins the lottery.
check_lottery_result
python
MadcowD/ell
examples/llm_lottery.py
https://github.com/MadcowD/ell/blob/master/examples/llm_lottery.py
MIT
def cached_chat(history : List[str], new_message : str) -> str: """You are a helpful assistant who chats with the user. Your response should < 2 sentences.""" return f"""Here is the chat history: {'\n'.join(history)}. Please respond to this message: {new_message}"""
You are a helpful assistant who chats with the user. Your response should < 2 sentences.
cached_chat
python
MadcowD/ell
examples/openai_prompt_caching.py
https://github.com/MadcowD/ell/blob/master/examples/openai_prompt_caching.py
MIT
def create_personality() -> str: """You are backstoryGPT. You come up with a backstory for a character incljuding name. Choose a completely random name from the list. Format as follows. Name: <name> Backstory: <3 sentence backstory>'""" # System prompt return "Come up with a backstory about " + random...
You are backstoryGPT. You come up with a backstory for a character incljuding name. Choose a completely random name from the list. Format as follows. Name: <name> Backstory: <3 sentence backstory>'
create_personality
python
MadcowD/ell
examples/quick_chat.py
https://github.com/MadcowD/ell/blob/master/examples/quick_chat.py
MIT
def predict_capital(question: str): """ If the quesiton is about hotdog land, answer Banana. Otherwise, answer the question. """ # print(question[0]) return f"Answer the following question. {question}"
If the quesiton is about hotdog land, answer Banana. Otherwise, answer the question.
predict_capital
python
MadcowD/ell
examples/evals/classification.py
https://github.com/MadcowD/ell/blob/master/examples/evals/classification.py
MIT
def critic(text_to_summarize: str, ai_produced_summary: str): """ You are a critic of summaries. You are given a text and a summary of that text. You should evaluate the summary for how well it captures the main points of the text. Criterion: - Summary should be shorter than the original text. Do n...
You are a critic of summaries. You are given a text and a summary of that text. You should evaluate the summary for how well it captures the main points of the text. Criterion: - Summary should be shorter than the original text. Do not give it a score above 50 if it is longer. - The best scoring s...
critic
python
MadcowD/ell
examples/evals/summaries.py
https://github.com/MadcowD/ell/blob/master/examples/evals/summaries.py
MIT
def create_person_json(description: str): """ Generate a JSON object describing a person based on the given description. """ return ( f"Based on the description '{description}', create a JSON object for a Person." )
Generate a JSON object describing a person based on the given description.
create_person_json
python
MadcowD/ell
examples/future/json_mode.py
https://github.com/MadcowD/ell/blob/master/examples/future/json_mode.py
MIT
def get_ice_cream_flavors(): """ Return a list of ice cream flavors. """ #XXX: Nice coercion function needed return to_content_blocks([("1. Vanilla"), "2.", (generate_strawberry_image()), ("3. Coconut")])
Return a list of ice cream flavors.
get_ice_cream_flavors
python
MadcowD/ell
examples/future/multimodal_tool_use.py
https://github.com/MadcowD/ell/blob/master/examples/future/multimodal_tool_use.py
MIT
def update(self, other: "KnowledgeGraph") -> "KnowledgeGraph": """Updates the current graph with the other graph, deduplicating nodes and edges.""" # Create dictionaries to store unique nodes and edges unique_nodes = {node.id: node for node in self.nodes} unique_edges = {(edge.source, ed...
Updates the current graph with the other graph, deduplicating nodes and edges.
update
python
MadcowD/ell
examples/future/o1_graph.py
https://github.com/MadcowD/ell/blob/master/examples/future/o1_graph.py
MIT
def create_claim_draft(claim_details: str, claim_type: str, claim_amount: float, claim_date : str = Field(description="The date of the claim in the format YYYY-MM-DD.")): """Create a claim draft. Returns the claim id created.""" print("Create claim draft", claim_details, claim_type, clai...
Create a claim draft. Returns the claim id created.
create_claim_draft
python
MadcowD/ell
examples/future/tool_using_chatbot.py
https://github.com/MadcowD/ell/blob/master/examples/future/tool_using_chatbot.py
MIT
def get_html_content( url : str = Field(description="The URL to get the HTML content of. Never incldue the protocol (like http:// or https://)"), ): """Get the HTML content of a URL.""" response = requests.get("https://" + url) soup = BeautifulSoup(response.text, 'html.parser') # print(soup.get_...
Get the HTML content of a URL.
get_html_content
python
MadcowD/ell
examples/future/use_tool_once.py
https://github.com/MadcowD/ell/blob/master/examples/future/use_tool_once.py
MIT
def get_weather(location: str = Field(description="The full name of a city and country, e.g. San Francisco, CA, USA")): """Get the current weather for a given location.""" # Simulated weather API call return f"The weather in {location} is sunny."
Get the current weather for a given location.
get_weather
python
MadcowD/ell
examples/future/weather_example.py
https://github.com/MadcowD/ell/blob/master/examples/future/weather_example.py
MIT
def travel_planner(destination: str): """Plan a trip based on the destination and current weather.""" return [ ell.system("You are a travel planner. Use the weather tool to provide relevant advice."), ell.user(f"Plan a trip to {destination}") ]
Plan a trip based on the destination and current weather.
travel_planner
python
MadcowD/ell
examples/future/weather_example.py
https://github.com/MadcowD/ell/blob/master/examples/future/weather_example.py
MIT
def translate_to_provider(self, *args, **kwargs): """ This translates ell call parameters to the provider call parameters. In this case instructor is just an openai client, so we can use the openai provider to do the translation. We just need to modify a few parameters because instructor doesn't suppor...
This translates ell call parameters to the provider call parameters. In this case instructor is just an openai client, so we can use the openai provider to do the translation. We just need to modify a few parameters because instructor doesn't support streaming.
translate_to_provider
python
MadcowD/ell
examples/providers/instructor_ex.py
https://github.com/MadcowD/ell/blob/master/examples/providers/instructor_ex.py
MIT
def translate_from_provider(self,provider_response, ell_call : EllCallParams, provider_call_params : Dict[str, Any], origin_id : str, logger : Optional[Callable] = None) -> Tuple[Message, Metadata]: """This translates the provider response (the result of calling ...
This translates the provider response (the result of calling client.chat.completions.create with the parameters from translate_to_provider) to an an ell message. In this case instructor just returns a pydantic type which we can use to create an ell response model.
translate_from_provider
python
MadcowD/ell
examples/providers/instructor_ex.py
https://github.com/MadcowD/ell/blob/master/examples/providers/instructor_ex.py
MIT
def rag(query: str, context: str) -> str: """You are an AI assistant using Retrieval-Augmented Generation (RAG). RAG enhances your responses by retrieving relevant information from a knowledge base. You will be provided with a query and relevant context. Use this context to inform your response, but als...
You are an AI assistant using Retrieval-Augmented Generation (RAG). RAG enhances your responses by retrieving relevant information from a knowledge base. You will be provided with a query and relevant context. Use this context to inform your response, but also draw upon your general knowledge when appropria...
rag
python
MadcowD/ell
examples/rag/rag.py
https://github.com/MadcowD/ell/blob/master/examples/rag/rag.py
MIT
def search_wikipedia(keywords: str = Field(description="Kewords for wikipedia search engine.")): """Search Wikipedia and return a list of search results and links.""" if VERBOSE: eprint(f"Calling tool: search_wikipedia('{keywords}')") encoded_query = urllib.parse.quote(keywords) cmd = f...
Search Wikipedia and return a list of search results and links.
search_wikipedia
python
MadcowD/ell
examples/rag/wikipedia_mini_rag.py
https://github.com/MadcowD/ell/blob/master/examples/rag/wikipedia_mini_rag.py
MIT
def wikipedia_page_content(wiki_page_url: str): """Fetch the content of a Wikipedia page given its URL.""" if VERBOSE: eprint(f"Calling tool: wikipedia_page_content('{wiki_page_url}')") cmd = f"lynx --dump '{wiki_page_url}'" result = subprocess.run(cmd, shell=True, capture_output=True) ...
Fetch the content of a Wikipedia page given its URL.
wikipedia_page_content
python
MadcowD/ell
examples/rag/wikipedia_mini_rag.py
https://github.com/MadcowD/ell/blob/master/examples/rag/wikipedia_mini_rag.py
MIT
def model_registry_override(self, overrides: Dict[str, _Model]): """ Temporarily override the model registry with new model configurations. :param overrides: A dictionary of model names to ModelConfig instances to override. :type overrides: Dict[str, ModelConfig] """ if ...
Temporarily override the model registry with new model configurations. :param overrides: A dictionary of model names to ModelConfig instances to override. :type overrides: Dict[str, ModelConfig]
model_registry_override
python
MadcowD/ell
src/ell/configurator.py
https://github.com/MadcowD/ell/blob/master/src/ell/configurator.py
MIT
def get_client_for(self, model_name: str) -> Tuple[Optional[openai.Client], bool]: """ Get the OpenAI client for a specific model name. :param model_name: The name of the model to get the client for. :type model_name: str :return: The OpenAI client for the specified model, or No...
Get the OpenAI client for a specific model name. :param model_name: The name of the model to get the client for. :type model_name: str :return: The OpenAI client for the specified model, or None if not found, and a fallback flag. :rtype: Tuple[Optional[openai.Client], bool] ...
get_client_for
python
MadcowD/ell
src/ell/configurator.py
https://github.com/MadcowD/ell/blob/master/src/ell/configurator.py
MIT
def register_provider(self, provider: Provider, client_type: Type[Any]) -> None: """ Register a provider class for a specific client type. :param provider_class: The provider class to register. :type provider_class: Type[Provider] """ assert isinstance( clien...
Register a provider class for a specific client type. :param provider_class: The provider class to register. :type provider_class: Type[Provider]
register_provider
python
MadcowD/ell
src/ell/configurator.py
https://github.com/MadcowD/ell/blob/master/src/ell/configurator.py
MIT
def get_provider_for(self, client: Union[Type[Any], Any]) -> Optional[Provider]: """ Get the provider instance for a specific client instance. :param client: The client instance to get the provider for. :type client: Any :return: The provider instance for the specified client, o...
Get the provider instance for a specific client instance. :param client: The client instance to get the provider for. :type client: Any :return: The provider instance for the specified client, or None if not found. :rtype: Optional[Provider]
get_provider_for
python
MadcowD/ell
src/ell/configurator.py
https://github.com/MadcowD/ell/blob/master/src/ell/configurator.py
MIT
def provider_call_function( self, client: Any, api_call_params: Optional[Dict[str, Any]] = None ) -> Callable[..., Any]: """ Implement this method to return the function that makes the API call to the language model. For example, if you're implementing the OpenAI provider, you would ...
Implement this method to return the function that makes the API call to the language model. For example, if you're implementing the OpenAI provider, you would return the function that makes the API call to OpenAI's API.
provider_call_function
python
MadcowD/ell
src/ell/provider.py
https://github.com/MadcowD/ell/blob/master/src/ell/provider.py
MIT
def translate_from_provider( self, provider_response: Any, ell_call: EllCallParams, provider_call_params: Dict[str, Any], origin_id: Optional[str] = None, logger: Optional[Callable[..., None]] = None, ) -> Tuple[List[Message], Metadata]: """Converts provider r...
Converts provider responses to universal format. with metadata
translate_from_provider
python
MadcowD/ell
src/ell/provider.py
https://github.com/MadcowD/ell/blob/master/src/ell/provider.py
MIT
def __init__(self, name: str, *, metrics=None, annotations=None, criterion=None, dataset=None, n_evals=None, samples_per_datapoint=1, default_api_params=None, has_serialized=False, id=None): """Initialize with both class fields and additional parameters""" self.name = ...
Initialize with both class fields and additional parameters
__init__
python
MadcowD/ell
src/ell/evaluation/evaluation.py
https://github.com/MadcowD/ell/blob/master/src/ell/evaluation/evaluation.py
MIT
def _get_messages(prompt_ret: Union[str, list[MessageOrDict]], prompt: LMP) -> list[Message]: """ Helper function to convert the output of an LMP into a list of Messages. """ if isinstance(prompt_ret, str): has_system_prompt = prompt.__doc__ is not None and prompt.__doc__.strip() != "" m...
Helper function to convert the output of an LMP into a list of Messages.
_get_messages
python
MadcowD/ell
src/ell/lmp/complex.py
https://github.com/MadcowD/ell/blob/master/src/ell/lmp/complex.py
MIT
def register(client: anthropic.Anthropic): """ Register Anthropic models with the provided client. This function takes an Anthropic client and registers various Anthropic models with the global configuration. It allows the system to use these models for different AI tasks. ...
Register Anthropic models with the provided client. This function takes an Anthropic client and registers various Anthropic models with the global configuration. It allows the system to use these models for different AI tasks. Args: client (anthropic.Anthropic): An...
register
python
MadcowD/ell
src/ell/models/anthropic.py
https://github.com/MadcowD/ell/blob/master/src/ell/models/anthropic.py
MIT
def register(client: Any): """ Register Bedrock models with the provided client. This function takes an boto3 client and registers various Bedrock models with the global configuration. It allows the system to use these models for different AI tasks. Args: client (boto3.client): An inst...
Register Bedrock models with the provided client. This function takes an boto3 client and registers various Bedrock models with the global configuration. It allows the system to use these models for different AI tasks. Args: client (boto3.client): An instance of the bedrock client to be u...
register
python
MadcowD/ell
src/ell/models/bedrock.py
https://github.com/MadcowD/ell/blob/master/src/ell/models/bedrock.py
MIT
def register(client: Optional[openai.Client] = None): """ Register OpenAI models with the provided client. This function takes an OpenAI client and registers various OpenAI models with the global configuration. It allows the system to use these models for different AI tasks. Args: clie...
Register OpenAI models with the provided client. This function takes an OpenAI client and registers various OpenAI models with the global configuration. It allows the system to use these models for different AI tasks. Args: client (openai.Client): An instance of the OpenAI client to be us...
register
python
MadcowD/ell
src/ell/models/google.py
https://github.com/MadcowD/ell/blob/master/src/ell/models/google.py
MIT
def register(base_url): """ Registers Ollama models with the provided base URL. This function sets up the Ollama client with the given base URL and fetches available models from the Ollama API. It then registers these models with the global configuration, allowing them to be used within the ell...
Registers Ollama models with the provided base URL. This function sets up the Ollama client with the given base URL and fetches available models from the Ollama API. It then registers these models with the global configuration, allowing them to be used within the ell framework. Args: ...
register
python
MadcowD/ell
src/ell/models/ollama.py
https://github.com/MadcowD/ell/blob/master/src/ell/models/ollama.py
MIT
def messages_to_groq_message_format(messages): """Assistant messages to Groq must take the format: {'role': 'assistant', 'content': <string>}""" # XXX: Issue #289: groq.BadRequestError: Error code: 400 - {'error': {'message': "'messages.1' : for 'role:assistant' the following must be satisfied[('messages.1.cont...
Assistant messages to Groq must take the format: {'role': 'assistant', 'content': <string>}
messages_to_groq_message_format
python
MadcowD/ell
src/ell/providers/groq.py
https://github.com/MadcowD/ell/blob/master/src/ell/providers/groq.py
MIT
def get_latest_lmps( self, session: Session, skip: int = 0, limit: int = 10 ) -> List[Dict[str, Any]]: """ Gets all the lmps grouped by unique name with the highest created at """ subquery = ( select( SerializedLMP.name, func.max(Se...
Gets all the lmps grouped by unique name with the highest created at
get_latest_lmps
python
MadcowD/ell
src/ell/stores/sql.py
https://github.com/MadcowD/ell/blob/master/src/ell/stores/sql.py
MIT
def freeze(self, *lmps: InvocableLM): """ A context manager for caching operations using a particular store. Args: *lmps: InvocableLM objects to freeze. Yields: None """ old_cache_values = {} try: for lmp in lmps: ...
A context manager for caching operations using a particular store. Args: *lmps: InvocableLM objects to freeze. Yields: None
freeze
python
MadcowD/ell
src/ell/stores/store.py
https://github.com/MadcowD/ell/blob/master/src/ell/stores/store.py
MIT
def init_or_migrate_database(engine) -> None: """Initialize or migrate database with ELL schema Handles three cases: 1. Existing database with our tables but no Alembic -> stamp with initial migration 2. Database with Alembic -> upgrade to head 3. New/empty database or database without our tabl...
Initialize or migrate database with ELL schema Handles three cases: 1. Existing database with our tables but no Alembic -> stamp with initial migration 2. Database with Alembic -> upgrade to head 3. New/empty database or database without our tables -> create tables and stamp with head Args...
init_or_migrate_database
python
MadcowD/ell
src/ell/stores/migrations/__init__.py
https://github.com/MadcowD/ell/blob/master/src/ell/stores/migrations/__init__.py
MIT
def coerce(cls, content: AnyContent) -> "ContentBlock": """ Coerce various types of content into a ContentBlock. This method provides a flexible way to create ContentBlock instances from different types of input. Args: content: The content to be coerced into a ContentBlock. Can...
Coerce various types of content into a ContentBlock. This method provides a flexible way to create ContentBlock instances from different types of input. Args: content: The content to be coerced into a ContentBlock. Can be one of the following types: - str: Will be converted to...
coerce
python
MadcowD/ell
src/ell/types/message.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/message.py
MIT
def to_content_blocks( content: Optional[Union[AnyContent, List[AnyContent]]] = None, **content_block_kwargs ) -> List[ContentBlock]: """ Coerce a variety of input types into a list of ContentBlock objects. Args: content: The content to be coerced. Can be a single item or a list of items. ...
Coerce a variety of input types into a list of ContentBlock objects. Args: content: The content to be coerced. Can be a single item or a list of items. Supported types include str, ContentBlock, ToolCall, ToolResult, BaseModel, Image, np.ndarray, and PILImage.Image. **content_block_kwargs...
to_content_blocks
python
MadcowD/ell
src/ell/types/message.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/message.py
MIT
def parsed(self) -> Union[BaseModel, List[BaseModel]]: """Returns a list of all parsed content. Example: >>> class CustomModel(BaseModel): ... value: int >>> parsed_content = CustomModel(value=42) >>> message = Message(role="user", content=["Text", Co...
Returns a list of all parsed content. Example: >>> class CustomModel(BaseModel): ... value: int >>> parsed_content = CustomModel(value=42) >>> message = Message(role="user", content=["Text", ContentBlock(parsed=parsed_content)]) >>> len(message.pa...
parsed
python
MadcowD/ell
src/ell/types/message.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/message.py
MIT
def serialize_content(self, content: List[ContentBlock]): """Serialize content blocks to a format suitable for JSON""" return [ {k: v for k, v in { 'text': str(block.text) if block.text is not None else None, 'image': block.image.model_dump() if block.image ...
Serialize content blocks to a format suitable for JSON
serialize_content
python
MadcowD/ell
src/ell/types/message.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/message.py
MIT
def model_validate_json(cls, json_str: str) -> 'Message': """Custom validation to handle deserialization from JSON string""" try: data = json.loads(json_str) return cls.model_validate(data) except json.JSONDecodeError as e: raise ValueError(f"Invalid JSON: {...
Custom validation to handle deserialization from JSON string
model_validate_json
python
MadcowD/ell
src/ell/types/message.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/message.py
MIT
def __new__( cls, content: str, logits: Optional[np.ndarray] = None, origin_trace: Optional[Union[str, FrozenSet[str]]] = None, ): """ Create a new instance of lstr. The `logits` should be a numpy array and `origin_trace` should be a frozen set of strings or a single...
Create a new instance of lstr. The `logits` should be a numpy array and `origin_trace` should be a frozen set of strings or a single string. Args: content (str): The string content of the lstr. logits (np.ndarray, optional): The logits associated with this string. Defaults to None....
__new__
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT
def __add__(self, other: Union[str, "_lstr"]) -> "_lstr": """ Concatenate this lstr instance with another string or lstr instance. Args: other (Union[str, "lstr"]): The string or lstr instance to concatenate with this instance. Returns: lstr: A new lstr instance...
Concatenate this lstr instance with another string or lstr instance. Args: other (Union[str, "lstr"]): The string or lstr instance to concatenate with this instance. Returns: lstr: A new lstr instance containing the concatenated content, with theorigin_trace(s) updated...
__add__
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT
def __mod__( self, other: Union[str, "_lstr", Tuple[Union[str, "_lstr"], ...]] ) -> "_lstr": """ Perform a modulo operation between this lstr instance and another string, lstr, or a tuple of strings and lstrs, tracing the operation by logging the operands and the result. Arg...
Perform a modulo operation between this lstr instance and another string, lstr, or a tuple of strings and lstrs, tracing the operation by logging the operands and the result. Args: other (Union[str, "lstr", Tuple[Union[str, "lstr"], ...]]): The right operand in the modulo operation...
__mod__
python
MadcowD/ell
src/ell/types/_lstr.py
https://github.com/MadcowD/ell/blob/master/src/ell/types/_lstr.py
MIT