id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
39,638
import argparse import gradio as gr from chat_table import parsing_QA args = parser.parse_args() def predict(query, history=[]): result = parsing_QA(args.api_key, args.secret_key, query) history.append(["user: {}".format(query), "assistant: {}".format(result)]) return "", history, history
null
39,639
import json import time from create_index import columns_titles, index_name from pipelines.document_stores import FAISSDocumentStore from pipelines.nodes import DensePassageRetriever, ErnieBot, ErnieRanker from pipelines.pipelines import Pipeline all_titles = [value for key, value in columns_titles.items()] def text_re...
FistrParsing query to obtain keywords, then,text retrieval, and table Q&A
39,640
import argparse import logging import os from typing import Optional import fitz import requests from pipelines.document_stores import BaiduElasticsearchDocumentStore from pipelines.nodes import EmbeddingRetriever, ErnieRanker from pipelines.pipelines import Pipeline import time from functools import partial from multi...
null
39,641
import argparse import logging import os from typing import Optional import fitz import requests from pipelines.document_stores import BaiduElasticsearchDocumentStore from pipelines.nodes import EmbeddingRetriever, ErnieRanker from pipelines.pipelines import Pipeline import time from functools import partial from multi...
Get gradio chatbot.
39,642
import argparse import logging import os from typing import Optional import fitz import requests from pipelines.document_stores import BaiduElasticsearchDocumentStore from pipelines.nodes import EmbeddingRetriever, ErnieRanker from pipelines.pipelines import Pipeline import time from functools import partial from multi...
null
39,643
import argparse from concurrent.futures import ThreadPoolExecutor import pandas as pd from pipelines.document_stores import ( BaiduElasticsearchDocumentStore, ElasticsearchDocumentStore, MilvusDocumentStore, ) from pipelines.nodes import DensePassageRetriever, EmbeddingRetriever, SpacyTextSplitter from pipe...
null
39,644
import argparse from concurrent.futures import ThreadPoolExecutor import pandas as pd from pipelines.document_stores import ( BaiduElasticsearchDocumentStore, ElasticsearchDocumentStore, MilvusDocumentStore, ) from pipelines.nodes import DensePassageRetriever, EmbeddingRetriever, SpacyTextSplitter from pipe...
null
39,645
import argparse from concurrent.futures import ThreadPoolExecutor import pandas as pd from pipelines.document_stores import ( BaiduElasticsearchDocumentStore, ElasticsearchDocumentStore, MilvusDocumentStore, ) from pipelines.nodes import DensePassageRetriever, EmbeddingRetriever, SpacyTextSplitter from pipe...
null
39,646
import argparse def get_parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--api_type", type=str, default="qianfan") parser.add_argument("--api_key", type=str, default="", help="The API Key.") parser.add_argument("--secret_key", type=str, default="", help="The secret key.") parse...
null
39,647
import json import logging import os import re import time import arxiv import erniebot as eb import gradio as gr from utils import ( _apply_token, get_parse_args, merge_summary, pdf2image, retrieval, summarize_abstract, tackle_history, translate_part, ) args = get_parse_args() PROMPT_RE...
Retrieve papers
39,648
import json import logging import os import re import time import arxiv import erniebot as eb import gradio as gr from utils import ( _apply_token, get_parse_args, merge_summary, pdf2image, retrieval, summarize_abstract, tackle_history, translate_part, ) args = get_parse_args() PROMPT_SY...
Model inference.
39,649
import json import logging import os import re import time import arxiv import erniebot as eb import gradio as gr from utils import ( _apply_token, get_parse_args, merge_summary, pdf2image, retrieval, summarize_abstract, tackle_history, translate_part, ) logger = logging.getLogger(__name...
Upload the file to bos or retrieve the json_file of the paper
39,650
import json import logging import os import re import time import arxiv import erniebot as eb import gradio as gr from utils import ( _apply_token, get_parse_args, merge_summary, pdf2image, retrieval, summarize_abstract, tackle_history, translate_part, ) def add_messaget_chatbot(message...
null
39,651
import json import logging import os import re import time import arxiv import erniebot as eb import gradio as gr from utils import ( _apply_token, get_parse_args, merge_summary, pdf2image, retrieval, summarize_abstract, tackle_history, translate_part, ) args = get_parse_args() def tran...
null
39,652
import argparse from pipelines.document_stores import ( BaiduElasticsearchDocumentStore, ElasticsearchDocumentStore, ) from pipelines.nodes import ( BM25Retriever, DensePassageRetriever, EmbeddingRetriever, ErnieRanker, JoinDocuments, ) from pipelines.pipelines import Pipeline from pipelines...
null
39,653
import json import erniebot import gradio as gr from prompt_utils import functions, get_parse_args from pipelines.document_stores import BaiduElasticsearchDocumentStore from pipelines.nodes import EmbeddingRetriever from pipelines.pipelines import Pipeline args = get_parse_args() def prediction(history): logs = [] ...
null
39,654
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from utils import pipelines_files, pipelines_is_ready, semantic_search, upload_doc def set_state_if_absent(key, value): if key not in st.session_sta...
null
39,655
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from utils import pipelines_files, pipelines_is_ready, semantic_search, upload_doc def on_change_text(): st.session_state.question = st.session_stat...
null
39,656
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from utils import pipelines_files, pipelines_is_ready, semantic_search, upload_doc def upload_doc(file): url = f"{API_ENDPOINT}/{DOC_UPLOAD}" fi...
null
39,657
import json import logging import os import socket from time import sleep from typing import Any, Dict, List, Optional, Tuple import requests import streamlit as st from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import DensePassageRetriever from pipelines.util...
Used to show the "pipelines is loading..." message
39,658
import json import logging import os import socket from time import sleep from typing import Any, Dict, List, Optional, Tuple import requests import streamlit as st from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import DensePassageRetriever from pipelines.util...
Get the pipelines version from the REST API
39,659
import json import logging import os import socket from time import sleep from typing import Any, Dict, List, Optional, Tuple import requests import streamlit as st from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import DensePassageRetriever from pipelines.util...
Get the pipelines files from the REST API # http://server_ip:server_port/files?file_name=8f6435d7ff1f1913dbcd74feb47e2fdb_0.png
39,660
import json import logging import os import socket from time import sleep from typing import Any, Dict, List, Optional, Tuple import requests import streamlit as st from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import DensePassageRetriever from pipelines.util...
Send a query to the REST API and parse the answer. Returns both a ready-to-use representation of the results and the raw JSON.
39,661
import json import logging import os import socket from time import sleep from typing import Any, Dict, List, Optional, Tuple import requests import streamlit as st from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import DensePassageRetriever from pipelines.util...
Send a query to the REST API and parse the answer. Returns both a ready-to-use representation of the results and the raw JSON.
39,662
import json import logging import os import socket from time import sleep from typing import Any, Dict, List, Optional, Tuple import requests import streamlit as st from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import DensePassageRetriever from pipelines.util...
Send a query to the REST API and parse the answer. Returns both a ready-to-use representation of the results and the raw JSON.
39,663
import json import logging import os import socket from time import sleep from typing import Any, Dict, List, Optional, Tuple import requests import streamlit as st from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import DensePassageRetriever from pipelines.util...
Send a prompt text and corresponding parameters to the REST API
39,664
import json import logging import os import socket from time import sleep from typing import Any, Dict, List, Optional, Tuple import requests import streamlit as st from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import DensePassageRetriever from pipelines.util...
Send a feedback (label) to the REST API
39,665
import json import logging import os import socket from time import sleep from typing import Any, Dict, List, Optional, Tuple import requests import streamlit as st from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import DensePassageRetriever from pipelines.util...
null
39,666
import json import logging import os import socket from time import sleep from typing import Any, Dict, List, Optional, Tuple import requests import streamlit as st from pipelines.document_stores import ElasticsearchDocumentStore, MilvusDocumentStore from pipelines.nodes import DensePassageRetriever from pipelines.util...
null
39,667
import argparse import io import os from pathlib import Path from typing import NamedTuple import gradio as gr from utils import ChatFile, upload_chatfile def clear_session(): return "", None, None, None, None, []
null
39,668
import argparse import io import os from pathlib import Path from typing import NamedTuple import gradio as gr from utils import ChatFile, upload_chatfile def upload(data_files, chunk_size, separator, filters): for index, data_file in enumerate(data_files): if data_file.name not in loaded_path: ...
null
39,669
import argparse from io import BytesIO import gradio as gr from PIL import Image, ImageFile from utils import image_to_text_search def pil_base64(image, img_format="JPEG"): Image.MAX_IMAGE_PIXELS = 1000000000 ImageFile.LOAD_TRUNCATED_IMAGES = True img_buffer = BytesIO() image.save(img_buffer, format=img...
null
39,670
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from ui.utils import ( multi_recall_semantic_search, pipelines_files, pipelines_is_ready, upload_doc, ) def set_state_if_absent(key, val...
null
39,671
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from ui.utils import ( multi_recall_semantic_search, pipelines_files, pipelines_is_ready, upload_doc, ) def on_change_text(): st.ses...
null
39,672
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from ui.utils import ( multi_recall_semantic_search, pipelines_files, pipelines_is_ready, upload_doc, ) def upload_doc(file): url = ...
null
39,673
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from annotated_text import annotation from markdown import markdown from ui.utils import get_backlink, pipelines_is_ready, query, upload_doc def set_state_if_absent(key, value): ...
null
39,674
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from annotated_text import annotation from markdown import markdown from ui.utils import get_backlink, pipelines_is_ready, query, upload_doc def on_change_text(): st.session_stat...
null
39,675
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from annotated_text import annotation from markdown import markdown from ui.utils import get_backlink, pipelines_is_ready, query, upload_doc def upload_doc(file): def upload(): ...
null
39,676
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from utils import pipelines_is_ready, semantic_search, upload_doc def set_state_if_absent(key, value): if key not in st.session_state: st.se...
null
39,677
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from utils import pipelines_is_ready, semantic_search, upload_doc def on_change_text(): st.session_state.question = st.session_state.quest st.se...
null
39,678
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from utils import pipelines_is_ready, semantic_search, upload_doc def upload_doc(file): url = f"{API_ENDPOINT}/{DOC_UPLOAD}" files = [("files", ...
null
39,679
import argparse import os import gradio as gr import requests with gr.Blocks() as demo: file_path = gr.Textbox(visible=False) gr.Markdown(value="# Sentiment Analysis Application\n----") upload_file = gr.File(label="Select a file", interactive=True, elem_id="file-upload-box") with gr.Row(): reset...
null
39,680
import argparse import os import gradio as gr import requests args = parser.parse_args() with gr.Blocks() as demo: file_path = gr.Textbox(visible=False) gr.Markdown(value="# Sentiment Analysis Application\n----") upload_file = gr.File(label="Select a file", interactive=True, elem_id="file-upload-box") w...
null
39,681
import argparse import os import gradio as gr import requests with gr.Blocks() as demo: file_path = gr.Textbox(visible=False) gr.Markdown(value="# Sentiment Analysis Application\n----") upload_file = gr.File(label="Select a file", interactive=True, elem_id="file-upload-box") with gr.Row(): reset...
null
39,682
import argparse import gradio as gr from utils import text_to_image_search def text_to_image_search( query, resolution="1024*1024", top_k_images=5, style="探索无限" ) -> Tuple[List[Dict[str, Any]], Dict[str, str]]: """ Send a prompt text and corresponding parameters to the REST API """ url = f"{API_END...
null
39,683
import argparse import base64 import traceback from io import BytesIO import cv2 import fitz import gradio as gr import numpy as np import requests from PIL import Image def process_path(path): error = None if path: try: images_list = load_document(path) return ( ...
null
39,684
import argparse import base64 import traceback from io import BytesIO import cv2 import fitz import gradio as gr import numpy as np import requests from PIL import Image def np2base64(image_np): image = cv2.imencode(".jpg", image_np)[1] base64_str = str(base64.b64encode(image))[2:-1] return base64_str
null
39,685
import argparse import base64 import traceback from io import BytesIO import cv2 import fitz import gradio as gr import numpy as np import requests from PIL import Image args = parser.parse_args() def get_base64(path): if path.startswith("http://") or path.startswith("https://"): resp = requests.get(path, a...
null
39,686
import argparse import base64 import traceback from io import BytesIO import cv2 import fitz import gradio as gr import numpy as np import requests from PIL import Image The provided code snippet includes necessary dependencies for implementing the `read_content` function. Write a Python function `def read_content(fil...
read the content of target file
39,687
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from ui.utils import ( file_upload_qa_generate, offline_ann, pipelines_is_ready, semantic_search, text_to_qa_pair_search, ) def set_...
null
39,688
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from ui.utils import ( file_upload_qa_generate, offline_ann, pipelines_is_ready, semantic_search, text_to_qa_pair_search, ) def on_c...
null
39,689
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from ui.utils import ( file_upload_qa_generate, offline_ann, pipelines_is_ready, semantic_search, text_to_qa_pair_search, ) def on_c...
null
39,690
import logging import os import sys from json import JSONDecodeError from pathlib import Path import pandas as pd import streamlit as st from markdown import markdown from ui.utils import ( file_upload_qa_generate, offline_ann, pipelines_is_ready, semantic_search, text_to_qa_pair_search, ) def file...
null
39,691
import argparse import gradio as gr from utils import image_text_search def image_text_search(query, filters={}, top_k_retriever=5) -> Tuple[List[Dict[str, Any]], Dict[str, str]]: """ Send a query to the REST API and parse the answer. Returns both a ready-to-use representation of the results and the raw JS...
null
39,692
import csv import math import time from collections import defaultdict from typing import Dict, List, cast from datasets import load_dataset from mteb.abstasks import AbsTaskRetrieval from paddlenlp import Taskflow def load_t2ranking_for_retraviel(num_max_passages: float): collection_dataset = load_dataset("THUIR/...
null
39,693
import json import logging import typing from datetime import datetime from typing import Dict, Generator, List, Optional, Tuple, Union from elasticsearch.helpers import scan from tqdm.auto import tqdm from pipelines.document_stores.filter_utils import LogicalFilterClause from pipelines.nodes.preprocessor import PrePro...
Read Documents + Labels from a SQuAD-style file. Document and Labels can then be indexed to the DocumentStore and be used for evaluation. :param filename: Path to file in SQuAD format :param max_docs: This sets the number of documents that will be loaded. By default, this is set to None, thus reading in all available e...
39,694
import json import logging import typing from datetime import datetime from typing import Dict, Generator, List, Optional, Tuple, Union from elasticsearch.helpers import scan from tqdm.auto import tqdm from pipelines.document_stores.filter_utils import LogicalFilterClause from pipelines.nodes.preprocessor import PrePro...
Read Documents + Labels from a SQuAD-style file in jsonl format, i.e. one document per line. Document and Labels can then be indexed to the DocumentStore and be used for evaluation. This is a generator which will yield one tuple per iteration containing a list of batch_size documents and a list with the documents' labe...
39,695
import json import logging import typing from datetime import datetime from typing import Dict, Generator, List, Optional, Tuple, Union from elasticsearch.helpers import scan from tqdm.auto import tqdm from pipelines.document_stores.filter_utils import LogicalFilterClause from pipelines.nodes.preprocessor import PrePro...
Converts a SQuAD-json-file into jsonl format with one document per line. :param squad_file: SQuAD-file in json format. :param output_file: Name of output file (SQuAD in jsonl format)
39,696
import json import logging import typing from datetime import datetime from typing import Dict, Generator, List, Optional, Tuple, Union from elasticsearch.helpers import scan from tqdm.auto import tqdm from pipelines.document_stores.filter_utils import LogicalFilterClause from pipelines.nodes.preprocessor import PrePro...
Converts a date to RFC3339 format, as Weaviate requires dates to be in RFC3339 format including the time and timezone. If the provided date string does not contain a time and/or timezone, we use 00:00 as default time and UTC as default time zone. This method cannot be part of WeaviateDocumentStore, as this would result...
39,697
import json import logging import typing from datetime import datetime from typing import Dict, Generator, List, Optional, Tuple, Union from elasticsearch.helpers import scan from tqdm.auto import tqdm from pipelines.document_stores.filter_utils import LogicalFilterClause from pipelines.nodes.preprocessor import PrePro...
This function provides brownfield support of existing Elasticsearch indexes by converting each of the records in the provided index to pipelines `Document` objects and writing them to the specified `DocumentStore`. It can be used on a regular basis in order to add new records of the Elasticsearch index to the `Document...
39,698
from abc import ABC, abstractmethod from collections import defaultdict from typing import Dict, List, Optional, Tuple, Union from sqlalchemy import and_, or_ from sqlalchemy.sql import select from pipelines.document_stores import utils The provided code snippet includes necessary dependencies for implementing the `ne...
Data structure that recursively adds a dictionary as value if a key does not exist. Advantage: In nested dictionary structures, we don't need to check if a key already exists (which can become hard to maintain in nested dictionaries with many levels) but access the existing value if a key exists and create an empty dic...
39,699
import collections import logging from abc import abstractmethod from itertools import islice from pathlib import Path from typing import Dict, Generator, List, Optional, Set, Union import numpy as np from pipelines.document_stores.utils import ( eval_data_from_json, eval_data_from_jsonl, squad_json_to_json...
null
39,700
import collections import logging from abc import abstractmethod from itertools import islice from pathlib import Path from typing import Dict, Generator, List, Optional, Set, Union import numpy as np from pipelines.document_stores.utils import ( eval_data_from_json, eval_data_from_jsonl, squad_json_to_json...
null
39,701
import collections import logging from abc import abstractmethod from itertools import islice from pathlib import Path from typing import Dict, Generator, List, Optional, Set, Union import numpy as np from pipelines.document_stores.utils import ( eval_data_from_json, eval_data_from_jsonl, squad_json_to_json...
Batch elements of an iterable into fixed-length chunks or blocks.
39,702
from __future__ import annotations import logging import re from collections.abc import Callable, Iterable from hashlib import md5 from typing import Any, Dict, List, Optional, Tuple, Union from events import Events from pipelines import ( Answer, BaseComponent, BaseStandardPipeline, Document, Extra...
Print text with optional color. :param text: Text to print. :param end: End character to use (defaults to ""). :param color: Color to print text in (defaults to None).
39,703
import inspect import logging import re import sys import networkx as nx from typing import Any, Dict, List, Optional from networkx import DiGraph from pipelines.pipelines.config import ( build_component_dependency_graph, get_component_definitions, get_pipeline_definition, validate_config, ) def camel_t...
Generates code to create a pipeline. :param pipeline_config: The pipeline config that specifies components and pipelines. :param pipeline_variable_name: The variable name of the pipeline to be generated. Defaults to "pipeline". :param pipeline_name: The name of the pipeline defined in pipeline_config to be generated. I...
39,704
import inspect import logging import re import sys import networkx as nx from typing import Any, Dict, List, Optional from networkx import DiGraph from pipelines.pipelines.config import ( build_component_dependency_graph, get_component_definitions, get_pipeline_definition, validate_config, ) def _format...
null
39,705
import inspect import logging import re import sys import networkx as nx from typing import Any, Dict, List, Optional from networkx import DiGraph from pipelines.pipelines.config import ( build_component_dependency_graph, get_component_definitions, get_pipeline_definition, validate_config, ) def _format...
null
39,706
import copy import logging import os from pathlib import Path import re from typing import Any, Dict, List, Optional from networkx import DiGraph import yaml The provided code snippet includes necessary dependencies for implementing the `get_pipeline_definition` function. Write a Python function `def get_pipeline_defi...
Get the definition of Pipeline from a given pipeline config. If the config contains more than one Pipeline, then the pipeline_name must be supplied. :param pipeline_config: Dict Pipeline config parsed as a dictionary. :param pipeline_name: name of the Pipeline.
39,707
import copy import logging import os from pathlib import Path import re from typing import Any, Dict, List, Optional from networkx import DiGraph import yaml def _overwrite_with_env_variables(component_definition: Dict[str, Any]): """ Overwrite the pipeline config with environment variables. For example, to cha...
Returns the definitions of all components from a given pipeline config. :param pipeline_config: Dict Pipeline config parsed as a dictionary. :param overwrite_with_env_variables: Overwrite the YAML configuration with environment variables. For example, to change index name param for an ElasticsearchDocumentStore, an env...
39,708
import copy import logging import os from pathlib import Path import re from typing import Any, Dict, List, Optional from networkx import DiGraph import yaml def read_pipeline_config_from_yaml(path: Path): with open(path, "r", encoding="utf-8") as stream: return yaml.safe_load(stream)
null
39,709
import copy import logging import os from pathlib import Path import re from typing import Any, Dict, List, Optional from networkx import DiGraph import yaml def _validate_user_input(input: str): def validate_config(pipeline_config: Dict[str, Any]): for component in pipeline_config["components"]: _validate...
null
39,710
import copy import logging import os from pathlib import Path import re from typing import Any, Dict, List, Optional from networkx import DiGraph import yaml The provided code snippet includes necessary dependencies for implementing the `build_component_dependency_graph` function. Write a Python function `def build_co...
Builds a dependency graph between components. Dependencies are: - referenced components during component build time (e.g. init params) - predecessor components in the pipeline that produce the needed input This enables sorting the components in a working and meaningful order for instantiation using topological sorting....
39,711
import ast import json import logging from abc import ABC from typing import Any, Dict, Iterator, List, Optional, Tuple, Union from uuid import uuid4 from pipelines.nodes.base import BaseComponent from pipelines.nodes.prompt.shapers import AnswerParser, BaseOutputParser from pipelines.schema import Document, MultiLabel...
null
39,712
import json import logging from typing import Any, Dict, List, Optional, Tuple, Union import requests import sseclient from pipelines.nodes.prompt.invocation_layer.base import PromptModelInvocationLayer from pipelines.nodes.prompt.invocation_layer.handlers import ( DefaultTokenStreamingHandler, TokenStreamingHa...
Make a request to the OpenAI API given a `url`, `headers`, `payload`, and `timeout`. :param url: The URL of the OpenAI API. :param headers: Dictionary of HTTP Headers to send with the :class:`Request`. :param payload: The payload to send with the request. :param timeout: The timeout length of the request. The default i...
39,713
import json import logging from typing import Any, Dict, List, Optional, Tuple, Union import requests import sseclient from pipelines.nodes.prompt.invocation_layer.base import PromptModelInvocationLayer from pipelines.nodes.prompt.invocation_layer.handlers import ( DefaultTokenStreamingHandler, TokenStreamingHa...
Check the `finish_reason` the answers returned by OpenAI completions endpoint. If the `finish_reason` is `length` or `content_filter`, log a warning to the user. :param result: The result returned from the OpenAI API. :param payload: The payload sent to the OpenAI API.
39,714
import inspect import logging import re from functools import reduce from string import Template from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pipelines.nodes.base import BaseComponent from pipelines.schema import Answer, Document, MultiLabel def format_document( document: Document, ...
null
39,715
import inspect import logging import re from functools import reduce from string import Template from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pipelines.nodes.base import BaseComponent from pipelines.schema import Answer, Document, MultiLabel The provided code snippet includes necessary dep...
An identity function. You can use it to rename values in the invocation context without changing them. Example: ```python assert rename(1) == 1 ```
39,716
import inspect import logging import re from functools import reduce from string import Template from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pipelines.nodes.base import BaseComponent from pipelines.schema import Answer, Document, MultiLabel def string_to_answer( string: str, prompt...
Transforms a list of strings into a list of answers. Specify `reference_pattern` to populate the answer's `document_ids` by extracting document references from the strings. :param strings: The list of strings to transform. :param prompts: The prompts used to generate the answers. :param documents: The documents used to...
39,717
import inspect import logging import re from functools import reduce from string import Template from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pipelines.nodes.base import BaseComponent from pipelines.schema import Answer, Document, MultiLabel The provided code snippet includes necessary dep...
Transforms a list of documents with scores in their metadata into a list containing a single document. The resulting document contains the scores and the contents of all the original documents. All metadata is dropped. Example: ```python assert join_documents_and_scores( documents=[ Document(content="first", meta={"sco...
39,718
import inspect import logging import re from functools import reduce from string import Template from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pipelines.nodes.base import BaseComponent from pipelines.schema import Answer, Document, MultiLabel def format_answer( answer: Answer, patter...
Extracts the content field of answers and returns a list of strings. Example: ```python assert answers_to_strings( answers=[ Answer(answer="first"), Answer(answer="second"), Answer(answer="third") ], pattern="[$idx] $answer", str_replace={"r": "R"} ) == ["[1] fiRst", "[2] second", "[3] thiRd"] ```
39,719
import inspect import logging import re from functools import reduce from string import Template from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pipelines.nodes.base import BaseComponent from pipelines.schema import Answer, Document, MultiLabel def format_document( document: Document, ...
Extracts the content field of documents and returns a list of strings. Use regext in the `pattern` parameter to control how the documents are represented. Example: ```python assert documents_to_strings( documents=[ Document(content="first"), Document(content="second"), Document(content="third") ], pattern="[$idx] $cont...
39,720
import inspect import logging import re from functools import reduce from string import Template from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pipelines.nodes.base import BaseComponent from pipelines.schema import Answer, Document, MultiLabel The provided code snippet includes necessary dep...
Transforms a list of strings into a list of documents. If you pass the metadata in a single dictionary, all documents get the same metadata. If you pass the metadata as a list, the length of this list must be the same as the length of the list of strings, and each document gets its own metadata. You can specify `id_has...
39,721
import inspect import logging import re from functools import reduce from string import Template from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pipelines.nodes.base import BaseComponent from pipelines.schema import Answer, Document, MultiLabel def join_documents_to_string( documents: List...
Transforms a list of documents into a list containing a single document. The content of this document is the joined result of all original documents, separated by the delimiter you specify. Use regex in the `pattern` parameter to control how each document is represented. You can use the following placeholders: - $conte...
39,722
import inspect import logging import re from functools import reduce from string import Template from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pipelines.nodes.base import BaseComponent from pipelines.schema import Answer, Document, MultiLabel def format_string(string: str, str_replace: Optio...
Transforms a list of strings into a single string. The content of this string is the content of all of the original strings separated by the delimiter you specify. Example: ```python assert join_strings(strings=["first", "second", "third"], delimiter=" - ", str_replace={"r": "R"}) == "fiRst - second - thiRd" ```
39,723
import inspect import logging import re from functools import reduce from string import Template from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pipelines.nodes.base import BaseComponent from pipelines.schema import Answer, Document, MultiLabel The provided code snippet includes necessary dep...
Joins the lists you pass to it into a single list. Example: ```python assert join_lists(lists=[[1, 2, 3], [4, 5]]) == [1, 2, 3, 4, 5] ```
39,724
import inspect import logging import re from functools import reduce from string import Template from typing import Any, Callable, Dict, List, Optional, Tuple, Union from pipelines.nodes.base import BaseComponent from pipelines.schema import Answer, Document, MultiLabel The provided code snippet includes necessary dep...
Transforms a value into a list containing this value as many times as the length of the target list. Example: ```python assert value_to_list(value=1, target_list=list(range(5))) == [1, 1, 1, 1, 1] ```
39,725
import logging from typing import Any, Dict, List, Optional, Tuple, Type, Union, overload from pipelines.nodes.base import BaseComponent from pipelines.nodes.prompt.invocation_layer import PromptModelInvocationLayer from pipelines.schema import Document, MultiLabel def instruction_following_models() -> List[str]: ...
null
39,726
import functools import logging import multiprocessing import os import tempfile from pathlib import Path from typing import Any, Dict, List, Optional import pypdf from pipelines.nodes.file_converter import BaseConverter, ImageToTextConverter def extract_pages(page_list, file_path): def run_process(pages, file_path, p...
null
39,727
from typing import Any, List, Optional The provided code snippet includes necessary dependencies for implementing the `calculate_ranking_scores` function. Write a Python function `def calculate_ranking_scores(list_items: List[Any], boost_first_factor: Optional[int] = None) -> List[float]` to solve the following proble...
Assigns scores to items in a list based on their rank position and ensures that the scores add up to 1. :param list_items: The list of items to score. :param boost_first_factor: The factor to boost the score of the first item by.
39,728
import logging import multiprocessing import time from copy import deepcopy from functools import partial from multiprocessing import Pool from typing import Dict, List, Optional, Union import numpy as np from tqdm.auto import tqdm from tritonclient.http import InferenceServerClient, InferInput, InferRequestedOutput fr...
null
39,729
import logging import multiprocessing import time from copy import deepcopy from functools import partial from multiprocessing import Pool from typing import Dict, List, Optional, Union import numpy as np from tqdm.auto import tqdm from tritonclient.http import InferenceServerClient, InferInput, InferRequestedOutput fr...
null
39,730
import logging from typing import Any, Callable, List, Optional, Protocol, Tuple from pipelines.nodes.combine_documents.base import BaseCombineDocuments def _split_list_of_docs(docs: List[dict], length_func: Callable, token_max: int, **kwargs: Any) -> List[List[dict]]: new_result_doc_list = [] _sub_result_docs...
null
39,731
import logging from typing import Any, Callable, List, Optional, Protocol, Tuple from pipelines.nodes.combine_documents.base import BaseCombineDocuments logger = logging.getLogger(__name__) class CombineDocsProtocol(Protocol): def __call__(self, docs: List[dict], **kwargs: Any) -> str: def _collapse_docs( doc...
null
39,732
import logging from typing import Any, List, Optional, Tuple from pipelines.nodes import ErnieBot from pipelines.nodes.combine_documents.base import BaseCombineDocuments def format_document(doc: dict, prompt: str) -> str: return prompt.format(**doc)
null
39,733
from __future__ import annotations import typing from dataclasses import asdict from typing import Any, Dict, List, Optional, Union import ast import json import logging import time from pathlib import Path from uuid import uuid4 import mmh3 import numpy as np import pandas as pd from pydantic import BaseConfig from py...
Constructs a pydantic dataclass from a dict incl. other nested dataclasses. This allows simple de-serialization of pydentic dataclasses from json. :param dict: Dict containing all attributes and values for the dataclass. :param pydantic_dataclass_type: The class of the dataclass that should be constructed (e.g. Documen...
39,734
from typing import Union, Optional, List import logging import numpy as np def offset_to_token_idx_vecorized(token_offsets, ch_idx): """Returns the idx of the token at the given character idx""" # case ch_idx is at end of tokens if ch_idx >= np.max(token_offsets): # TODO check "+ 1" (it is needed fo...
TODO Write Comment
39,735
from typing import Union, Optional, List import logging import numpy as np The provided code snippet includes necessary dependencies for implementing the `get_passage_offsets` function. Write a Python function `def get_passage_offsets(doc_offsets, doc_stride, passage_len_t, doc_text)` to solve the following problem: G...
Get spans (start and end offsets) for passages by applying a sliding window function. The sliding window moves in steps of doc_stride. Returns a list of dictionaries which each describe the start, end and id of a passage that is formed when chunking a document using a sliding window approach.
39,736
from typing import Union, Optional, List import logging import numpy as np The provided code snippet includes necessary dependencies for implementing the `offset_to_token_idx` function. Write a Python function `def offset_to_token_idx(token_offsets, ch_idx) -> Optional[int]` to solve the following problem: Returns the...
Returns the idx of the token at the given character idx
39,737
import json import logging import os import random from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Union import numpy as np from pipelines.data_handler.dataset import convert_features_to_dataset from pipelines.data_handler.samples import ( Sample, SampleBask...
null