id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
39,401
import random import numpy as np import paddle from seqeval.metrics.sequence_labeling import get_entities def set_seed(seed): paddle.seed(seed) random.seed(seed) np.random.seed(seed)
null
39,402
import random import numpy as np import paddle from seqeval.metrics.sequence_labeling import get_entities def load_dict(dict_path): with open(dict_path, "r", encoding="utf-8") as f: words = [word.strip() for word in f.readlines()] word2id = dict(zip(words, range(len(words)))) id2word = dict...
null
39,403
import random import numpy as np import paddle from seqeval.metrics.sequence_labeling import get_entities def read_test_file(data_path): with open(data_path, "r", encoding="utf-8") as f: for line in f.readlines(): line = line.strip().replace(" ", "") yield {"text": line}
null
39,404
import argparse import copy import json import os import re from collections import defaultdict from functools import partial import paddle from datasets import Dataset, load_dataset from paddle import inference from seqeval.metrics.sequence_labeling import get_entities from paddlenlp.data import DataCollatorForTokenCl...
null
39,405
import argparse import copy import json import os import re from collections import defaultdict from functools import partial import paddle from datasets import Dataset, load_dataset from paddle import inference from seqeval.metrics.sequence_labeling import get_entities from paddlenlp.data import DataCollatorForTokenCl...
null
39,406
import argparse import copy import json import os import re from collections import defaultdict from functools import partial import paddle from datasets import Dataset, load_dataset from paddle import inference from seqeval.metrics.sequence_labeling import get_entities from paddlenlp.data import DataCollatorForTokenCl...
null
39,407
import argparse import copy import json import os import re from collections import defaultdict from functools import partial import paddle from datasets import Dataset, load_dataset from paddle import inference from seqeval.metrics.sequence_labeling import get_entities from paddlenlp.data import DataCollatorForTokenCl...
null
39,408
import argparse import copy import json import os import re from collections import defaultdict from functools import partial import paddle from datasets import Dataset, load_dataset from paddle import inference from seqeval.metrics.sequence_labeling import get_entities from paddlenlp.data import DataCollatorForTokenCl...
null
39,409
import argparse import copy import json import os import re from collections import defaultdict from functools import partial import paddle from datasets import Dataset, load_dataset from paddle import inference from seqeval.metrics.sequence_labeling import get_entities from paddlenlp.data import DataCollatorForTokenCl...
null
39,410
import argparse import os import random import warnings from functools import partial import numpy as np import paddle from data import convert_example_to_feature, load_dict from datasets import load_dataset from evaluate import evaluate from paddlenlp.data import DataCollatorForTokenClassification from paddlenlp.metri...
null
39,411
import argparse from functools import partial import paddle from data import convert_example_to_feature, load_dict from datasets import load_dataset from tqdm import tqdm from paddlenlp.data import DataCollatorForTokenClassification from paddlenlp.metrics import ChunkEvaluator from paddlenlp.transformers import SkepFor...
null
39,412
import argparse import copy import json import re from collections import defaultdict from functools import partial import paddle from classification.data import ( convert_example_to_feature as convert_example_to_feature_cls, ) from datasets import Dataset, load_dataset from extraction.data import convert_example_t...
null
39,413
import argparse import copy import json import re from collections import defaultdict from functools import partial import paddle from classification.data import ( convert_example_to_feature as convert_example_to_feature_cls, ) from datasets import Dataset, load_dataset from extraction.data import convert_example_t...
null
39,414
import argparse import copy import json import re from collections import defaultdict from functools import partial import paddle from classification.data import ( convert_example_to_feature as convert_example_to_feature_cls, ) from datasets import Dataset, load_dataset from extraction.data import convert_example_t...
null
39,415
import argparse import json import os import numpy as np from utils import concate_aspect_and_opinion, decoding, save_dict, save_examples def concate_aspect_and_opinion(text, aspect, opinions): aspect_text = "" for opinion in opinions: if text.find(aspect) <= text.find(opinion): aspect_text...
@Description: Consvert doccano file to data format which is suitable to input to this Application. @Param doccano_file: The annotated file exported from doccano labeling platform. @Param save_ext_dir: The directory of ext data that you wanna save. @Param save_cls_dir: The directory of cls data that you wanna save. @Par...
39,416
import argparse import re import paddle from utils import decoding, load_dict from paddlenlp.transformers import ( SkepForSequenceClassification, SkepForTokenClassification, SkepTokenizer, ) def concate_aspect_and_opinion(text, aspect, opinion_words): aspect_text = "" for opinion_word in opinion_wor...
null
39,417
import argparse import os import random import warnings from functools import partial import numpy as np import paddle from data import convert_example_to_feature, load_dict from datasets import load_dataset from evaluate import evaluate from paddlenlp.data import DataCollatorWithPadding from paddlenlp.metrics.glue imp...
null
39,418
def convert_example_to_feature(example, tokenizer, label2id, max_seq_len=512, is_test=False): example = example["text"].rstrip().split("\t") if not is_test: label = int(example[0]) aspect_text = example[1] text = example[2] encoded_inputs = tokenizer(aspect_text, text_pair=text...
null
39,419
import argparse from functools import partial import paddle from data import convert_example_to_feature, load_dict from datasets import load_dataset from tqdm import tqdm from paddlenlp.data import DataCollatorWithPadding from paddlenlp.metrics.glue import AccuracyAndF1 from paddlenlp.transformers import SkepForSequenc...
null
39,420
import argparse import os import random import warnings from functools import partial import numpy as np import paddle import paddle.nn.functional as F from data import convert_example_to_feature, load_dict from datasets import load_dataset from evaluate import evaluate from paddlenlp.data import DataCollatorWithPaddin...
null
39,421
import argparse from functools import partial import paddle from data import convert_example_to_feature, load_dict from datasets import load_dataset from paddlenlp.data import Pad from paddlenlp.transformers import PPMiniLMTokenizer import paddleslim def convert_example_to_feature(example, tokenizer, label2id, max_seq...
null
39,422
def load_dict(dict_path): with open(dict_path, "r", encoding="utf-8") as f: words = [word.strip() for word in f.readlines()] word2id = dict(zip(words, range(len(words)))) id2word = dict((v, k) for k, v in word2id.items()) return word2id, id2word
null
39,424
import argparse from functools import partial import paddle from data import convert_example_to_feature, load_dict from datasets import load_dataset from paddlenlp.data import DataCollatorWithPadding from paddlenlp.metrics.glue import AccuracyAndF1 from paddlenlp.transformers import PPMiniLMForSequenceClassification, P...
null
39,425
import argparse import os import random import time from functools import partial import numpy as np import paddle import paddle.nn.functional as F from data import convert_example, create_dataloader, read_data from paddlenlp.data import Pad, Stack, Tuple from paddlenlp.datasets import load_dataset from paddlenlp.train...
null
39,426
import json from paddle_serving_server.web_service import Op, WebService from scipy.special import softmax def convert_example(example, tokenizer, max_seq_length=512): query, title = example["query"], example["title"] encoded_inputs = tokenizer(text=query, text_pair=title, max_seq_len=max_seq_length) inp...
null
39,427
import argparse import os import sys import numpy as np import paddle from paddle import inference from scipy.special import softmax from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_dataset from paddlenlp.transformers import AutoTokenizer from paddlenlp.utils.log import logger The provided cod...
Reads data.
39,428
import argparse import os import sys import numpy as np import paddle from paddle import inference from scipy.special import softmax from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_dataset from paddlenlp.transformers import AutoTokenizer from paddlenlp.utils.log import logger def convert_exam...
null
39,429
import time import numpy as np from paddle_serving_client import Client from scipy.special import expit from paddlenlp.transformers import AutoTokenizer max_seq_len = 64 def convert_example(example, tokenizer, max_seq_length=512): query, title = example["query"], example["title"] encoded_inputs = tokenizer(te...
null
39,430
import time import numpy as np from paddle_serving_client.httpclient import HttpClient from scipy.special import expit from paddlenlp.transformers import AutoTokenizer max_seq_len = 64 def convert_example(example, tokenizer, max_seq_length=512): query, title = example["query"], example["title"] encoded_inputs...
null
39,431
import numpy as np import paddle The provided code snippet includes necessary dependencies for implementing the `convert_example` function. Write a Python function `def convert_example(example, tokenizer, max_seq_length=512, is_test=False, is_pair=False)` to solve the following problem: Builds model inputs from a sequ...
Builds model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. And creates a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` It re...
39,432
import numpy as np import paddle The provided code snippet includes necessary dependencies for implementing the `read_text_pair` function. Write a Python function `def read_text_pair(data_path)` to solve the following problem: Reads data. Here is the function: def read_text_pair(data_path): """Reads data.""" ...
Reads data.
39,433
import numpy as np import paddle The provided code snippet includes necessary dependencies for implementing the `read_data` function. Write a Python function `def read_data(data_path)` to solve the following problem: Reads data. Here is the function: def read_data(data_path): """Reads data.""" with open(data...
Reads data.
39,435
import argparse import os from functools import partial import paddle import paddle.nn.functional as F from data import convert_example, create_dataloader, read_text_pair from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_dataset from paddlenlp.transformers import AutoModelForSequenceClassificati...
null
39,436
import argparse import os import random from functools import partial import numpy as np import paddle import paddle.nn.functional as F from data import convert_example, create_dataloader, read_data from paddlenlp.data import Pad, Stack, Tuple from paddlenlp.datasets import load_dataset from paddlenlp.transformers impo...
sets random seed
39,437
import argparse import os import random from functools import partial import numpy as np import paddle import paddle.nn.functional as F from data import convert_example, create_dataloader, read_data from paddlenlp.data import Pad, Stack, Tuple from paddlenlp.datasets import load_dataset from paddlenlp.transformers impo...
Given a dataset, it evals model and computes the metric. Args: model(obj:`paddle.nn.Layer`): A model to classify texts. data_loader(obj:`paddle.io.DataLoader`): The dataset loader which generates batches. metric(obj:`paddle.metric.Metric`): The evaluation metric.
39,438
import argparse import os import random import time from functools import partial import numpy as np import paddle import pandas as pd from data import convert_pairwise_example as convert_example from data import create_dataloader from model import PairwiseMatching from tqdm import tqdm from paddlenlp.data import Pad, ...
null
39,439
import json from paddle_serving_server.web_service import Op, WebService def convert_example(example, tokenizer, max_seq_length=512): query, title = example["query"], example["title"] encoded_inputs = tokenizer(text=query, text_pair=title, max_seq_len=max_seq_length) input_ids = encoded_inputs["input_ids...
null
39,440
import argparse import os import sys import numpy as np import paddle from paddle import inference from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_dataset from paddlenlp.transformers import AutoTokenizer from paddlenlp.utils.log import logger The provided code snippet includes necessary depen...
Reads data.
39,441
import argparse import os import sys import numpy as np import paddle from paddle import inference from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_dataset from paddlenlp.transformers import AutoTokenizer from paddlenlp.utils.log import logger def convert_example(example, tokenizer, max_seq_le...
null
39,442
import time import numpy as np from paddle_serving_client import Client import paddlenlp as ppnlp max_seq_len = 64 def convert_example(example, tokenizer, max_seq_length=512): query, title = example["query"], example["title"] encoded_inputs = tokenizer(text=query, text_pair=title, max_seq_len=max_seq_length) ...
null
39,443
import time import numpy as np from paddle_serving_client.httpclient import HttpClient import paddlenlp as ppnlp max_seq_len = 64 def convert_example(example, tokenizer, max_seq_length=512): query, title = example["query"], example["title"] encoded_inputs = tokenizer(text=query, text_pair=title, max_seq_len=m...
null
39,445
import paddle import numpy as np from paddlenlp.datasets import MapDataset The provided code snippet includes necessary dependencies for implementing the `read_text_pair` function. Write a Python function `def read_text_pair(data_path)` to solve the following problem: Reads data. Here is the function: def read_text_...
Reads data.
39,448
import paddle import numpy as np from paddlenlp.datasets import MapDataset The provided code snippet includes necessary dependencies for implementing the `gen_pair` function. Write a Python function `def gen_pair(dataset, pool_size=100)` to solve the following problem: Generate triplet randomly based on dataset Args: ...
Generate triplet randomly based on dataset Args: dataset: A `MapDataset` or `IterDataset` or a tuple of those. Each example is composed of 2 texts: example["query"], example["title"] pool_size: the number of example to sample negative example randomly Return: dataset: A `MapDataset` or `IterDataset` or a tuple of those...
39,449
import argparse import os from functools import partial import numpy as np import paddle from data import convert_pairwise_example as convert_example from data import create_dataloader, read_text_pair from model import PairwiseMatching from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_dataset fr...
Predicts the data labels. Args: model (obj:`SemanticIndexBase`): A model to extract text embedding or calculate similarity of text pair. data_loader (obj:`List(Example)`): The processed data ids of text pair: [query_input_ids, query_token_type_ids, title_input_ids, title_token_type_ids] Returns: results(obj:`List`): co...
39,450
import argparse import os import random from functools import partial import numpy as np import paddle import pandas as pd from data import convert_pairwise_example as convert_example from data import create_dataloader from model import PairwiseMatching from tqdm import tqdm from paddlenlp.data import Pad, Stack, Tuple...
sets random seed
39,451
import argparse import os import random from functools import partial import numpy as np import paddle import pandas as pd from data import convert_pairwise_example as convert_example from data import create_dataloader from model import PairwiseMatching from tqdm import tqdm from paddlenlp.data import Pad, Stack, Tuple...
Given a dataset, it evals model and computes the metric. Args: model(obj:`paddle.nn.Layer`): A model to classify texts. data_loader(obj:`paddle.io.DataLoader`): The dataset loader which generates batches. metric(obj:`paddle.metric.Metric`): The evaluation metric.
39,452
import argparse import os import random from functools import partial import numpy as np import paddle import pandas as pd from data import convert_pairwise_example as convert_example from data import create_dataloader from model import PairwiseMatching from tqdm import tqdm from paddlenlp.data import Pad, Stack, Tuple...
null
39,453
import argparse import os import random from functools import partial import numpy as np import paddle import pandas as pd from data import convert_pairwise_example as convert_example from data import create_dataloader from model import PairwiseMatching from tqdm import tqdm from paddlenlp.data import Pad, Stack, Tuple...
null
39,454
import argparse import os import sys import numpy as np import paddle from paddle import inference from tqdm import tqdm from paddlenlp.data import Pad, Tuple from paddlenlp.transformers import AutoTokenizer from data import convert_example def read_text(file_path): file = open(file_path) id2corpus = {} fo...
null
39,455
import os from functools import partial import paddle from base_model import SemanticIndexBaseStatic from config import collection_name, embedding_name, partition_tag from data import convert_example, create_dataloader from milvus_util import RecallByMilvus from paddlenlp.data import Pad, Tuple from paddlenlp.datasets ...
null
39,456
import os import paddle from paddlenlp.utils.log import logger def create_dataloader(dataset, mode="train", batch_size=1, batchify_fn=None, trans_fn=None): if trans_fn: dataset = dataset.map(trans_fn) shuffle = True if mode == "train" else False if mode == "train": batch_sampler = paddle.io...
null
39,457
import os import paddle from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the `convert_example` function. Write a Python function `def convert_example(example, tokenizer, max_seq_length=512, pad_to_max_seq_len=False)` to solve the following problem: Build...
Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Args: example(obj:`list(str)`): The list of text to be converted to ids. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer` which conta...
39,458
import os import paddle from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the `read_text_pair` function. Write a Python function `def read_text_pair(data_path)` to solve the following problem: Reads data. Here is the function: def read_text_pair(data_pa...
Reads data.
39,459
import os import paddle from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the `read_text_triplet` function. Write a Python function `def read_text_triplet(data_path)` to solve the following problem: Reads data. Here is the function: def read_text_triple...
Reads data.
39,460
import os import paddle from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the `get_latest_checkpoint` function. Write a Python function `def get_latest_checkpoint(args)` to solve the following problem: Return: (latest_checkpoint_path, global_step) Here i...
Return: (latest_checkpoint_path, global_step)
39,461
import os import paddle from paddlenlp.utils.log import logger logger = Logger() def get_latest_ann_data(ann_data_dir): if not os.path.exists(ann_data_dir): return None, -1 subdirectories = list(next(os.walk(ann_data_dir))[1]) def valid_checkpoint(step): ann_data_file = os.path.join(ann_...
null
39,462
import os import paddle from paddlenlp.utils.log import logger def gen_id2corpus(corpus_file): id2corpus = {} with open(corpus_file, "r", encoding="utf-8") as f: for idx, line in enumerate(f): id2corpus[idx] = line.rstrip() return id2corpus
null
39,463
import os import paddle from paddlenlp.utils.log import logger def gen_text_file(similar_text_pair_file): text2similar_text = {} texts = [] with open(similar_text_pair_file, "r", encoding="utf-8") as f: for line in f: splited_line = line.rstrip().split("\t") if len(splited_l...
null
39,464
import argparse import time import numpy as np from config import collection_name, embedding_name, partition_tag from milvus_util import RecallByMilvus, VecToMilvus, text_max_len from tqdm import tqdm def read_text(file_path): file = open(file_path) id2corpus = [] for idx, data in enumerate(file.readlines()...
null
39,465
import argparse import time import numpy as np from config import collection_name, embedding_name, partition_tag from milvus_util import RecallByMilvus, VecToMilvus, text_max_len from tqdm import tqdm collection_name = "multi_label" partition_tag = "partition_2" embedding_name = "embeddings" class RecallByMilvus: ...
null
39,466
import logging from paddle_serving_server.web_service import Op, WebService def convert_example(example, tokenizer, max_seq_length=512, pad_to_max_seq_len=False): result = [] for text in example: encoded_inputs = tokenizer(text=text, max_seq_len=max_seq_length, pad_to_max_seq_len=pad_to_max_seq_len) ...
null
39,467
import argparse import os import sys import paddle from paddle import inference from scipy import spatial from paddlenlp.data import Pad, Tuple from paddlenlp.transformers import AutoTokenizer from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the `convert...
Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Args: example(obj:`list(str)`): The list of text to be converted to ids. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer` which conta...
39,468
import time import numpy as np from paddle_serving_client import Client from paddlenlp.transformers import AutoTokenizer max_seq_len = 64 def convert_example(example, tokenizer, max_seq_length=512, pad_to_max_seq_len=True): list_input_ids = [] list_token_type_ids = [] for text in example: encoded_i...
null
39,469
import time import numpy as np from paddle_serving_client import HttpClient from paddlenlp.transformers import AutoTokenizer max_seq_len = 64 def convert_example(example, tokenizer, max_seq_length=512, pad_to_max_seq_len=True): list_input_ids = [] list_token_type_ids = [] for text in example: encod...
null
39,479
import numpy as np import hnswlib from paddlenlp.utils.log import logger logger = Logger() def build_index(args, data_loader, model): index = hnswlib.Index(space="ip", dim=args.output_emb_size if args.output_emb_size > 0 else 768) # Initializing index # max_elements - the maximum number of elements (cap...
null
39,480
import argparse import os import random import time from functools import partial import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from ann_util import build_index from batch_negative.model import SemanticIndexBatchNeg, SemanticIndexCacheNeg from data import ( convert_example...
null
39,482
import argparse import os import random import time from functools import partial import numpy as np import paddle from data import convert_example, create_dataloader, read_simcse_text from model import SimCSE from visualdl import LogWriter from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_datas...
null
39,483
import argparse import os import sys import paddle from paddle import inference from scipy import spatial from paddlenlp.data import Pad, Tuple from paddlenlp.transformers import AutoTokenizer from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the `convert...
Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Args: example(obj:`list(str)`): The list of text to be converted to ids. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer` which conta...
39,484
import os from functools import partial import paddle from data import create_dataloader from model import SimCSE from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import MapDataset from paddlenlp.transformers import AutoModel, AutoTokenizer The provided code snippet includes necessary dependencies for imp...
Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Args: example(obj:`list(str)`): The list of text to be converted to ids. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer` which conta...
39,486
import paddle The provided code snippet includes necessary dependencies for implementing the `convert_example_test` function. Write a Python function `def convert_example_test(example, tokenizer, max_seq_length=512, pad_to_max_seq_len=False)` to solve the following problem: Builds model inputs from a sequence. A BERT ...
Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Args: example(obj:`list(str)`): The list of text to be converted to ids. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer` which conta...
39,487
import paddle The provided code snippet includes necessary dependencies for implementing the `convert_example` function. Write a Python function `def convert_example(example, tokenizer, max_seq_length=512, do_evalute=False)` to solve the following problem: Builds model inputs from a sequence. A BERT sequence has the f...
Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Args: example(obj:`list(str)`): The list of text to be converted to ids. tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer` which conta...
39,488
import paddle def gen_id2corpus(corpus_file): id2corpus = {} with open(corpus_file, "r", encoding="utf-8") as f: for idx, line in enumerate(f): id2corpus[idx] = line.rstrip() return id2corpus
null
39,489
import paddle def gen_text_file(similar_text_pair_file): text2similar_text = {} texts = [] with open(similar_text_pair_file, "r", encoding="utf-8") as f: for line in f: splited_line = line.rstrip().split("\t") if len(splited_line) != 2: continue ...
null
39,490
import paddle The provided code snippet includes necessary dependencies for implementing the `read_simcse_text` function. Write a Python function `def read_simcse_text(data_path)` to solve the following problem: Reads data. Here is the function: def read_simcse_text(data_path): """Reads data.""" with open(da...
Reads data.
39,491
import paddle The provided code snippet includes necessary dependencies for implementing the `read_text_pair` function. Write a Python function `def read_text_pair(data_path, is_test=False)` to solve the following problem: Reads data. Here is the function: def read_text_pair(data_path, is_test=False): """Reads d...
Reads data.
39,492
import argparse import os from functools import partial import numpy as np import paddle from data import convert_example, create_dataloader, read_text_pair from model import SimCSE from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import load_dataset from paddlenlp.transformers import AutoModel, AutoTokeni...
Predicts the data labels. Args: model (obj:`SimCSE`): A model to extract text embedding or calculate similarity of text pair. data_loader (obj:`List(Example)`): The processed data ids of text pair: [query_input_ids, query_token_type_ids, title_input_ids, title_token_type_ids] Returns: results(obj:`List`): cosine simila...
39,493
import numpy as np import hnswlib from paddlenlp.utils.log import logger logger = Logger() def build_index(args, data_loader, model): index = hnswlib.Index(space="ip", dim=args.output_emb_size) # Initializing index # max_elements - the maximum number of elements (capacity). Will throw an exception if ex...
null
39,495
import sys import time import numpy as np import pandas as pd from paddle_serving_server.pipeline import PipelineClient from config import collection_name, embedding_name, partition_tag from milvus_util import RecallByMilvus def recall_result(list_data): client = PipelineClient() client.connect(["127.0.0.1:80...
null
39,496
import sys import time import numpy as np import pandas as pd from paddle_serving_server.pipeline import PipelineClient from config import collection_name, embedding_name, partition_tag from milvus_util import RecallByMilvus collection_name = "multi_label" partition_tag = "partition_2" embedding_name = "embeddings" ...
null
39,497
import sys import time import numpy as np import pandas as pd from paddle_serving_server.pipeline import PipelineClient from config import collection_name, embedding_name, partition_tag from milvus_util import RecallByMilvus def rerank(df): client = PipelineClient() client.connect(["127.0.0.1:8089"]) list...
null
39,504
import random from functools import partial import numpy as np import paddle import paddle.distributed as dist from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler from paddlenlp.data import Pad def convert_example( example, tokenizer, max_seq_len=512, max_target_len=128, max_title_len=256, mode=...
null
39,505
import random from functools import partial import numpy as np import paddle import paddle.distributed as dist from paddle.io import BatchSampler, DataLoader, DistributedBatchSampler from paddlenlp.data import Pad def post_process_sum(token_ids, tokenizer): def remove_template(instr): def select_sum(ids, scores, token...
null
39,506
import json import math import random import re import numpy as np import paddle from tqdm import tqdm from paddlenlp.utils.log import logger def set_seed(seed): paddle.seed(seed) random.seed(seed) np.random.seed(seed)
null
39,507
import json import math import random import re import numpy as np import paddle from tqdm import tqdm from paddlenlp.utils.log import logger def map_offset(ori_offset, offset_mapping): """ map ori offset to token offset """ for index, span in enumerate(offset_mapping): if span[0] <= ori_offset ...
example: { title prompt content result_list }
39,508
import json import math import random import re import numpy as np import paddle from tqdm import tqdm from paddlenlp.utils.log import logger The provided code snippet includes necessary dependencies for implementing the `reader` function. Write a Python function `def reader(data_path, max_seq_len=512)` to solve the f...
read json
39,509
import json import math import random import re import numpy as np import paddle from tqdm import tqdm from paddlenlp.utils.log import logger def unify_prompt_name(prompt): # The classification labels are shuffled during finetuning, so they need # to be unified during evaluation. if re.search(r"\[.*?\]$", ...
null
39,510
import json import math import random import re import numpy as np import paddle from tqdm import tqdm from paddlenlp.utils.log import logger def generate_cls_example(text, labels, prompt_prefix, options): random.shuffle(options) cls_options = ",".join(options) prompt = prompt_prefix + "[" + cls_options + "...
Convert labeled data export from doccano for classification task.
39,511
import json import math import random import re import numpy as np import paddle from tqdm import tqdm from paddlenlp.utils.log import logger def add_negative_example(examples, texts, prompts, label_set, negative_ratio): negative_examples = [] positive_examples = [] with tqdm(total=len(prompts)) as pbar: ...
Convert labeled data export from doccano for extraction and aspect-level classification task.
39,512
import argparse import os import time from functools import partial import paddle from evaluate import evaluate from utils import convert_example, reader, set_seed from paddlenlp.datasets import load_dataset from paddlenlp.metrics import SpanEvaluator from paddlenlp.transformers import UIE, AutoTokenizer from paddlenlp...
null
39,513
import argparse from functools import partial import paddle from utils import convert_example, reader, unify_prompt_name from paddlenlp.datasets import MapDataset, load_dataset from paddlenlp.metrics import SpanEvaluator from paddlenlp.transformers import UIE, AutoTokenizer from paddlenlp.utils.log import logger def ev...
null
39,514
import argparse import os from pprint import pprint from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import ( AnswerExtractor, DensePassageRetriever, ErnieRanker, QAFilter, QuestionGenerator, ) from pipelines.pipelines import QAGenerationPipeline, SemanticSearchPipeline ...
null
39,515
import argparse import os from pprint import pprint from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import ( AnswerExtractor, DensePassageRetriever, ErnieRanker, QAFilter, QuestionGenerator, ) from pipelines.pipelines import QAGenerationPipeline, SemanticSearchPipeline ...
null
39,516
import argparse import json import os from tqdm import tqdm from paddlenlp import Taskflow def parse_args(): parser = argparse.ArgumentParser(__doc__) parser.add_argument('--answer_generation_model_path', type=str, default=None, help='the model path to be loaded for answer extraction') parser.add_argument(...
null
39,517
import argparse import json import os from tqdm import tqdm from paddlenlp import Taskflow The provided code snippet includes necessary dependencies for implementing the `answer_generation_from_paragraphs` function. Write a Python function `def answer_generation_from_paragraphs( paragraphs, batch_size=16, model=No...
Generate answer from given paragraphs.
39,518
import argparse import json import os from tqdm import tqdm from paddlenlp import Taskflow def create_fake_question( json_file_or_pair_list, out_json=None, num_return_sequences=1, all_sample_num=None, batch_size=8 ): if out_json: wf = open(out_json, "w", encoding="utf-8") if isinstance(json_file_or...
null
39,519
import argparse import json import os from tqdm import tqdm from paddlenlp import Taskflow def filtration(paragraphs, batch_size=16, model=None, schema=None, wf=None, wf_debug=None): result = [] buffer = [] valid_num, invalid_num = 0, 0 i = 0 len_paragraphs = len(paragraphs) for paragraph_tobe ...
null
39,520
import argparse import json import os def parse_args(): parser = argparse.ArgumentParser(__doc__) parser.add_argument('--source_file_path', type=str, default=None, help='the source json file path') parser.add_argument('--target_dir', type=str, default='data', help='the target file path') parser.add_arg...
null
39,521
import argparse import json import os def convert_from_json_to_answer_extraction_format( json_file, output_path, domain=None, do_answer_prompt=True, do_len_prompt=False, do_domain_prompt=False ): with open(json_file, "r", encoding="utf-8") as rf, open(output_path, "w", encoding="utf-8") as wf: for line...
null
39,522
import argparse import json import os def convert_from_json_to_question_generation_format(json_file, output_path, tokenizer=None): with open(json_file, "r", encoding="utf-8") as rf, open(output_path, "w", encoding="utf-8") as wf: for line in rf: json_line = json.loads(line) context ...
null
39,523
import argparse import json import os def convert_from_json_to_filtration_format(json_file, output_path, tokenizer=None): with open(json_file, "r", encoding="utf-8") as rf, open(output_path, "w", encoding="utf-8") as wf: for line in rf: json_line = json.loads(line) context = json_li...
null