code
stringlengths
17
6.64M
class Logger(): ' Writes evaluation results of training/testing ' @classmethod def initialize(cls, args, training): logtime = datetime.datetime.now().__format__('_%m%d_%H%M%S') logpath = (args.logpath if training else (('_TEST_' + args.load.split('/')[(- 2)].split('.')[0]) + logtime)) ...
def fix_randseed(seed): ' Set random seeds for reproducibility ' if (seed is None): seed = int((random.random() * 100000.0)) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.benchmark = False torch.b...
def mean(x): return ((sum(x) / len(x)) if (len(x) > 0) else 0.0)
def to_cuda(batch): for (key, value) in batch.items(): if isinstance(value, torch.Tensor): batch[key] = value.cuda() return batch
def to_cpu(tensor): return tensor.detach().clone().cpu()
class DatasetCOCO(Dataset): def __init__(self, datapath, fold, transform, split, shot, use_original_imgsize): self.split = ('val' if (split in ['val', 'test']) else 'trn') self.fold = fold self.nfolds = 4 self.nclass = 80 self.benchmark = 'coco' self.shot = shot ...
class FSSDataset(): @classmethod def initialize(cls, img_size, datapath, use_original_imgsize): cls.datasets = {'pascal': DatasetPASCAL, 'coco': DatasetCOCO, 'fss': DatasetFSS} cls.img_mean = [0.485, 0.456, 0.406] cls.img_std = [0.229, 0.224, 0.225] cls.datapath = datapath ...
class DatasetFSS(Dataset): def __init__(self, datapath, fold, transform, split, shot, use_original_imgsize): self.split = split self.benchmark = 'fss' self.shot = shot self.base_path = os.path.join(datapath, 'FSS-1000') with open(('./data/splits/fss/%s.txt' % split), 'r') ...
class DatasetPASCAL(Dataset): def __init__(self, datapath, fold, transform, split, shot, use_original_imgsize): self.split = ('val' if (split in ['val', 'test']) else 'trn') self.fold = fold self.nfolds = 4 self.nclass = 20 self.benchmark = 'pascal' self.shot = sho...
class CenterPivotConv4d(nn.Module): ' CenterPivot 4D conv' def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=True): super(CenterPivotConv4d, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size[:2], stride=stride[:2], bias=bias, padding...
class Correlation(): @classmethod def multilayer_correlation(cls, query_feats, support_feats, stack_ids): eps = 1e-05 corrs = [] for (idx, (query_feat, support_feat)) in enumerate(zip(query_feats, support_feats)): (bsz, ch, hb, wb) = support_feat.size() support...
def extract_feat_vgg(img, backbone, feat_ids, bottleneck_ids=None, lids=None): ' Extract intermediate features from VGG ' feats = [] feat = img for (lid, module) in enumerate(backbone.features): feat = module(feat) if (lid in feat_ids): feats.append(feat.clone()) return...
def extract_feat_res(img, backbone, feat_ids, bottleneck_ids, lids): ' Extract intermediate features from ResNet' feats = [] feat = backbone.conv1.forward(img) feat = backbone.bn1.forward(feat) feat = backbone.relu.forward(feat) feat = backbone.maxpool.forward(feat) for (hid, (bid, lid)) i...
class HPNLearner(nn.Module): def __init__(self, inch): super(HPNLearner, self).__init__() def make_building_block(in_channel, out_channels, kernel_sizes, spt_strides, group=4): assert (len(out_channels) == len(kernel_sizes) == len(spt_strides)) building_block_layers = [] ...
def test(model, dataloader, nshot): ' Test HSNet ' utils.fix_randseed(0) average_meter = AverageMeter(dataloader.dataset) for (idx, batch) in enumerate(dataloader): batch = utils.to_cuda(batch) pred_mask = model.module.predict_mask_nshot(batch, nshot=nshot) assert (pred_mask.si...
def train(epoch, model, dataloader, optimizer, training): ' Train HSNet ' (utils.fix_randseed(None) if training else utils.fix_randseed(0)) (model.module.train_mode() if training else model.module.eval()) average_meter = AverageMeter(dataloader.dataset) for (idx, batch) in enumerate(dataloader): ...
def parse_arguments(): '\n Parse options for functions.\n ' parser = argparse.ArgumentParser(description='Tool for managing Elasticsearch indices') subparsers = parser.add_subparsers() create = subparsers.add_parser('create', help='Create Elasticsearch index') create.add_argument('-i', '--index'...
def create_index(es, index_name, body): if (not es.indices.exists(index_name)): es.indices.create(index=index_name, body=body)
def delete_indices(es, indices_name): for index in indices_name: if es.indices.exists(index): es.indices.delete(index=index) else: logger.info('Index `{}` not found'.format(index))
def reindex(es, source_index, target_index): helpers.reindex(es, source_index=source_index, target_index=target_index)
def lazy_indexing(es, path, chunck, index, item_type): def serialize_json(json_line): to_null = ['author', 'article_tag', 'list_of_tags', 'keywords', 'news_keywords'] for tag in to_null: if (json_line[tag] == '---'): json_line[tag] = None if (json_line['publica...
def groupByQuery(eintrag, eintrag_spalte): return dataset.groupby(eintrag_spalte).get_group(eintrag)
def groupByQuery(eintrag, eintrag_spalte): return dataset.groupby(eintrag_spalte).get_group(eintrag)
def gendata(records, index, type): for (k, v) in zip(records.keys(), records.values()): (yield {'_index': index, '_id': k, '_source': v})
def extract_classifications(line): classifications_list = [] start_classification = line.find('<classifications-ipcr>') relative_end_classification = (line[start_classification:].find('</classifications-ipcr>') + 23) classification_string = line[start_classification:(start_classification + relative_en...
def extract_citationIDs(application_identifier, line): words = line.split('\t')[6].split(' ') indices = [i for (i, x) in enumerate(words) if ('sr-cit' in x)] return [((application_identifier + '_') + words[i][(words[i].find('sr-cit') + 6):(words[i].find('sr-cit') + 10)]) for i in indices]
def normalize_claims(claims): normalized_claims = [] for claim in claims.split(','): if ('-' not in claim): normalized_claims.append(int(claim)) else: for number in range(int(claim.split('-')[0]), (int(claim.split('-')[1]) + 1)): normalized_claims.append...
def extract_citation_entry(citation_id, searchreport_line): citation = {} start_citation = searchreport_line.find(('<citation id="sr-cit' + citation_id[(- 4):])) relative_end_citation = (searchreport_line[start_citation:].find('</citation>') + 11) citation_string = searchreport_line[start_citation:(st...
def main(file): f = open(file, 'r', encoding='utf8', errors='ignore') lines = f.readlines() records = {} citations = {} for line in lines: if ('\ten\t' in line): application_identifier = line.split('EP\t')[1].split('\ten\t')[0].replace('\t', '') application_number =...
def createIndexPatentApplications(): settings = {'settings': {'number_of_shards': 1, 'number_of_replicas': 0}, 'mappings': {'properties': {'application_number': {'type': 'keyword'}, 'application_category': {'type': 'keyword'}, 'application_date': {'type': 'date'}, 'title': {'type': 'text'}, 'abstract': {'type': '...
def createIndexCitations(): settings = {'settings': {'number_of_shards': 1, 'number_of_replicas': 0, 'index.mapping.ignore_malformed': True}, 'mappings': {'properties': {'dnum': {'type': 'keyword'}, 'publication_url': {'type': 'text'}, 'country': {'type': 'keyword'}, 'kind': {'type': 'keyword'}, 'doc_number': {'t...
def upload(records, index, type): client = connections.create_connection(hosts=['http://172.16.64.23:9200/']) res = helpers.bulk(client, gendata(records, index, type), index=index, chunk_size=1000, request_timeout=200) print(res)
def gendata(records, index, type): for (k, v) in zip(records.keys(), records.values()): (yield {'_index': index, '_id': k, '_source': v})
def extract_classifications(line): classifications_list = [] start_classification = line.find('<classifications-ipcr>') relative_end_classification = (line[start_classification:].find('</classifications-ipcr>') + 23) classification_string = line[start_classification:(start_classification + relative_en...
def extract_citationIDs(application_identifier, line): words = line.split('\t')[6].split(' ') indices = [i for (i, x) in enumerate(words) if ('sr-cit' in x)] return [((application_identifier + '_') + words[i][(words[i].find('sr-cit') + 6):(words[i].find('sr-cit') + 10)]) for i in indices]
def normalize_claims(claims): normalized_claims = [] for claim in claims.split(','): if ('-' not in claim): normalized_claims.append(int(claim)) else: for number in range(int(claim.split('-')[0]), (int(claim.split('-')[1]) + 1)): normalized_claims.append...
def extract_citation_entry(citation_id, searchreport_line): citation = {} start_citation = searchreport_line.find(('<citation id="sr-cit' + citation_id[(- 4):])) relative_end_citation = (searchreport_line[start_citation:].find('</citation>') + 11) citation_string = searchreport_line[start_citation:(st...
def main(file): f = open(file, 'r', encoding='utf8', errors='ignore') lines = f.readlines() records = {} citations = {} for line in lines: if ('\ten\t' in line): application_identifier = line.split('EP\t')[1].split('\ten\t')[0].replace('\t', '') application_number =...
def createIndexPatentApplications(): settings = {'settings': {'number_of_shards': 1, 'number_of_replicas': 0}, 'mappings': {'properties': {'application_number': {'type': 'keyword'}, 'application_category': {'type': 'keyword'}, 'application_date': {'type': 'date'}, 'title': {'type': 'text'}, 'abstract': {'type': '...
def createIndexCitations(): settings = {'settings': {'number_of_shards': 1, 'number_of_replicas': 0, 'index.mapping.ignore_malformed': True}, 'mappings': {'properties': {'dnum': {'type': 'keyword'}, 'publication_url': {'type': 'text'}, 'country': {'type': 'keyword'}, 'kind': {'type': 'keyword'}, 'doc_number': {'t...
def upload(records, index, type): client = connections.create_connection(hosts=['http://172.16.64.23:9200/']) res = helpers.bulk(client, gendata(records, index, type), index=index, chunk_size=1000, request_timeout=200) print(res)
def query_exist_claim(): return {'query': {'bool': {'filter': [{'exists': {'field': 'citation_ids'}}, {'exists': {'field': 'claims'}}]}}}
def query_citation_id(citation_entry): return {'query': {'bool': {'filter': [{'exists': {'field': 'category_A'}}, {'ids': {'values': [citation_entry]}}]}}}
def process_hits(es, response, patent_application_id_column, patent_citation_column, application_claim_number_column, application_claim_text_column, related_passages_against_claim_column, category_column): print(response) all_response_patent_applications = response.get('hits').get('hits') for element in a...
def main(): patent_application_id_column = [] patent_citation_column = [] application_claim_number_column = [] application_claim_text_column = [] related_passages_against_claim_column = [] category_column = [] es = Elasticsearch(hosts=['http://172.16.64.23:9200/']) response = es.search...
def query_exist_claim(): return {'query': {'bool': {'filter': [{'exists': {'field': 'citation_ids'}}, {'exists': {'field': 'claims'}}]}}}
def query_citation_id(citation_entry): return {'query': {'bool': {'filter': [{'exists': {'field': 'category_X'}}, {'ids': {'values': [citation_entry]}}]}}}
def process_hits(es, response, patent_application_id_column, patent_citation_column, application_claim_number_column, application_claim_text_column, related_passages_against_claim_column, category_column): print(response) all_response_patent_applications = response.get('hits').get('hits') for element in a...
def main(): patent_application_id_column = [] patent_citation_column = [] application_claim_number_column = [] application_claim_text_column = [] related_passages_against_claim_column = [] category_column = [] es = Elasticsearch(hosts=['http://172.16.64.23:9200/']) response = es.search...
def desirable(tag): return ((tag[0] in ['paragraph', '-', '[']) or ((tag[1] in ['CD']) and tag[0].isdigit()))
def syntax_right(tag_before_tag, tag): if (tag[1] != 'CD'): return True else: return (((tag[1] == 'CD') and ('paragraph' in tag_before_tag[0])) or ('[' in tag_before_tag[0]))
def text_is_range(tag_before_tag, tag, tag_after_tag): return ((tag_before_tag[1] == 'CD') and (tag[0] == '-') and (tag_after_tag[1] == 'CD'))
def extract_paragraphs(text): tokens = nltk.word_tokenize(text.lower().replace('paragraphs', 'paragraph')) pos_tags = nltk.pos_tag(tokens) pos_tags = [tag for tag in pos_tags if desirable(tag)] pos_tags = [tag for (tag_before_tag, tag) in zip(([('', '')] + pos_tags[:(- 1)]), pos_tags) if syntax_right(...
def getAccessToken(): payload = 'grant_type=client_credentials' usrPass = ((consumer_key + ':') + consumer_secret_key) b64Val = base64.b64encode(bytes(usrPass, 'utf-8')) header = {'authorization': ('Basic %s' % b64Val.decode('utf-8')), 'content-type': 'application/x-www-form-urlencoded'} request_t...
def getEquivalents(number): access_token = getAccessToken() equivalent = [] payload = number header = {'authorization': ('Bearer %s' % access_token), 'content-type': 'text/plain'} request_equivalent = requests.post(request_url, headers=header, data=payload) response = request_equivalent.text ...
def query_patent_citation_country_docNumber(id): return {'query': {'bool': {'filter': [{'ids': {'values': [id]}}]}}}
def elasticSearch_process(id): response_citation = es.search(index='ep_patent_citations', body=query_patent_citation_country_docNumber(id), size=10000) try: country = response_citation.get('hits').get('hits')[0].get('_source').get('country') docNumber = response_citation.get('hits').get('hits'...
def getPatentCitationIds(csv_path): list_of_patent_citation_ids = [] list_of_equivalents_lists = [] dataframe = pd.read_csv(csv_path, header=0, skiprows=range(1, 2767211)) patent_citation_id_iterator = dataframe['patent_citation_id'] for id in patent_citation_id_iterator.unique(): list_of_...
def process_csv(path): global counter_error global counter_success with open(path) as f: lines = f.readlines() follow_up_next_line = False current_id = '' for line in lines: if (follow_up_next_line is True): equivalents_list = line.replace('[', '').replace(']', '')....
def elasticsearch_request_getDnum(citation_id): return {'query': {'bool': {'filter': [{'ids': {'values': [citation_id]}}]}}}
def elasticsearch_request_getParagraphText(application_number, application_category): return {'query': {'bool': {'filter': [{'term': {'application_number': application_number}}, {'term': {'application_category': application_category}}]}}}
def getPatentDetails(citation_id): response = es.search(index='ep_patent_citations', body=elasticsearch_request_getDnum(citation_id)) print(response) try: dnum = response['hits']['hits'][0]['_source']['dnum'] docNumber = response['hits']['hits'][0]['_source']['doc-number'] patentCo...
def dataframeToDict(dataframe, dictionary): for (index, entry) in dataframe.iterrows(): id_list = entry['equivalent_patents'].strip('][').split(', ') clean_id_list = [] for value in id_list: clean_id_list.append(value.replace("'", '')) dictionary[entry['patent_id']] = c...
def getParagraphText(dnum, application_category, paragraphs): response = es.search(index='ep_patent_applications', body=elasticsearch_request_getParagraphText(dnum, application_category)) try: paragraph_field = response['hits']['hits'][0]['_source']['description'] except: return 'not found...
def getParagraphFromText(paragraphsText, paragraphNumber): found_paragraph_position_start = paragraphsText.find((((('<p id="p' + ('%04d' % int(paragraphNumber))) + '" num="') + ('%04d' % int(paragraphNumber))) + '">')) found_paragraph_position_end = (paragraphsText.find('</p', found_paragraph_position_start) ...
def execute(): path = '/mnt/data/datasets/patents/patent_matching' positives = pd.read_csv((path + '/positives_satellite.csv'), header=0, dtype={'application_claim_text': str, 'patent_searchReport_paragraph': str}) negatives = pd.read_csv((path + '/negatives_satellite.csv'), header=0, dtype={'application_...
def query_citation_id(citation_entry): return {'query': {'ids': {'values': [citation_entry]}}}
def process_hits(response, column_id_pa, column_cit_srprt, column_category_P, column_category_A, column_category_D, column_category_Y, column_category_L, column_category_O, column_category_T, column_category_E, column_category_X): all_response_patent_applications = response.get('hits').get('hits') for element...
def read_file(f): with open(f, 'r') as f: return json.load(f)
def get_results(results, dataset, name): if (dataset not in datasets_mt_few_shot): res = {k: round((v['acc'] * 100), 1) for (k, v) in results.items()} else: res = {k.replace(name, 'few-shot'): round((v['acc'] * 100), 1) for (k, v) in results.items()} res = dict(sorted(res.items())) tas...
def get_all_results(models, datasets): all_results = defaultdict(dict) for (model, names) in models.items(): for dataset in datasets: for name in names: shots = (8 if ('mgsm' in dataset) else 0) if (not os.path.exists(f'../results/{model}/{name}/{name}_{data...
def get_dataframes(all_results, datasets): results_avg = pd.DataFrame() for dataset in datasets: results = pd.DataFrame(all_results[dataset]).T results['dataset'] = dataset results['model'] = [models_reverse[model] for model in results.index] results['size'] = model_sizes_all[:...
def plot_size_df_models(df, langs=False): df.set_index('size', inplace=True) df.groupby('model')['avg'].plot(x='size', y='acc', title=list(df['dataset'])[0], legend=True, marker='o') plt.xscale('log') plt.xticks(model_sizes_all, model_sizes_all, rotation='vertical') plt.show() if langs: ...
def get_dataframes_model(all_results, datasets, model_name, divide=False): dataset_keys = list(all_results.keys()) if divide: df_avg_self = pd.DataFrame() df_avg_mt = pd.DataFrame() else: df_avg = {} for average in (['avg'] + list(languages.keys())): df_avg[aver...
def plot_size_df_datasets(df, model_name, title, langs=False): titles = {'low': 'Low-resource languages', 'high': 'High-resource languages', 'avg': 'Average'} df.set_index('size', inplace=True) for average in (['avg'] + list(languages.keys())): if (average not in df.columns): continue ...
def get_metrics(): metrics_dict = defaultdict(dict) for dataset_name in _DATASETS: for model_name in _MODELS: if ((model_name == 'bloom-560m') and (dataset_name == 'xnli')): with open(f'metrics/{dataset_name}/bloom-1b1.json') as f: metrics_dict[dataset_n...
def add_avg(metrics_dict): metrics_dict_split = defaultdict(dict) for metric in ['sacrebleu', 'chrf++', 'comet']: metrics_dict_split[metric] = deepcopy(metrics_dict) for dataset_name in metrics_dict: for model_name in metrics_dict[dataset_name]: '\n i...
def plot_size_df_datasets(df, model_name, title, langs=False): df.set_index('size', inplace=True) df_model = df[(df['model'] == model_name)] for average in (['avg'] + list(languages.keys())): if (average not in df.columns): continue df_model[average].plot(x='size', y='acc', tit...
def get_dataframes_model(metrics_dict_split, model_name): for metric in ['comet']: df_avg = {} for average in (['avg'] + list(languages.keys())): df_avg[average] = pd.DataFrame({'model': _MODELS}, index=_MODELS) for dataset_name in metrics_dict_split[metric]: df = p...
def get_dataset(dataset_args: Dict[(str, str)]) -> DatasetDict: '\n Loads the dataset using the dataset_args.\n\n Args:\n - dataset_args (dict): A dictionary containing the dataset name, split, and configurations.\n\n Returns:\n - dataset (DatasetDict): A dictionary containing the dataset.\n ' ...
def get_dataset_mt(dataset_args: Dict[(str, str)], model: str) -> DatasetDict: '\n Loads the machine translation dataset using the dataset_args and model.\n\n Args:\n - dataset_args (dict): A dictionary containing the dataset name, split, and configurations.\n - model (str): The name of the model.\n\n...
def get_texts(dataset: DatasetDict, dataset_args: Dict[(str, str)]) -> DefaultDict[(str, Dict[(str, List[str])])]: '\n Extracts the texts from the dataset.\n\n Args:\n - dataset (DatasetDict): A dictionary containing the dataset.\n - dataset_args (dict): A dictionary containing the dataset name, split...
def load_comet(model_name: str='Unbabel/wmt22-comet-da'): '\n Loads the COMET model from a checkpoint.\n\n Args:\n - model_name (str): The name of the COMET model.\n\n Returns:\n - model: The loaded COMET model.\n ' model_path = download_model(model_name) model = load_from_checkpoint(mod...
@find_executable_batch_size(starting_batch_size=2048) def compute_comet(batch_size: int, model: load_from_checkpoint, predictions: List[str], references: List[str], sources: List[str], gpus: Optional[int]=None, progress_bar: bool=False) -> Dict[(str, float)]: '\n Computes the COMET score for a batch of transla...
def evaluate_translations(predictions: List[str], references: List[str], sources: List[str]) -> Dict[(str, float)]: '\n Evaluates the translations using sacrebleu, chrf and comet metrics.\n\n Args:\n - predictions (List[str]): A list of predicted translations.\n - references (List[str]): A list of ref...
def evaluate_texts(predictions: DefaultDict[(str, Dict[(str, List[str])])], references: DefaultDict[(str, Dict[(str, List[str])])], dataset_args: Dict[(str, str)], model_name: str) -> None: '\n Evaluates the translations for each configuration and field.\n\n Args:\n - predictions (defaultdict): A diction...
def save_file(evaluations: Dict[(str, Dict[(str, Dict[(str, float)])])], dataset_args: Dict[(str, str)], model_name: str) -> None: '\n Saves the evaluation results to a file.\n\n Args:\n - evaluations (dict): A dictionary containing the evaluation results for each configuration and field.\n - dataset_...
def main() -> None: '\n Main function that evaluates the translations for each dataset and model.\n ' for dataset_name in _DATASETS: dataset_args = dataset_configs[dataset_name] print('Evaluating dataset', dataset_name) dataset = get_dataset(dataset_args) references = get...
def count_lines(input_list: List[str]) -> int: '\n Counts the number of lines in a list of strings.\n\n Args:\n input_list (List[str]): List of strings.\n\n Returns:\n int: Number of lines in the list.\n ' return len(input_list)
class DatasetReader(IterableDataset): def __init__(self, sentences: List[str], tokenizer, max_length: int=128): '\n Initializes the DatasetReader class.\n\n Args:\n sentences (List[str]): List of sentences.\n tokenizer: Tokenizer object.\n max_length (int, o...
class ParallelTextReader(IterableDataset): def __init__(self, predictions: List[str], references: List[str]): '\n Initializes the ParallelTextReader class.\n\n Args:\n predictions (List[str]): List of predicted sentences.\n references (List[str]): List of reference sen...
def encode_string(text): return text.replace('\r', '\\r').replace('\n', '\\n').replace('\t', '\\t')
def get_dataloader(accelerator: Accelerator, translate_data, tokenizer: PreTrainedTokenizerBase, batch_size: int, max_length: int) -> DataLoader: dataset = DatasetReader(translate_data, tokenizer, max_length) if (accelerator.distributed_type == DistributedType.TPU): data_collator = DataCollatorForSeq2...
def main(source_lang: str, target_lang: str, starting_batch_size: int, model_name: str='facebook/m2m100_1.2B', cache_dir: str=None, precision: str='32', max_length: int=128, num_beams: int=4, num_return_sequences: int=1, do_sample: bool=False, temperature: float=1.0, top_k: int=50, top_p: float=1.0, keep_special_toke...
def get_dataset(dataset_args: Dict[(str, Any)]) -> DatasetDict: '\n Load the dataset specified in dataset_args and return a DatasetDict object.\n\n Args:\n - dataset_args: A dictionary containing the dataset name, dataset configurations, dataset split.\n\n Returns:\n - A DatasetDict object containi...
def get_texts(dataset: DatasetDict, dataset_args: Dict[(str, Any)]) -> Dict[(str, Dict[(str, Any)])]: '\n Extract the texts from the dataset and return a dictionary containing the texts.\n\n Args:\n - dataset: A DatasetDict object containing the loaded dataset.\n - dataset_args: A dictionary containin...
def get_few_shot_dataset(dataset_args: Dict[(str, Any)]) -> DatasetDict: '\n Load the few-shot dataset specified in dataset_args and return a DatasetDict object.\n\n Args:\n - dataset_args: A dictionary containing the few-shot dataset configurations.\n\n Returns:\n - A DatasetDict object containing...
def get_few_shot_prompts(dataset: DatasetDict, dataset_args: Dict[(str, Any)], translate_args: Dict[(str, Any)], shots: int) -> Dict[(str, str)]: '\n Generate few-shot prompts for each language in dataset_args and return a dictionary containing the prompts.\n\n Args:\n - dataset: A DatasetDict object con...
def text_with_prompt(text: str, prompt: str, translate_args: Dict[(str, Any)]) -> str: '\n Concatenate the text with the prompt and the eos_token.\n\n Args:\n - text: A string representing the text to be concatenated.\n - prompt: A string representing the prompt to be concatenated.\n - translate_ar...
def map_texts_with_prompts(texts: Dict[(str, Dict[(str, List[str])])], prompts: Dict[(str, str)], translate_args: Dict[(str, Any)]) -> Dict[(str, Dict[(str, List[str])])]: '\n Map the texts with the prompts.\n\n Args:\n - texts: A dictionary containing the texts to be mapped.\n - prompts: A dictionary...