id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
144,403
from pathlib import Path from typing import Any, Dict, Optional, Tuple, Union import flet as ft import httpx import tqdm.asyncio from httpx_socks import AsyncProxyTransport from .config import CONFIG_FILE_NAME, _, sra_config_obj from .log import log transport = AsyncProxyTransport.from_url(proxies) if proxies else None...
说明: 下载文件(带进度条) 参数: :param url: url :param save_path: 保存路径
144,404
from pathlib import Path from typing import Any, Dict, Optional, Tuple, Union import flet as ft import httpx import tqdm.asyncio from httpx_socks import AsyncProxyTransport from .config import CONFIG_FILE_NAME, _, sra_config_obj from .log import log async def post(url: str, *, headers: O...
null
144,405
import os import re import sys import orjson import gettext from pathlib import Path from copy import copy from loguru import logger The provided code snippet includes necessary dependencies for implementing the `get_folder` function. Write a Python function `def get_folder(path) -> list[str]` to solve the following p...
获取文件夹下的文件夹列表
144,406
import os import re import sys import orjson import gettext from pathlib import Path from copy import copy from loguru import logger message = "" _ = t.gettext The provided code snippet includes necessary dependencies for implementing the `get_message` function. Write a Python function `def get_message(*arg)` to solve...
说明: 收集消息并返回 返回: 收集到的消息
144,407
import os import re import sys import orjson import gettext from pathlib import Path from copy import copy from loguru import logger class FileFilter: def __init__(self, file): self.file = file def __call__(self, record): return record["extra"].get("file") == self.file VER = str(data.get("star_v...
null
144,408
import inspect from typing import Any from typing import Callable from typing import Dict from typing import List from typing import Set ACTIVATED_ASYNC_MODE = False def is_prompt_toolkit_3() -> bool: from prompt_toolkit import __version__ as ptk_version return ptk_version.startswith("3.") The provided code sn...
Configure prompt toolkit to use the asyncio event loop. Needs to be async, so we use the right event loop in py 3.5
144,409
from typing import Any from typing import Callable from typing import Dict from typing import Iterable from typing import List from typing import Optional from typing import Tuple from typing import Union from prompt_toolkit.completion import CompleteEvent from prompt_toolkit.completion import Completer from prompt_too...
Prompt the user to enter a message with autocomplete help. Example: >>> import questionary >>> questionary.autocomplete( ... 'Choose ant specie', ... choices=[ ... 'Camponotus pennsylvanicus', ... 'Linepithema humile', ... 'Eciton burchellii', ... "Atta colombica", ... 'Polyergus lucidus', ... 'Polyergus rufescens', .....
144,410
import os from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import Optional from typing import Tuple from prompt_toolkit.completion import CompleteEvent from prompt_toolkit.completion import Completion from prompt_toolkit.completion import PathCompleter f...
A text input for a file or directory path with autocompletion enabled. Example: >>> import questionary >>> questionary.path( >>> "What's the path to the projects version file?" >>> ).ask() ? What's the path to the projects version file? ./pyproject.toml './pyproject.toml' .. image:: ../images/path.gif This is just a re...
144,411
from typing import Any from typing import Dict from typing import Optional from typing import Sequence from typing import Union from prompt_toolkit.styles import Style from ..constants import DEFAULT_QUESTION_PREFIX from ..constants import DEFAULT_SELECTED_POINTER from ..prompts import select from ..prompts.common impo...
Ask the user to select one item from a list of choices using shortcuts. The user can only select one option. Example: >>> import questionary >>> questionary.rawselect( ... "What do you want to do?", ... choices=[ ... "Order a pizza", ... "Make a reservation", ... "Ask for opening hours" ... ]).ask() ? What do you want ...
144,412
from typing import Any from typing import Optional from prompt_toolkit import PromptSession from prompt_toolkit.formatted_text import to_formatted_text from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.keys import Keys from prompt_toolkit.styles import Style from ..question import Question from ..s...
Wait until user presses any key to continue. Example: >>> import questionary >>> questionary.press_any_key_to_continue().ask() Press any key to continue... '' Args: message: Question text. Defaults to ``"Press any key to continue..."`` style: A custom color and style for the question parts. You can configure colors as ...
144,413
from typing import Any from typing import Optional from prompt_toolkit import PromptSession from prompt_toolkit.formatted_text import to_formatted_text from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.keys import Keys from prompt_toolkit.styles import Style from ..constants import DEFAULT_QUESTION...
A yes or no question. The user can either confirm or deny. This question type can be used to prompt the user for a confirmation of a yes-or-no question. If the user just hits enter, the default value will be returned. Example: >>> import questionary >>> questionary.confirm("Are you amazed?").ask() ? Are you amazed? Yes...
144,414
from typing import Any from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import Sequence from typing import Tuple from typing import Union from prompt_toolkit.application import Application from prompt_toolkit.formatted_text import FormattedText from pro...
Ask the user to select from a list of items. This is a multiselect, the user can choose one, none or many of the items. Example: >>> import questionary >>> questionary.checkbox( ... 'Select toppings', ... choices=[ ... "Cheese", ... "Tomato", ... "Pineapple", ... ]).ask() ? Select toppings done (2 selections) ['Cheese'...
144,415
from typing import Any from typing import Optional from .. import Style from ..constants import DEFAULT_QUESTION_PREFIX from ..prompts import text from ..question import Question DEFAULT_QUESTION_PREFIX = "?" def text( message: str, default: str = "", validate: Any = None, qmark: str = DEFAULT_QUESTIO...
A text input where a user can enter a secret which won't be displayed on the CLI. This question type can be used to prompt the user for information that should not be shown in the command line. The typed text will be replaced with ``*``. Example: >>> import questionary >>> questionary.password("What's your secret?").as...
144,416
from typing import Any from typing import Dict from typing import NamedTuple from typing import Sequence from .constants import DEFAULT_KBI_MESSAGE from .question import Question class FormField(NamedTuple): """ Represents a question within a form Args: key: The name of the form field. quest...
Create a form with multiple questions. The parameter name of a question will be the key for the answer in the returned dict. Args: kwargs: Questions to ask in the form.
144,417
from typing import Any from typing import Dict from typing import Iterable from typing import Mapping from typing import Optional from typing import Union from prompt_toolkit.output import ColorDepth from . import utils from .constants import DEFAULT_KBI_MESSAGE from .prompts import AVAILABLE_PROMPTS from .prompts impo...
Prompt the user for input on all the questions. Catches keyboard interrupts and prints a message. See :func:`unsafe_prompt` for possible question configurations. Args: questions: A list of question configs representing questions to ask. A question config may have the following options: * type - The type of question. * ...
144,418
import gradio as gr import mdtex2html from prompt2model.dataset_processor import TextualizeProcessor from prompt2model.model_executor import GenerationModelExecutor from prompt2model.prompt_parser import PromptBasedInstructionParser The provided code snippet includes necessary dependencies for implementing the `create...
Create a Gradio interface automatically. Args: model_executor: A GenerationModelExecutor to expose via a Gradio interface. prompt_parser: An instance of PromptBasedInstructionParser to parse the prompt. Returns: A Gradio interface for interacting with the model.
144,419
import gradio as gr import transformers from prompt2model.prompt_parser.base import PromptSpec class PromptSpec(ABC): """Parse and store structured information about the prompt.""" task_type: TaskType _instruction: str | None _examples: str | None def parse_from_prompt(self, prompt: str) -> None:...
Create a Gradio interface automatically. Args: model: A trained model to expose via a Gradio interface. prompt_spec: A PromptSpec to help choose the visual interface. Returns: A Gradio interface for interacting with the model.
144,420
from __future__ import annotations import logging from prompt2model.prompt_parser import PromptSpec from prompt2model.utils import API_ERRORS, api_tools, handle_api_error PROMPT_PREFIX = """HuggingFace contains models, which are each given a user-generated description. The first section of the description, delimited w...
Generate a hypothetical model description for the user's instruction. This method is based on HyDE by Gao et al 2022 (https://arxiv.org/abs/2212.10496). Args: prompt: PromptSpec object containing the user's instruction. Returns: a hypothetical model description for the user's instruction.
144,421
from __future__ import annotations METAPROMPT_BASE = """Your objective is to rerank datasets given a task (and few examples of the task) based on relevancy. Relevant factors involve how suited the dataset is for the task and whether the input/output formats of the task and the dataset data match. For each dataset, you...
Generate the full prompt for dataset reranking based on the given parameters. Args: instruction (str): Instruction of the task. examples (str): Examples of the task. datasets_infos (dict): Dictionary with dataset information. Each dataset_info object also has a configs object representing the various configs of that da...
144,422
from __future__ import annotations METAPROMPT_BASE = """Your objective is to carefully analyze the task and the dataset mentioned, and decide whether the columns are relevant input, relevant output, irrelevant for the given task, or if it is ambiguous. There should be at most one output column. It is possible to have ...
Generate prompt for column selection.
144,423
import random COMPLEX_PROMPT_TEMPLATE = """ {META_PROMPT} -------------------------------------------------------------------------------------------- Here are some examples you can refer to: - Example 1 {example_1} - Example 2 {example_2} - Example 3 {example_3} - Example 4 {example_4} --------------------------------...
Constructs a prompt template for the dataset generator. Args: instruction: The natural language instruction for the prompt. low_quality_example_string: A string representing the low quality examples. high_quality_example_string: A string representing the high quality examples. template_type: If template_type is COMPLEX...
144,424
from __future__ import annotations import argparse from prompt2model.dataset_generator import DatasetSplit, MockDatasetGenerator from prompt2model.dataset_processor import MockProcessor from prompt2model.dataset_retriever import MockRetriever from prompt2model.demo_creator import mock_gradio_create from prompt2model.mo...
Run the prompt2model pipeline locally using base/stub components.
144,425
from __future__ import annotations import json METAPROMPT_INSTRUCTION = """ As a PromptParser, your objective is to carefully analyze prompts and divide them into two distinct components: an 'Instruction' that provides the primary description of the task, and 'Demonstrations' which are optional examples showcasing the...
A (GPT-3) prompt for separating instructions from demonstrations. Args: user_prompt: A user-generated prompt asking for a response. Returns: A prompt to instruct GPT-3 to parse the user's provided prompt.
144,426
import json from typing import Any IMPLICATURES: dict[str, Any] = { "task_description": "Predict whether Speaker 2's answer to Speaker 1 counts as a yes or as a no", "samples": """input=\n\nQ: Speaker 1: 'Have you found him yet? ' Speaker 2: 'We're still looking.' \nA: \noutput=no""", "plan": """1. Create a...
Construct prompt for plan. Args: task_description: str: Description of the task. example: str: Example of the target task. dataset: list[dict]: List of dictionaries containing the dataset rows of the potentially relevant dataset for the task. num_rows: int: Number of rows from `dataset` to add to the prompt. Returns: s...
144,427
import json from typing import Any IMPLICATURES: dict[str, Any] = { "task_description": "Predict whether Speaker 2's answer to Speaker 1 counts as a yes or as a no", "samples": """input=\n\nQ: Speaker 1: 'Have you found him yet? ' Speaker 2: 'We're still looking.' \nA: \noutput=no""", "plan": """1. Create a...
Construct prompt for dataset transformation. Args: task_description: str: Description of the task. example: str: Example of the target task. plan: str: Plan for dataset transformation. dataset_row: dict: A dictionary containing the dataset row of the potentially relevant dataset to be transformed. Returns: str: Prompt ...
144,428
import datasets import requests from prompt2model.utils.logging_utils import get_formatted_logger def query(API_URL): """Returns a response json for a URL.""" try: response = requests.get(API_URL) if response.status_code == 200: return response.json() else: logger...
Fetches dataset size for a dataset in MB from hugging face API.
144,429
import datasets import requests from prompt2model.utils.logging_utils import get_formatted_logger The provided code snippet includes necessary dependencies for implementing the `make_combined_datasets` function. Write a Python function `def make_combined_datasets( dataset_list: list[datasets.Dataset], dataset_type...
Combine multiple datasets into one. Args: dataset_list: List of datasets to combine. dataset_type: Type of dataset to combine. Can be "text" or "input_output". "text" is for combining datasets with a single column "text". "input_output" is for combining datasets with 2 columns "input_col" and "output_col". Returns: A c...
144,430
import datasets import requests from prompt2model.utils.logging_utils import get_formatted_logger The provided code snippet includes necessary dependencies for implementing the `format_train_data` function. Write a Python function `def format_train_data(train_dataset: datasets.Dataset)` to solve the following problem:...
Formats the train dataset for training.
144,431
import logging The provided code snippet includes necessary dependencies for implementing the `get_formatted_logger` function. Write a Python function `def get_formatted_logger(logger_name: str)` to solve the following problem: Create a formatted logger. Args: logger_name: The name of the logger, usually the name of t...
Create a formatted logger. Args: logger_name: The name of the logger, usually the name of the component that uses the logger. Returns: A logger object.
144,432
from __future__ import annotations import json import re import openai from prompt2model.utils import api_tools, get_formatted_logger from prompt2model.utils.api_tools import API_ERRORS, handle_api_error logger = get_formatted_logger("ParseJsonResponses") The provided code snippet includes necessary dependencies for i...
Parse stuctured fields from the API response. Args: response: API response. required_keys: Required keys from the response optional_keys: Optional keys from the response Returns: If the API response is a valid JSON object and contains the required and optional keys then returns the final response as a Dictionary Else r...
144,433
from __future__ import annotations import json import re import openai from prompt2model.utils import api_tools, get_formatted_logger from prompt2model.utils.api_tools import API_ERRORS, handle_api_error logger = get_formatted_logger("ParseJsonResponses") def parse_json( response: openai.Completion, required_keys: ...
Parse prompt into specific fields, and return to the calling function. This function calls the required api, has the logic for the retrying, passes the response to the parsing function, and return the response back or throws an error Args: prompt: User prompt into specific fields required_keys: Fields that need to be p...
144,434
from __future__ import annotations import json import re import openai from prompt2model.utils import api_tools, get_formatted_logger from prompt2model.utils.api_tools import API_ERRORS, handle_api_error logger = get_formatted_logger("ParseJsonResponses") API_ERRORS = ( openai.error.APIError, openai.error.Time...
Prompts an LLM using the APIAgent, and returns the response. This function calls the required api, has the logic for retrying, returns the response back or throws an error Args: prompt: User prompt into specific fields max_api_calls: Max number of retries, defaults to 5 to avoid being stuck in an infinite loop Returns:...
144,435
from __future__ import annotations import pickle import numpy as np from tevatron.faiss_retriever import BaseFaissIPRetriever The provided code snippet includes necessary dependencies for implementing the `retrieve_objects` function. Write a Python function `def retrieve_objects( query_vector: np.ndarray, enco...
Return a ranked list of object indices and their scores. Args: query vector: Vector representation of query. encoded_datasets_path: Path to file containing encoded dataset index. depth: Number of documents to return. Returns: Ranked list of object names and their inner product similarity to the query.
144,436
from __future__ import annotations import json import os import pickle import tempfile from contextlib import nullcontext import numpy as np import torch from tevatron.arguments import DataArguments from tevatron.data import EncodeCollator, EncodeDataset from tevatron.datasets import HFCorpusDataset, HFQueryDataset fr...
Encode a query or documents. This code is mostly duplicated from tevatron/driver/encode.py in the Tevatron repository. Args: model_name_or_path: The HuggingFace model name or path to the model. file_to_encode: JSON or JSONL file containing `"text"` fields to encode. text_to_encode: String or list of strings to encode. ...
144,437
from __future__ import annotations import asyncio import json import logging import time import aiolimiter import litellm.utils import openai import openai.error import tiktoken from aiohttp import ClientSession from litellm import acompletion, completion from tqdm.asyncio import tqdm_asyncio The provided code snippe...
Handle count the tokens in a string with OpenAI's tokenizer. Args: string: The string to count. encoding_name: The name of the tokenizer to use. Returns: The number of tokens in the string.
144,438
import argparse import json import os from typing import Any from huggingface_hub import list_datasets The provided code snippet includes necessary dependencies for implementing the `parse_arguments` function. Write a Python function `def parse_arguments()` to solve the following problem: Parse command line arguments ...
Parse command line arguments for the script. Returns: argparse.Namespace: An object with the following attributes: - unprocessed_datasets_file (str): Filename for unprocessed datasets. - preprocessed_datasets_file (str): Filename for preprocessed datasets. - min_words_in_desc (int): Minimum words in a dataset descripti...
144,439
import argparse import json import os from typing import Any from huggingface_hub import list_datasets The provided code snippet includes necessary dependencies for implementing the `load_datasets` function. Write a Python function `def load_datasets(file_path: str) -> list[dict[str, Any]]` to solve the following prob...
Load all huggingface datasets from a JSON file. Check if the unfiltered dataset file exists, if not generate it. Generating it is helpful for multiple iterations of preprocessing. Args: file_path: File path of unfiltered datasets. Returns: List of datasets from HuggingFace. This doesn't have configs or rows.
144,440
import argparse import json import os from typing import Any from huggingface_hub import list_datasets The provided code snippet includes necessary dependencies for implementing the `filter_datasets` function. Write a Python function `def filter_datasets( datasets: list[dict[str, Any]], min_downloads, min_words_in...
Filter datasets based on specific criteria. Filter if description is None, if number of words in description is < 4, if number of downloads is less than a threshold, or if it is a duplicated dataset (if the description is the same). Args: datasets: List of datasets from HuggingFace. Returns: Datasets filtered based on ...
144,441
from __future__ import annotations import argparse import gc import json import threading import time from collections.abc import MutableMapping from typing import Any import datasets import requests The provided code snippet includes necessary dependencies for implementing the `parse_arguments` function. Write a Py...
Parse command line arguments for the script. Used for whether we should create the dataset index file with processing of each configuration or not Returns: argparse: Argument Parser which contains 'loads_configs' attribute, indicating if configurations should be loaded (boolean).
144,442
from __future__ import annotations import argparse import gc import json import threading import time from collections.abc import MutableMapping from typing import Any import datasets import requests def get_dataset_validity(dataset_name: str, max_retries: int = 5) -> bool: """Check if a given dataset name is val...
Process through the chunk of datasets and get dataset info to store.
144,443
import json import logging import os import time from pathlib import Path import datasets import pyfiglet import torch import transformers import yaml from datasets import concatenate_datasets, load_from_disk from termcolor import colored from prompt2model.dataset_generator.base import DatasetSplit from prompt2model.da...
Print the logo of Prompt2Model.
144,444
import json import logging import os import time from pathlib import Path import datasets import pyfiglet import torch import transformers import yaml from datasets import concatenate_datasets, load_from_disk from termcolor import colored from prompt2model.dataset_generator.base import DatasetSplit from prompt2model.da...
Parse the user input for the maximum size of the model. Args: line: The user input. default_size: The default size to use if the user does not specify a size.
144,445
from operator import itemgetter import sys from typing import TYPE_CHECKING, List, NoReturn, Optional, Tuple import click from pygments.util import ClassNotFound from rich.console import Console, RenderableType from rich.markup import escape from rich.text import Text The provided code snippet includes necessary depen...
Blend text from one color to another.
144,446
from operator import itemgetter import sys from typing import TYPE_CHECKING, List, NoReturn, Optional, Tuple import click from pygments.util import ClassNotFound from rich.console import Console, RenderableType from rich.markup import escape from rich.text import Text def on_error(message: str, error: Optional[Exceptio...
Render resource as CSV. Args: resource (str): Resource string. Returns: RenderableType: Table renderable.
144,447
from operator import itemgetter import sys from typing import TYPE_CHECKING, List, NoReturn, Optional, Tuple import click from pygments.util import ClassNotFound from rich.console import Console, RenderableType from rich.markup import escape from rich.text import Text console = Console() def read_resource(path: str, le...
Render resource as Jupyter notebook. Args: resource (str): Resource string. theme (str): Syntax theme for code cells. hyperlinks (bool): Whether to render hyperlinks in Markdown cells. lexer (str): Lexer for code cell syntax highlighting (if no language set in notebook). head (int): Display first `head` lines of each c...
144,448
from operator import itemgetter import sys from typing import TYPE_CHECKING, List, NoReturn, Optional, Tuple import click from pygments.util import ClassNotFound from rich.console import Console, RenderableType from rich.markup import escape from rich.text import Text def main( resource: str, version: bool = Fa...
null
144,449
from contextlib import contextmanager import ctypes import platform if WINDOWS: from ctypes.wintypes import DWORD, byref _STD_OUTPUT_HANDLE = -11 _ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 _KERNEL32 = ctypes.WinDLL("kernel32", use_last_error=True) def _get_console_mode() -> int: """Get the...
Context manager to enable virtual terminal processing on enter, and restore the previous setting on exit. Does nothing if run on a non-Widows platfrom.
144,450
from contextlib import contextmanager import ctypes import platform The provided code snippet includes necessary dependencies for implementing the `enable_windows_virtual_terminal_processing` function. Write a Python function `def enable_windows_virtual_terminal_processing()` to solve the following problem: Context ma...
Context manager to enable virtual terminal processing on enter, and restore the previous setting on exit. Does nothing if run on a non-Widows platfrom.
144,451
from __future__ import annotations from harlequin.options import ( FlagOption, SelectOption, TextOption, ) def _float_validator(s: str | None) -> tuple[bool, str]: if s is None: return True, "" try: _ = float(s) except ValueError: return False, f"Cannot convert {s} to a ...
null
144,452
from __future__ import annotations from harlequin.options import ( FlagOption, SelectOption, TextOption, ) def _int_validator(s: str | None) -> tuple[bool, str]: if s is None: return True, "" try: _ = int(s) except ValueError: return False, f"Cannot convert {s} to an int...
null
144,453
from __future__ import annotations import sqlite3 from harlequin.autocomplete.completion import HarlequinCompletion class HarlequinCompletion: def __lt__(self, other: "HarlequinCompletion") -> bool: def __le__(self, other: "HarlequinCompletion") -> bool: def __gt__(self, other: "HarlequinCompletion") ->...
null
144,454
from __future__ import annotations import duckdb def get_completion_data( cur: duckdb.DuckDBPyConnection, ) -> list[tuple[str, str, int, str | None]]: keyword_data = cur.execute( """ select distinct keyword_name as label, 'kw' as type_label, case when keyword...
null
144,455
from __future__ import annotations import hashlib import json import pickle from collections import defaultdict from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any, Sequence from platformdirs import user_cache_dir from harlequin.catalog import Catalog from harlequin.history ...
null
144,456
from __future__ import annotations import hashlib import json import pickle from collections import defaultdict from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any, Sequence from platformdirs import user_cache_dir from harlequin.catalog import Catalog from harlequin.history ...
null
144,457
from __future__ import annotations import hashlib import json import pickle from collections import defaultdict from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any, Sequence from platformdirs import user_cache_dir from harlequin.catalog import Catalog from harlequin.history ...
null
144,458
from __future__ import annotations import sys from pathlib import Path from typing import Any, Sequence import rich_click as click from harlequin import Harlequin from harlequin.adapter import HarlequinAdapter from harlequin.catalog_cache import get_connection_hash from harlequin.colors import GREEN, PINK, PURPLE, YELL...
The main entrypoint for the Harlequin IDE. Builds and executes the click Command.
144,459
from __future__ import annotations import itertools import re from typing import Iterable from harlequin.autocomplete.completion import HarlequinCompletion from harlequin.autocomplete.constants import get_functions, get_keywords from harlequin.catalog import Catalog, CatalogItem class WordCompleter: def __init__( ...
null
144,460
from __future__ import annotations from harlequin.options import ( FlagOption, HarlequinCopyFormat, SelectOption, TextOption, ) def _validate_int(raw: str) -> tuple[bool, str | None]: try: int(raw) except ValueError: return False, "Must be an integer." else: return Tr...
null
144,461
from __future__ import annotations from harlequin.options import ( FlagOption, HarlequinCopyFormat, SelectOption, TextOption, ) def _validate_float(raw: str) -> tuple[bool, str | None]: try: float(raw) except ValueError: return False, "Must be a floating point number." else:...
null
144,462
from __future__ import annotations import re from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Callable, Generator, Iterable, Sequence import click import questionary from textual.validation import ValidationResult, Validator from textual.widget import Widget from harlequin.colors imp...
null
144,463
from __future__ import annotations from pathlib import Path from typing import Any, Callable, Dict, Sequence, Tuple from textual import events from textual.app import ComposeResult from textual.containers import Horizontal, Vertical, VerticalScroll from textual.css.query import QueryError from textual.screen import Mod...
null
144,464
from typing import Dict, Type, Union from pygments.style import Style as PygmentsStyle from pygments.styles import get_style_by_name from pygments.token import ( Comment, Error, Keyword, Literal, Name, Number, Operator, Punctuation, String, Token, ) from pygments.util import Clas...
null
144,465
import pickle from dataclasses import dataclass from pathlib import Path from typing import List, Union from platformdirs import user_cache_dir from textual.widgets.text_area import Selection class Cache: focus_index: int # currently doesn't impact focus on load buffers: List[BufferState] def get_cache_file() ...
Returns a Cache (a list of strings) by loading from a pickle saved to disk
144,466
import pickle from dataclasses import dataclass from pathlib import Path from typing import List, Union from platformdirs import user_cache_dir from textual.widgets.text_area import Selection class Cache: focus_index: int # currently doesn't impact focus on load buffers: List[BufferState] def get_cache_file() ...
Updates dumps buffer contents to to disk
144,467
import asyncio from unittest.mock import patch from harlequin import Harlequin from harlequin.editor_cache import BufferState, Cache from harlequin_duckdb import DuckDbAdapter from textual.widgets.text_area import Selection class BufferState: class Cache: async def load_lots_of_buffers() -> None: with patch("ha...
null
144,468
import asyncio from harlequin import Harlequin from harlequin_duckdb import DuckDbAdapter from pygments.styles import get_all_styles TEXT = """ select drivers.surname, drivers.forename, drivers.nationality, avg(driver_standings.position) as avg_standing, avg(driver_standings.points) as avg_points fr...
null
144,469
import asyncio from unittest.mock import patch from harlequin import Harlequin from harlequin.editor_cache import BufferState, Cache from harlequin_duckdb import DuckDbAdapter from textual.widgets.text_area import Selection class BufferState: selection: Selection text: str class Cache: focus_index: int ...
null
144,470
import argparse from fastsam import FastSAM, FastSAMPrompt import ast import torch from PIL import Image from utils.tools import convert_box_xywh_to_xyxy def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--model_path", type=str, default="./weights/FastSAM.pt", help="model" ...
null
144,471
import numpy as np import torch from PIL import Image def convert_box_xywh_to_xyxy(box): x1 = box[0] y1 = box[1] x2 = box[0] + box[2] y2 = box[1] + box[3] return [x1, y1, x2, y2]
null
144,472
import numpy as np import torch from PIL import Image def adjust_bboxes_to_image_border(boxes, image_shape, threshold=20): '''Adjust bounding boxes to stick to image border if they are within a certain threshold. Args: boxes: (n, 4) image_shape: (height, width) threshold: pixel threshold Returns...
Compute the Intersection-Over-Union of a bounding box with respect to an array of other bounding boxes. Args: box1: (4, ) boxes: (n, 4) Returns: high_iou_indices: Indices of boxes with IoU > thres
144,473
import numpy as np import torch from PIL import Image def image_to_np_ndarray(image): if type(image) is str: return np.array(Image.open(image)) elif issubclass(type(image), Image.Image): return np.array(image) elif type(image) is np.ndarray: return image return None
null
144,474
import argparse import cv2 import shutil import ast from cog import BasePredictor, Input, Path from ultralytics import YOLO from utils.tools import * def prompt(results, args, box=None, point=None, text=None): ori_img = cv2.imread(args.img_path) ori_h = ori_img.shape[0] ori_w = ori_img.shape[1] if box:...
null
144,475
from ultralytics import YOLO import gradio as gr import torch from utils.tools_gradio import fast_process from utils.tools import format_results, box_prompt, point_prompt, text_prompt from PIL import ImageDraw import numpy as np model = YOLO('./weights/FastSAM.pt') device = torch.device( "cuda" if torch.cuda.is...
null
144,476
from ultralytics import YOLO import gradio as gr import torch from utils.tools_gradio import fast_process from utils.tools import format_results, box_prompt, point_prompt, text_prompt from PIL import ImageDraw import numpy as np model = YOLO('./weights/FastSAM.pt') device = torch.device( "cuda" if torch.cuda.is...
null
144,477
from ultralytics import YOLO import gradio as gr import torch from utils.tools_gradio import fast_process from utils.tools import format_results, box_prompt, point_prompt, text_prompt from PIL import ImageDraw import numpy as np global_points = [] global_point_label = [] with gr.Blocks(css=css, title='Fast Segment Anyt...
null
144,478
from ultralytics import YOLO import gradio as gr import torch from utils.tools_gradio import fast_process from utils.tools import format_results, box_prompt, point_prompt, text_prompt from PIL import ImageDraw import numpy as np def clear(): return None, None
null
144,479
from ultralytics import YOLO import gradio as gr import torch from utils.tools_gradio import fast_process from utils.tools import format_results, box_prompt, point_prompt, text_prompt from PIL import ImageDraw import numpy as np def clear_text(): return None, None, None
null
144,480
import numpy as np from PIL import Image import matplotlib.pyplot as plt import cv2 import torch import os import sys import clip def convert_box_xywh_to_xyxy(box): if len(box) == 4: return [box[0], box[1], box[0] + box[2], box[1] + box[3]] else: result = [] for b in box: b ...
null
144,481
import numpy as np from PIL import Image import matplotlib.pyplot as plt import cv2 import torch import os import sys import clip def filter_masks(annotations): # filter the overlap mask annotations.sort(key=lambda x: x["area"], reverse=True) to_remove = set() for i in range(0, len(annotations)): ...
null
144,482
import numpy as np from PIL import Image import matplotlib.pyplot as plt import cv2 import torch import os import sys import clip def box_prompt(masks, bbox, target_height, target_width): h = masks.shape[1] w = masks.shape[2] if h != target_height or w != target_width: bbox = [ int(bbox...
null
144,483
import time from langchain.chains.natbot.base import NatBotChain from langchain.chains.natbot.crawler import Crawler class Crawler: def __init__(self) -> None: try: from playwright.sync_api import sync_playwright except ImportError: raise ValueError( "Could n...
Run command.
144,484
import os import requests from langchain.agents import initialize_agent, Tool from langchain.tools.bing_search.tool import BingSearchRun, BingSearchAPIWrapper from langchain.chains.conversation.memory import ConversationBufferMemory from langchain.chains import PALChain from langchain.llms import AzureOpenAI from langc...
null
144,485
import importlib.util import logging from typing import Any, Callable, List, Mapping, Optional from pydantic import BaseModel, Extra from langchain.llms.self_hosted import SelfHostedPipeline from langchain.llms.utils import enforce_stop_tokens VALID_TASKS = ("text2text-generation", "text-generation") def enforce_stop_...
Inference function to send to the remote hardware. Accepts a Hugging Face pipeline (or more likely, a key pointing to such a pipeline on the cluster's object store) and returns generated text.
144,486
import importlib.util import logging from typing import Any, Callable, List, Mapping, Optional from pydantic import BaseModel, Extra from langchain.llms.self_hosted import SelfHostedPipeline from langchain.llms.utils import enforce_stop_tokens DEFAULT_MODEL_ID = "gpt2" DEFAULT_TASK = "text-generation" VALID_TASKS = ("t...
Inference function to send to the remote hardware. Accepts a huggingface model_id and returns a pipeline for the task.
144,487
import os import logging import sys from typing import ( Any, Callable, Dict, Generator, List, Mapping, Optional, Set, Tuple, Union, ) from pydantic import BaseModel, Extra, Field, root_validator from tenacity import ( before_sleep_log, retry, retry_if_exception_type,...
Update token usage.
144,488
import os import logging import sys from typing import ( Any, Callable, Dict, Generator, List, Mapping, Optional, Set, Tuple, Union, ) from pydantic import BaseModel, Extra, Field, root_validator from tenacity import ( before_sleep_log, retry, retry_if_exception_type,...
Update response from the stream response.
144,489
import os import logging import sys from typing import ( Any, Callable, Dict, Generator, List, Mapping, Optional, Set, Tuple, Union, ) from pydantic import BaseModel, Extra, Field, root_validator from tenacity import ( before_sleep_log, retry, retry_if_exception_type,...
null
144,490
import json from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Dict, List, Mapping, Optional, Tuple, Union import yaml from pydantic import BaseModel, Extra, Field, validator import langchain from langchain.callbacks import get_callback_manager from langchain.callbacks.base import Base...
null
144,491
import json from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Dict, List, Mapping, Optional, Tuple, Union import yaml from pydantic import BaseModel, Extra, Field, validator import langchain from langchain.callbacks import get_callback_manager from langchain.callbacks.base import Base...
Get prompts that are already cached.
144,492
import json from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Dict, List, Mapping, Optional, Tuple, Union import yaml from pydantic import BaseModel, Extra, Field, validator import langchain from langchain.callbacks import get_callback_manager from langchain.callbacks.base import Base...
Update the cache and get the LLM output.
144,493
import importlib.util import logging import pickle from typing import Any, Callable, List, Mapping, Optional from pydantic import BaseModel, Extra from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens def enforce_stop_tokens(text: str, stop: List[str]) -> str: """Cut off the text...
Inference function to send to the remote hardware. Accepts a pipeline callable (or, more likely, a key pointing to the model on the cluster's object store) and returns text predictions for each document in the batch.
144,494
import importlib.util import logging import pickle from typing import Any, Callable, List, Mapping, Optional from pydantic import BaseModel, Extra from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens logger = logging.getLogger() The provided code snippet includes necessary dependenc...
Send a pipeline to a device on the cluster.
144,495
import os from typing import Any, Dict, Optional, Tuple import requests import io import re from PIL import Image The provided code snippet includes necessary dependencies for implementing the `get_from_dict_or_env` function. Write a Python function `def get_from_dict_or_env( data: Dict[str, Any], key: str, env_ke...
Get a value from a dictionary or an environment variable.
144,496
import os from typing import Any, Dict, Optional, Tuple import requests import io import re from PIL import Image import requests The provided code snippet includes necessary dependencies for implementing the `download_image` function. Write a Python function `def download_image(url:str)` to solve the following probl...
Download raw image from url
144,497
from typing import Any, Mapping, Optional, Protocol from langchain.chains.combine_documents.base import BaseCombineDocumentsChain from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain from langchain.chains.combine_documents.map_rerank import MapRerankDocumentsChain from langchain.chains.comb...
Load question answering with sources chain. Args: llm: Language Model to use in the chain. chain_type: Type of document combining chain to use. Should be one of "stuff", "map_reduce", and "refine". verbose: Whether chains should be run in verbose mode or not. Note that this applies to all chains that make up the final ...
144,498
import json from pathlib import Path from typing import Any, Union import yaml from langchain.chains.api.base import APIChain from langchain.chains.base import Chain from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain from langchain.chains.combine_documents.map_rerank import MapRerankDocum...
Load LLM chain from config dict.
144,499
import json from pathlib import Path from typing import Any, Union import yaml from langchain.chains.api.base import APIChain from langchain.chains.base import Chain from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain from langchain.chains.combine_documents.map_rerank import MapRerankDocum...
Load hypothetical document embedder chain from config dict.
144,500
import json from pathlib import Path from typing import Any, Union import yaml from langchain.chains.api.base import APIChain from langchain.chains.base import Chain from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain from langchain.chains.combine_documents.map_rerank import MapRerankDocum...
null
144,501
import json from pathlib import Path from typing import Any, Union import yaml from langchain.chains.api.base import APIChain from langchain.chains.base import Chain from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain from langchain.chains.combine_documents.map_rerank import MapRerankDocum...
null
144,502
import json from pathlib import Path from typing import Any, Union import yaml from langchain.chains.api.base import APIChain from langchain.chains.base import Chain from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain from langchain.chains.combine_documents.map_rerank import MapRerankDocum...
null