id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
39,524
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_path', type=str, default=None, help='the target dir path') parser.add_a...
null
39,525
import argparse import json import os def convert_json_to_data(json_file, out_dir, test_sample_num, train_sample_num, all_sample_num=None): with open(json_file, "r", encoding="utf-8") as rf, open( os.path.join(out_dir, "qa_pair.csv"), "w", encoding="utf-8" ) as qa_pair_wf, open(os.path.join(out_dir, "q...
null
39,526
import json def json_format_indent(json_file, output_json): with open(output_json, "w", encoding="utf-8") as wf: with open(json_file, "r", encoding="utf-8") as rf: all_lines = [] for json_line in rf: line_dict = json.loads(json_line) all_lines.append(...
null
39,527
import argparse import json import multiprocessing import os import time from tqdm import tqdm from tqdm.contrib import tzip from paddlenlp.metrics import BLEU from paddlenlp.transformers import BasicTokenizer def parse_args(): parser = argparse.ArgumentParser(__doc__) parser.add_argument('--true_file_path', t...
null
39,528
import argparse import json import multiprocessing import os import time from tqdm import tqdm from tqdm.contrib import tzip from paddlenlp.metrics import BLEU from paddlenlp.transformers import BasicTokenizer def calc_bleu_n(preds, targets, n_size=4): assert len(preds) == len(targets), ( "The length of pre...
null
39,529
import argparse import json from tqdm import tqdm from paddlenlp import Taskflow def parse_args(): parser = argparse.ArgumentParser(__doc__) parser.add_argument('--model_path', type=str, default=None, help='the model path to be loaded for question_generation taskflow') parser.add_argument('--max_length', t...
null
39,530
import argparse import json from tqdm import tqdm from paddlenlp import Taskflow def create_fake_question(json_file, out_json, num_return_sequences, all_sample_num=None, batch_size=8): with open(json_file, "r", encoding="utf-8") as rf, open(out_json, "w", encoding="utf-8") as wf: all_lines = rf.readlines()...
null
39,531
import argparse import json import os def parse_args(): parser = argparse.ArgumentParser(__doc__) parser.add_argument("--do_create_test_qq_pair", action='store_true', help="Whether to do create_test_qq_pair") parser.add_argument('--qq_pair_source_ori_file_path', type=str, default=None, help='the original s...
null
39,532
import argparse import json import os def extract_q_from_json_file(json_file, out_file=None, test_sample_num=None, query_answer_path=None): with open(json_file, "r", encoding="utf-8") as rf: if out_file: wf = open(os.path.join(out_file), "w", encoding="utf-8") if query_answer_path: ...
null
39,533
import argparse import json from tqdm import tqdm from paddlenlp import Taskflow def parse_args(): parser = argparse.ArgumentParser(__doc__) parser.add_argument('--model_path', type=str, default=None, help='the model path to be loaded for question_generation taskflow') parser.add_argument('--source_file_pa...
null
39,534
import argparse import json 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=None, wf=None)` t...
Generate answer from given paragraphs.
39,535
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, read_text_pair, word_repetition, ) from model import SimCSE from scipy import stats from paddlenlp.data import P...
null
39,536
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, read_text_pair, word_repetition, ) from model import SimCSE from scipy import stats from paddlenlp.data import P...
null
39,537
import argparse import os 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 The provided code snippet includes necessary dependencies for implementing the `convert_example` function. Write a Python ...
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,538
import argparse import os 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 def read_text(file_path): file = open(file_path) id2corpus = {} for idx, data in enumerate(file.readlines()): ...
null
39,539
import argparse import os from functools import partial import paddle from ann_util import build_index from data import convert_example_test, create_dataloader, gen_id2corpus, gen_text_file from model import SimCSE from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import MapDataset from paddlenlp.transforme...
null
39,540
import argparse 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,541
import argparse from paddle_serving_server.web_service import 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,542
import random import numpy as np 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,543
import random import numpy as np import paddle 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.DistributedBat...
null
39,544
import random 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, do_evalute=False)` to solve the following problem: Builds model inputs from a se...
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,545
import random import numpy as np 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 mode...
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,546
import random import numpy as np 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.
39,547
import random 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, is_test=False)` to solve the following problem: Reads data. Here is the function: def read_text_pair(data_pat...
Reads data.
39,548
import random import numpy as np 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: ...
null
39,549
import random import numpy as np import paddle The provided code snippet includes necessary dependencies for implementing the `word_repetition` function. Write a Python function `def word_repetition(input_ids, token_type_ids, dup_rate=0.32)` to solve the following problem: Word Repetition strategy. Here is the functi...
Word Repetition strategy.
39,550
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,551
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,552
import hnswlib import numpy as np 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,553
import time import numpy as np import pandas as pd from config import collection_name, embedding_name, partition_tag from milvus_util import RecallByMilvus from paddle_serving_server.pipeline import PipelineClient def recall_result(list_data): client = PipelineClient() client.connect(["127.0.0.1:8080"]) fe...
null
39,554
import time import numpy as np import pandas as pd from config import collection_name, embedding_name, partition_tag from milvus_util import RecallByMilvus from paddle_serving_server.pipeline import PipelineClient collection_name = "multi_label" partition_tag = "partition_2" embedding_name = "embeddings" class Recal...
null
39,556
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, word_repetition from model import SimCSE from scipy import stats from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import ...
null
39,557
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, word_repetition from model import SimCSE from scipy import stats from paddlenlp.data import Pad, Tuple from paddlenlp.datasets import ...
null
39,561
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) input_ids...
null
39,567
import random 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, is_test=False)` to solve the following problem: Reads data. Here is the function: def read_text_pair(data_pat...
Reads data.
39,570
import numpy as np from milvus_util import VecToMilvus from tqdm import tqdm class VecToMilvus: def __init__(self): self.client = Milvus(host=MILVUS_HOST, port=MILVUS_PORT) def has_collection(self, collection_name): try: status, ok = self.client.has_collection(collection_name) ...
null
39,572
import time import numpy as np import pandas as pd from data import gen_id2corpus from milvus_util import RecallByMilvus from paddle_serving_server.pipeline import PipelineClient def gen_id2corpus(corpus_file): id2corpus = {} with open(corpus_file, "r", encoding="utf-8") as f: for idx, line in enumerat...
null
39,574
import json import math import random import time from urllib.error import URLError from urllib.parse import urlencode from urllib.request import Request, urlopen import numpy as np import paddle from tqdm import tqdm def set_seed(seed): paddle.seed(seed) random.seed(seed) np.random.seed(seed)
null
39,575
import json import math import random import time from urllib.error import URLError from urllib.parse import urlencode from urllib.request import Request, urlopen import numpy as np import paddle from tqdm import tqdm class ASRError(Exception): pass The provided code snippet includes necessary dependencies for imp...
Mandarin ASR Args: audio_file (str): Audio file of Mandarin with sampling rate 16000. audio_format (str): The file extension of audio_file, 'wav' by default. Please refer to https://github.com/Baidu-AIP/speech-demo for more demos.
39,576
import json import math import random import time from urllib.error import URLError from urllib.parse import urlencode from urllib.request import Request, urlopen import numpy as np import paddle from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `evaluate` function. W...
Given a dataset, it evals model and computes the metric. Args: model(obj:`paddle.nn.Layer`): A model to classify texts. metric(obj:`paddle.metric.Metric`): The evaluation metric. data_loader(obj:`paddle.io.DataLoader`): The dataset loader which generates batches.
39,577
import json import math import random import time from urllib.error import URLError from urllib.parse import urlencode from urllib.request import Request, urlopen import numpy as np import paddle from tqdm import tqdm def map_offset(ori_offset, offset_mapping): """ map ori offset to token offset """ for...
example: { title prompt content result_list }
39,578
import json import math import random import time from urllib.error import URLError from urllib.parse import urlencode from urllib.request import Request, urlopen import numpy as np import paddle from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `reader` function. Wri...
read json
39,579
import json import math import random import time from urllib.error import URLError from urllib.parse import urlencode from urllib.request import Request, urlopen import numpy as np import paddle from tqdm import tqdm def add_negative_example(examples, texts, prompts, label_set, negative_ratio): with tqdm(total=len...
null
39,580
import json import math import random import time from urllib.error import URLError from urllib.parse import urlencode from urllib.request import Request, urlopen import numpy as np import paddle from tqdm import tqdm def create_dataloader(dataset, mode="train", batch_size=1, batchify_fn=None, trans_fn=None): if t...
null
39,581
import argparse import os import time from functools import partial import paddle from utils import convert_example, create_dataloader, evaluate, reader, set_seed from paddlenlp.datasets import load_dataset from paddlenlp.metrics import SpanEvaluator from paddlenlp.transformers import UIE, AutoTokenizer def set_seed(s...
null
39,582
import os import time import argparse import json import numpy as np from utils import set_seed, convert_ext_examples def set_seed(seed): def convert_ext_examples( raw_examples, negative_ratio, prompt_prefix="情感倾向", options=["正向", "负向"], separator="##", is_train=True, ...
null
39,583
import io import os import setuptools with open("requirements.txt") as fin: REQUIRED_PACKAGES = fin.read() def read(*names, **kwargs): with io.open(os.path.join(os.path.dirname(__file__), *names), encoding=kwargs.get("encoding", "utf8")) as fp: return fp.read()
null
39,584
import json import logging import os import shutil import uuid from pathlib import Path from typing import List, Optional from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile from fastapi.responses import FileResponse from pydantic import BaseModel from rest_api.config import ( FILE_PARSE_P...
You can use this endpoint to upload a file for indexing
39,585
import json import logging import os import shutil import uuid from pathlib import Path from typing import List, Optional from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile from fastapi.responses import FileResponse from pydantic import BaseModel from rest_api.config import ( FILE_PARSE_P...
You can use this endpoint to upload a file for indexing
39,586
import json import logging import os import shutil import uuid from pathlib import Path from typing import List, Optional from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile from fastapi.responses import FileResponse from pydantic import BaseModel from rest_api.config import ( FILE_PARSE_P...
null
39,587
import json import logging import os import shutil import uuid from pathlib import Path from typing import List, Optional from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile from fastapi.responses import FileResponse from pydantic import BaseModel from rest_api.config import ( FILE_PARSE_P...
null
39,588
import json import logging import shutil import time import uuid from pathlib import Path from typing import Any, Dict, List, Optional from fastapi import APIRouter, File, Form, UploadFile from numpy import ndarray from pydantic import BaseConfig from rest_api.config import ( CONCURRENT_REQUEST_PER_WORKER, FILE...
This endpoint can be used during startup to understand if the server is ready to take any requests, or is still loading. The recommended approach is to call this endpoint with a short timeout, like 500ms, and in case of no reply, consider the server busy.
39,589
import json import logging import shutil import time import uuid from pathlib import Path from typing import Any, Dict, List, Optional from fastapi import APIRouter, File, Form, UploadFile from numpy import ndarray from pydantic import BaseConfig from rest_api.config import ( CONCURRENT_REQUEST_PER_WORKER, FILE...
Get the running pipelines version.
39,590
import json import logging import shutil import time import uuid from pathlib import Path from typing import Any, Dict, List, Optional from fastapi import APIRouter, File, Form, UploadFile from numpy import ndarray from pydantic import BaseConfig from rest_api.config import ( CONCURRENT_REQUEST_PER_WORKER, FILE...
This endpoint receives the question as a string and allows the requester to set additional parameters that will be passed on to the pipelines pipeline.
39,591
import json import logging import shutil import time import uuid from pathlib import Path from typing import Any, Dict, List, Optional from fastapi import APIRouter, File, Form, UploadFile from numpy import ndarray from pydantic import BaseConfig from rest_api.config import ( CONCURRENT_REQUEST_PER_WORKER, FILE...
This endpoint receives the question as a string and allows the requester to set additional parameters that will be passed on to the pipelines pipeline.
39,592
import json import logging import shutil import time import uuid from pathlib import Path from typing import Any, Dict, List, Optional from fastapi import APIRouter, File, Form, UploadFile from numpy import ndarray from pydantic import BaseConfig from rest_api.config import ( CONCURRENT_REQUEST_PER_WORKER, FILE...
This endpoint receives the question as a string and allows the requester to set additional parameters that will be passed on to the pipelines pipeline.
39,593
import json import logging import shutil import time import uuid from pathlib import Path from typing import Any, Dict, List, Optional from fastapi import APIRouter, File, Form, UploadFile from numpy import ndarray from pydantic import BaseConfig from rest_api.config import ( CONCURRENT_REQUEST_PER_WORKER, FILE...
This endpoint receives the question as a string and allows the requester to set additional parameters that will be passed on to the pipelines pipeline.
39,594
import json import logging import shutil import time import uuid from pathlib import Path from typing import Any, Dict, List, Optional from fastapi import APIRouter, File, Form, UploadFile from numpy import ndarray from pydantic import BaseConfig from rest_api.config import ( CONCURRENT_REQUEST_PER_WORKER, FILE...
This endpoint receives the question as a string and allows the requester to set additional parameters that will be passed on to the pipelines pipeline.
39,595
import json import logging import shutil import time import uuid from pathlib import Path from typing import Any, Dict, List, Optional from fastapi import APIRouter, File, Form, UploadFile from numpy import ndarray from pydantic import BaseConfig from rest_api.config import ( CONCURRENT_REQUEST_PER_WORKER, FILE...
This endpoint receives the question as a string and allows the requester to set additional parameters that will be passed on to the pipelines pipeline.
39,596
from typing import Dict, Union, Optional import json import logging from fastapi import APIRouter from pipelines.schema import Label from rest_api.schema import FilterRequest, LabelSerialized, CreateLabelSerialized from rest_api.controller.search import DOCUMENT_STORE class LabelSerialized(Label, BaseModel): docum...
This endpoint allows the API user to submit feedback on an answer for a particular query. For example, the user can send feedback on whether the answer was correct and whether the right snippet was identified as the answer. Information submitted through this endpoint is used to train the underlying QA model.
39,597
from typing import Dict, Union, Optional import json import logging from fastapi import APIRouter from pipelines.schema import Label from rest_api.schema import FilterRequest, LabelSerialized, CreateLabelSerialized from rest_api.controller.search import DOCUMENT_STORE DOCUMENT_STORE = PIPELINE.get_document_store() Th...
This endpoint allows the API user to retrieve all the feedback that has been submitted through the `POST /feedback` endpoint.
39,598
from typing import Dict, Union, Optional import json import logging from fastapi import APIRouter from pipelines.schema import Label from rest_api.schema import FilterRequest, LabelSerialized, CreateLabelSerialized from rest_api.controller.search import DOCUMENT_STORE DOCUMENT_STORE = PIPELINE.get_document_store() Th...
This endpoint allows the API user to delete all the feedback that has been sumbitted through the `POST /feedback` endpoint
39,599
from typing import Dict, Union, Optional import json import logging from fastapi import APIRouter from pipelines.schema import Label from rest_api.schema import FilterRequest, LabelSerialized, CreateLabelSerialized from rest_api.controller.search import DOCUMENT_STORE class FilterRequest(BaseModel): filters: Optio...
This endpoint returns basic accuracy metrics based on user feedback, e.g., the ratio of correct answers or correctly identified documents. You can filter the output by document or label. Example: `curl --location --request POST 'http://127.0.0.1:8000/eval-doc-qa-feedback' \ --header 'Content-Type: application/json' \ -...
39,600
from typing import Dict, Union, Optional import json import logging from fastapi import APIRouter from pipelines.schema import Label from rest_api.schema import FilterRequest, LabelSerialized, CreateLabelSerialized from rest_api.controller.search import DOCUMENT_STORE logger = logging.getLogger(__name__) DOCUMENT_STOR...
This endpoint returns JSON output in the SQuAD format for question/answer pairs that were marked as "relevant" by user feedback through the `POST /feedback` endpoint. The context_size param can be used to limit response size for large documents.
39,601
from typing import List import logging from fastapi import APIRouter from rest_api.controller.search import DOCUMENT_STORE from rest_api.config import LOG_LEVEL from rest_api.schema import FilterRequest, DocumentSerialized DOCUMENT_STORE = PIPELINE.get_document_store() class FilterRequest(BaseModel): filters: Opt...
This endpoint allows you to retrieve documents contained in your document store. You can filter the documents to delete by metadata (like the document's name), or provide an empty JSON object to clear the document store. Example of filters: `'{"filters": {{"name": ["some", "more"], "category": ["only_one"]}}'` To get a...
39,602
from typing import List import logging from fastapi import APIRouter from rest_api.controller.search import DOCUMENT_STORE from rest_api.config import LOG_LEVEL from rest_api.schema import FilterRequest, DocumentSerialized DOCUMENT_STORE = PIPELINE.get_document_store() class FilterRequest(BaseModel): filters: Opt...
This endpoint allows you to delete documents contained in your document store. You can filter the documents to delete by metadata (like the document's name), or provide an empty JSON object to clear the document store. Example of filters: `'{"filters": {{"name": ["some", "more"], "category": ["only_one"]}}'` To get all...
39,603
import logging import sys import uvicorn from fastapi import FastAPI, HTTPException from fastapi.openapi.utils import get_openapi from fastapi.routing import APIRoute from starlette.middleware.cors import CORSMiddleware from rest_api.config import ROOT_PATH from rest_api.controller.errors.http_error import http_error_h...
Used to autogenerate OpenAPI specs file to use in the documentation. See `docs/_src/api/openapi/generate_openapi_specs.py`
39,604
import logging import sys import uvicorn from fastapi import FastAPI, HTTPException from fastapi.openapi.utils import get_openapi from fastapi.routing import APIRoute from starlette.middleware.cors import CORSMiddleware from rest_api.config import ROOT_PATH from rest_api.controller.errors.http_error import http_error_h...
Simplify operation IDs so that generated API clients have simpler function names (see https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#using-the-path-operation-function-name-as-the-operationid). The operation IDs will be the same as the route names (i.e. the python method names of the endpoi...
39,605
import argparse from pipelines import DocPipeline from pipelines.nodes import DocOCRProcessor, DocPrompter args = parser.parse_args() def docprompt_pipeline(): use_gpu = True if args.device == "gpu" else False preprocessor = DocOCRProcessor(use_gpu=use_gpu) docprompter = DocPrompter(use_gpu=use_gpu, batc...
null
39,606
import argparse import os from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import MultiModalRetriever from pipelines.pipelines import Pipeline from pipelines.utils import convert_files_to_dicts, fetch_archive_from_http args = parser.parse_args() def image_text_retrieval_tutorial(): fai...
null
39,607
import argparse import os from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import MultiModalRetriever from pipelines.pipelines import Pipeline from pipelines.schema import Document from pipelines.utils import fetch_archive_from_http args = parser.parse_args() def image_text_retrieval_tutor...
null
39,608
import argparse import os from pipelines.nodes import AnswerExtractor, QAFilter, QuestionGenerator from pipelines.pipelines import QAGenerationPipeline args = parser.parse_args() def offline_qa_generation(): answer_extractor = AnswerExtractor( model="uie-base-answer-extractor", device=args.device, ...
null
39,610
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,611
import argparse from pipelines import TextToImagePipeline from pipelines.nodes import ErnieTextToImageGenerator args = parser.parse_args() def text_to_image(): erine_image_generator = ErnieTextToImageGenerator(ak=args.api_key, sk=args.secret_key) pipe = TextToImagePipeline(erine_image_generator) prediction...
null
39,612
import argparse from pipelines.document_stores import ( BaiduElasticsearchDocumentStore, ElasticsearchDocumentStore, ) from pipelines.nodes import ( BM25Retriever, DensePassageRetriever, ErnieRanker, JoinDocuments, ) from pipelines.pipelines import Pipeline from pipelines.utils import ( conv...
null
39,613
import argparse import os from pipelines.document_stores import FAISSDocumentStore, MilvusDocumentStore from pipelines.nodes import DensePassageRetriever, ErnieRanker from pipelines.utils import ( convert_files_to_dicts, fetch_archive_from_http, print_documents, ) args = parser.parse_args() def get_faiss_re...
null
39,614
import logging import os from src.llm import Ernie_llm_list, llamaChatCompletion, llm_config def completions_with_backoff(**kwargs): chatter = kwargs["chatter"] return chatter.create( messages=kwargs["messages"], temperature=kwargs["temperature"], max_gen_len=kwargs["max_tokens"] )
null
39,615
import os import re import pandas as pd import sympy from src.tot.prompts.game24 import ( cot_prompt, propose_prompt, standard_prompt, value_last_step_prompt, value_prompt, ) from src.tot.tasks.base import DATA_PATH, Task def get_current_numbers(y: str) -> str: last_line = y.strip().split("\n")...
null
39,616
import re import time import erniebot def contains_number(input_string): # 检查字符串中是否存在中文 和 数字 return bool(re.search(r"\d", input_string))
null
39,617
import re import time import erniebot def contains_chinese(input_string): return bool(re.search(r"[\u4e00-\u9fff]", input_string))
null
39,618
import re import time import erniebot def contains_english(input_string): return bool(re.search(r"[a-zA-Z]", input_string))
null
39,619
import re import time import erniebot def contains_math_symbols(input_string): # 这里我们对特殊字符进行了转义,因为它们在正则表达式中有特殊含义 return bool(re.search(r"[\+\-\*/]", input_string))
null
39,620
import argparse import json import os import time from src.llm.llama import Ernie, Ernie_llm_list, llamaChatCompletion, llm_config from src.tot.methods.bfs import naive_solve, solve from src.tot.models import gpt_usage from src.tot.tasks import get_task def solve(args, task, idx, to_print=True, chatter=None): glob...
null
39,621
import argparse import json import os import time from src.llm.llama import Ernie, Ernie_llm_list, llamaChatCompletion, llm_config from src.tot.methods.bfs import naive_solve, solve from src.tot.models import gpt_usage from src.tot.tasks import get_task llm_backend_choices = list(llm_config.keys()) def parse_args(): ...
null
39,622
import argparse from pipelines.agents import Agent, Tool from pipelines.agents.base import ToolsManager from pipelines.nodes import PromptNode, WebRetriever from pipelines.nodes.prompt.prompt_template import PromptTemplate from pipelines.pipelines import WebQAPipeline few_shot_prompt = """ You are a helpful and knowled...
null
39,623
import argparse import glob import os from pipelines.agents import Agent, Tool from pipelines.agents.base import ToolsManager from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import ( CharacterTextSplitter, DensePassageRetriever, DocxToTextConverter, FileTypeClassifier, ...
null
39,624
import argparse import glob import os from pipelines.agents import Agent, Tool from pipelines.agents.base import ToolsManager from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import ( CharacterTextSplitter, DensePassageRetriever, DocxToTextConverter, FileTypeClassifier, ...
null
39,625
os from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import DensePassageRetriever, ErnieRanker from pipelines.utils import ( convert_files_to_dicts, fetch_archive_from_http, print_documents, ) args = parser.parse_args() def dense_faq_pipeline(): use_gpu = True if args.devic...
null
39,626
os from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import DensePassageRetriever, ErnieRanker, ErnieReader from pipelines.utils import ( convert_files_to_dicts, fetch_archive_from_http, print_answers, ) args = parser.parse_args() def dense_qa_pipeline(): use_gpu = True if ...
null
39,627
import argparse import os from pipelines.document_stores import FAISSDocumentStore, MilvusDocumentStore from pipelines.nodes import ( DensePassageRetriever, ErnieBot, PromptTemplate, TruncatedConversationHistory, ) from pipelines.pipelines import Pipeline from pipelines.utils import convert_files_to_dic...
null
39,628
import argparse import glob import time from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import ( CharacterTextSplitter, DensePassageRetriever, ErnieBot, ErnieRanker, MarkdownConverter, PromptTemplate, TruncatedConversationHistory, ) from pipelines.nodes.file_con...
null
39,629
import argparse import glob from pipelines.document_stores import ( BaiduElasticsearchDocumentStore, FAISSDocumentStore, ) from pipelines.nodes import ( ErnieBot, ErnieRanker, PromptTemplate, TruncatedConversationHistory, ) from pipelines.nodes.file_converter import TextConverter from pipelines....
null
39,630
import argparse import glob import time from pipelines.document_stores import ElasticsearchDocumentStore from pipelines.nodes import ( CharacterTextSplitter, ChatGLMBot, DensePassageRetriever, ErnieBot, ErnieRanker, PDFToTextConverter, PromptTemplate, ) from pipelines.pipelines import Pipeli...
null
39,631
import argparse import glob from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import ( CharacterTextSplitter, DensePassageRetriever, ErnieBot, ErnieRanker, PDFToTextConverter, PromptTemplate, ) from pipelines.pipelines import Pipeline args = parser.parse_args() def c...
null
39,632
import argparse import glob import time from pipelines.document_stores import ( BaiduElasticsearchDocumentStore, ElasticsearchDocumentStore, ) from pipelines.nodes import ( BM25Retriever, CharacterTextSplitter, ChatGLMBot, DensePassageRetriever, EmbeddingRetriever, ErnieBot, ErnieRan...
null
39,633
import argparse import glob from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import DensePassageRetriever, ErnieBot, ErnieRanker, PromptTemplate from pipelines.nodes.file_converter.docx import DocxTotxtConverter from pipelines.nodes.preprocessor.text_splitter import SpacyTextSplitter from p...
null
39,634
import argparse from pipelines import SentaPipeline from pipelines.nodes import SentaProcessor, SentaVisualization, UIESenta def format_print(results): """ Print Information in results. """ if "sr_save_path" in results: print("\nText Result: ", results["sr_save_path"]) if "img_dict" in resul...
Sentiment Analysis with Pipeline.
39,635
import glob import json import logging import os import re import shutil from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import DensePassageRetriever from collections import defaultdict def preprocess(path): """ Preprocessing json file """ with open(path, mode="r", encoding...
Process json files to obtain text and table information
39,636
import glob import json import logging import os import re import shutil from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import DensePassageRetriever from collections import defaultdict The provided code snippet includes necessary dependencies for implementing the `create_index` function....
Creating indexes
39,637
import argparse import gradio as gr from chat_table import parsing_QA def reset_state(): return "", []
null