code
stringlengths
17
6.64M
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...
def extract_translations(translations: List[str], texts: List[str], translate_args: Dict[(str, Any)]) -> List[str]: '\n Extract the translation from the output of the translation model.\n\n Args:\n - translations: A list containing the translations to be extracted.\n - texts: A list containing the tex...
def translate_texts(dataset: DatasetDict, texts: Dict[(str, Dict[(str, List[str])])], translate_args: Dict[(str, Any)], dataset_args: Dict[(str, Any)]) -> None: '\n Translate the texts.\n\n Args:\n - dataset: A DatasetDict object containing the dataset.\n - texts: A dictionary containing the texts to ...
def save_file(translations: Dict[(str, List[str])], config: str, translate_args: Dict[(str, Any)], dataset_args: Dict[(str, Any)]) -> None: '\n Save the translations to a file.\n\n Args:\n - translations: A dictionary containing the translations to be saved.\n - config: A string representing the confi...
def main(translate_args: Dict[(str, Any)], dataset_args: Dict[(str, Any)]) -> None: '\n Main function to translate the dataset.\n\n Args:\n - translate_args: A dictionary containing the translation configurations.\n - dataset_args: A dictionary containing the dataset configurations.\n\n Returns:\n ...
def get_dataset(dataset_args): dataset = DatasetDict() for config in dataset_args['dataset_configs']: dataset[config] = load_dataset(dataset_args['dataset'], config, split=dataset_args['dataset_split']) return dataset
def get_texts(dataset, dataset_args): texts = defaultdict(dict) for config in dataset_args['dataset_configs']: for field in dataset_args['dataset_fields']: texts[config][field] = dataset[config][field] return texts
def translate_texts(dataset, texts, translate_args, dataset_args): translations = {} for config in dataset_args['dataset_configs']: translations[config] = dataset[config].to_dict() translate_args['source_lang'] = dataset_args['lang_codes'][config] print(f'Translating from {config}') ...
def save_file(translations, config, translate_args, dataset_args): name = translate_args['model_name'].split('/')[(- 1)] dirname = f"{dataset_args['file_path']}/{name}" if (not os.path.exists(dirname)): os.makedirs(dirname) translated_df = pd.DataFrame(translations) filename = f"{dirname}/...
def main(translate_args, dataset_args): dataset = get_dataset(dataset_args) texts = get_texts(dataset, dataset_args) translate_texts(dataset, texts, translate_args, dataset_args)
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, max_new_tokens: 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: flo...
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 setup(app): app.add_css_file('custom.css')
def parse_keys_section(self, section): return self._format_fields('Keys', self._consume_fields())
def parse_attributes_section(self, section): return self._format_fields('Attributes', self._consume_fields())
def parse_class_attributes_section(self, section): return self._format_fields('Class Attributes', self._consume_fields())
def patched_parse(self): self._sections['keys'] = self._parse_keys_section self._sections['class attributes'] = self._parse_class_attributes_section self._unpatched_parse()
class MyDeepText(nn.Module): def __init__(self, vocab_size, padding_idx=1, embed_dim=100, hidden_dim=64): super(MyDeepText, self).__init__() self.word_embed = nn.Embedding(vocab_size, embed_dim, padding_idx=padding_idx) self.rnn = nn.GRU(embed_dim, hidden_dim, num_layers=2, bidirectional=...
class RMSELoss(nn.Module): def __init__(self): 'root mean squared error' super().__init__() self.mse = nn.MSELoss() def forward(self, input: Tensor, target: Tensor) -> Tensor: return torch.sqrt(self.mse(input, target))
class Accuracy(Metric): def __init__(self, top_k: int=1): super(Accuracy, self).__init__() self.top_k = top_k self.correct_count = 0 self.total_count = 0 self._name = 'acc' def reset(self): self.correct_count = 0 self.total_count = 0 def __call__(...
class SillyCallback(Callback): def on_train_begin(self, logs=None): self.trainer.silly_callback = {} self.trainer.silly_callback['beginning'] = [] self.trainer.silly_callback['end'] = [] def on_epoch_begin(self, epoch, logs=None): self.trainer.silly_callback['beginning'].appe...
class RayTuneReporter(Callback): 'Callback that allows reporting history and lr_history values to RayTune\n during Hyperparameter tuning\n\n Callbacks are passed as input parameters to the ``Trainer`` class. See\n :class:`pytorch_widedeep.trainer.Trainer`\n\n For examples see the examples folder at:\n...
class WnBReportBest(Callback): 'Callback that allows reporting best performance of a run to WnB\n during Hyperparameter tuning. It is an adjusted pytorch_widedeep.callbacks.ModelCheckpoint\n with added WnB and removed checkpoint saving.\n\n Callbacks are passed as input parameters to the ``Trainer`` clas...
@wandb_mixin def training_function(config, X_train, X_val): early_stopping = EarlyStopping() model_checkpoint = ModelCheckpoint(save_best_only=True) batch_size = config['batch_size'] trainer = Trainer(model, objective='binary_focal_loss', callbacks=[RayTuneReporter, WnBReportBest(wb=wandb), early_stop...
def get_coo_indexes(lil): rows = [] cols = [] for (i, el) in enumerate(lil): if (type(el) != list): el = [el] for j in el: rows.append(i) cols.append(j) return (rows, cols)
def get_sparse_features(series, shape): coo_indexes = get_coo_indexes(series.tolist()) sparse_df = coo_matrix((np.ones(len(coo_indexes[0])), (coo_indexes[0], coo_indexes[1])), shape=shape) return sparse_df
def sparse_to_idx(data, pad_idx=(- 1)): indexes = data.nonzero() indexes_df = pd.DataFrame() indexes_df['rows'] = indexes[0] indexes_df['cols'] = indexes[1] mdf = indexes_df.groupby('rows').apply((lambda x: x['cols'].tolist())) max_len = mdf.apply((lambda x: len(x))).max() return mdf.apply...
class Wide(nn.Module): def __init__(self, input_dim: int, pred_dim: int): super().__init__() self.input_dim = input_dim self.pred_dim = pred_dim self.wide_linear = nn.Linear(input_dim, pred_dim) def forward(self, X): out = self.wide_linear(X.type(torch.float32)) ...
class SimpleEmbed(nn.Module): def __init__(self, vocab_size: int, embed_dim: int, pad_idx: int): super().__init__() self.vocab_size = vocab_size self.embed_dim = embed_dim self.pad_idx = pad_idx self.embed = nn.Embedding(vocab_size, embed_dim, padding_idx=pad_idx) def...
def download_images(df, out_path, id_col, img_col): download_error = [] counter = 0 for (idx, row) in tqdm(df.iterrows(), total=df.shape[0]): if (counter < 1000): img_path = str((out_path / '.'.join([str(row[id_col]), 'jpg']))) if os.path.isfile(img_path): c...
def get_coo_indexes(lil): rows = [] cols = [] for (i, el) in enumerate(lil): if (type(el) != list): el = [el] for j in el: rows.append(i) cols.append(j) return (rows, cols)
def get_sparse_features(series, shape): coo_indexes = get_coo_indexes(series.tolist()) sparse_df = coo_matrix((np.ones(len(coo_indexes[0])), (coo_indexes[0], coo_indexes[1])), shape=shape) return sparse_df
def sparse_to_idx(data, pad_idx=(- 1)): indexes = data.nonzero() indexes_df = pd.DataFrame() indexes_df['rows'] = indexes[0] indexes_df['cols'] = indexes[1] mdf = indexes_df.groupby('rows').apply((lambda x: x['cols'].tolist())) max_len = mdf.apply((lambda x: len(x))).max() return mdf.apply...
def idx_to_sparse(idx, sparse_dim): sparse = np.zeros(sparse_dim) sparse[int(idx)] = 1 return pd.Series(sparse, dtype=int)
def process_cats_as_kaggle_notebook(df): df['gender'] = (df['gender'] == 'M').astype(int) df = pd.concat([df.drop('occupation', axis=1), pd.get_dummies(df['occupation']).astype(int)], axis=1) df.drop('other', axis=1, inplace=True) df.drop('zip_code', axis=1, inplace=True) return df
class WideAndDeep(nn.Module): def __init__(self, continious_feature_shape, embed_size, embed_dict_len, pad_idx): super(WideAndDeep, self).__init__() self.embed = nn.Embedding(embed_dict_len, embed_size, padding_idx=pad_idx) self.linear_relu_stack = nn.Sequential(nn.Linear((embed_size + co...
def get_coo_indexes(lil): rows = [] cols = [] for (i, el) in enumerate(lil): if (type(el) != list): el = [el] for j in el: rows.append(i) cols.append(j) return (rows, cols)
def get_sparse_features(series, shape): coo_indexes = get_coo_indexes(series.tolist()) sparse_df = coo_matrix((np.ones(len(coo_indexes[0])), (coo_indexes[0], coo_indexes[1])), shape=shape) return sparse_df
def sparse_to_idx(data, pad_idx=(- 1)): indexes = data.nonzero() indexes_df = pd.DataFrame() indexes_df['rows'] = indexes[0] indexes_df['cols'] = indexes[1] mdf = indexes_df.groupby('rows').apply((lambda x: x['cols'].tolist())) max_len = mdf.apply((lambda x: len(x))).max() return mdf.apply...
class Wide(nn.Module): def __init__(self, input_dim: int, pred_dim: int): super().__init__() self.input_dim = input_dim self.pred_dim = pred_dim self.wide_linear = nn.Linear(input_dim, pred_dim) def forward(self, X): out = self.wide_linear(X.type(torch.float32)) ...
class SimpleEmbed(nn.Module): def __init__(self, vocab_size: int, embed_dim: int, pad_idx: int): super().__init__() self.vocab_size = vocab_size self.embed_dim = embed_dim self.pad_idx = pad_idx self.embed = nn.Embedding(vocab_size, embed_dim, padding_idx=pad_idx) def...
class MyDeepText(nn.Module): def __init__(self, vocab_size, padding_idx=1, embed_dim=100, hidden_dim=64): super(MyDeepText, self).__init__() self.hidden_dim = hidden_dim self.word_embed = nn.Embedding(vocab_size, embed_dim, padding_idx=padding_idx) self.rnn = nn.GRU(embed_dim, hid...
class RMSELoss(nn.Module): def __init__(self): 'root mean squared error' super().__init__() self.mse = nn.MSELoss() def forward(self, input: Tensor, target: Tensor) -> Tensor: return torch.sqrt(self.mse(input, target))
class Accuracy(Metric): def __init__(self, top_k: int=1): super(Accuracy, self).__init__() self.top_k = top_k self.correct_count = 0 self.total_count = 0 self._name = 'acc' def reset(self): self.correct_count = 0 self.total_count = 0 def __call__(...
class SillyCallback(Callback): def on_train_begin(self, logs=None): self.trainer.silly_callback = {} self.trainer.silly_callback['beginning'] = [] self.trainer.silly_callback['end'] = [] def on_epoch_begin(self, epoch, logs=None): self.trainer.silly_callback['beginning'].appe...
class MyDeepText(nn.Module): def __init__(self, vocab_size, padding_idx=1, embed_dim=100, hidden_dim=64): super(MyDeepText, self).__init__() self.hidden_dim = hidden_dim self.word_embed = nn.Embedding(vocab_size, embed_dim, padding_idx=padding_idx) self.rnn = nn.GRU(embed_dim, hid...
class RMSELoss(nn.Module): def __init__(self): 'root mean squared error' super().__init__() self.mse = nn.MSELoss() def forward(self, input: Tensor, target: Tensor) -> Tensor: return torch.sqrt(self.mse(input, target))