id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
179,734 | from dataclasses import asdict
from datetime import datetime
from logging import getLogger
from typing import Optional
from urllib.parse import urlencode
import justext
import requests
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadReque... | null |
179,735 | from dataclasses import asdict
from datetime import datetime
from logging import getLogger
from typing import Optional
from urllib.parse import urlencode
import justext
import requests
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadReque... | null |
179,736 | from dataclasses import asdict
from datetime import datetime
from logging import getLogger
from typing import Optional
from urllib.parse import urlencode
import justext
import requests
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadReque... | null |
179,737 | from dataclasses import asdict
from datetime import datetime
from logging import getLogger
from typing import Optional
from urllib.parse import urlencode
import justext
import requests
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadReque... | null |
179,738 | from dataclasses import asdict
from datetime import datetime
from logging import getLogger
from typing import Optional
from urllib.parse import urlencode
import justext
import requests
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadReque... | null |
179,739 | import os
import pickle
from datetime import datetime
from pathlib import Path
from queue import Queue
from mwmbl.indexer import record_urls_in_database
def run_update_urls_on_fixed_batches():
with open(Path(os.environ["HOME"]) / "data" / "mwmbl" / "hashed-batches.pickle", "rb") as file:
batches = pickle.l... | null |
179,740 | from collections import defaultdict
from random import Random
from zstandard import ZstdCompressor, ZstdDecompressor
random = Random(1)
def test_compress_decompress():
error_type_counts = defaultdict(int)
for i in range(10000):
compressor = ZstdCompressor()
decompressor = ZstdDecompressor()
... | null |
179,741 | import glob
import gzip
import json
from collections import defaultdict, Counter
from urllib.parse import urlparse
from mwmbl.crawler import HashedBatch
from mwmbl.indexer import CRAWL_GLOB, MWMBL_DATA_DIR
def get_urls():
for path in glob.glob(CRAWL_GLOB):
data = json.load(gzip.open(path))
batch = H... | null |
179,742 | import multiprocessing
import os
import string
from multiprocessing.pool import ThreadPool
from pathlib import Path
from random import Random
from mwmbl.tinysearchengine.indexer import TinyIndex, Document
random = Random(2)
def random_string():
randomly_generated_string = "".join([random.choice(string.ascii_letter... | null |
179,743 | import multiprocessing
import os
import string
from multiprocessing.pool import ThreadPool
from pathlib import Path
from random import Random
from mwmbl.tinysearchengine.indexer import TinyIndex, Document
random = Random(2)
indexer = TinyIndex(Document, str(INDEX_PATH), 'r')
indexer.__enter__()
def read_page(page_index... | null |
179,744 | import json
from mwmbl.indexer import TOP_DOMAINS_JSON_PATH
from mwmbl.hn_top_domains_filtered import DOMAINS
DOMAINS = {'blog.samaltman.com': 0.9906157038365982,
'paulgraham.com': 0.9900792629020208,
'blog.rust-lang.org': 0.9890328852259848,
'blog.ycombinator.com': 0.9883892917770221,
'ciechanow.ski': 0.9880439204029... | null |
179,745 | from mwmbl.tinysearchengine import TinyIndex, Document
def run():
urls = set()
with TinyIndex(Document, 'data/index.tinysearch') as index:
for i in range(index.num_pages):
print("Page", i)
page = index.get_page(i)
new_urls = {doc.url for doc in page}
urls... | null |
179,746 | import sqlite3
from mwmbl.indexer import URLS_PATH
from mwmbl.app import get_config_and_index
def create_database():
with sqlite3.connect(URLS_PATH) as connection:
connection.execute("""
CREATE TABLE urls (url TEXT PRIMARY KEY)
""")
def get_url_batches():
config, index = get_config_a... | null |
179,747 | import os
from pathlib import Path
from random import Random
import numpy as np
from scipy.stats import sem
from mwmbl.tinysearchengine.indexer import TinyIndex, Document, _trim_items_to_page, astuple
from zstandard import ZstdCompressor
from mwmbl.utils import add_term_info
random = Random(1)
INDEX_PATH = Path(__file_... | null |
179,748 | import requests
from mwmbl.crawler import Batch, Item, ItemContent
URL = 'http://localhost:5000/crawler/batches/'
def run():
batch = Batch(user_id='test_user_id111111111111111111111111', items=[Item(
url='https://www.theguardian.com/stage/2007/nov/18/theatre',
content=ItemContent(
title... | null |
179,749 | import glob
import gzip
import json
import requests
from mwmbl.indexer import CRAWL_GLOB
API_ENDPOINT = "http://95.216.215.29/batches/historical"
def total_num_batches():
return len(glob.glob(CRAWL_GLOB))
def get_batches():
for path in sorted(glob.glob(CRAWL_GLOB)):
hashed_batch = json.load(gzip.open(pa... | null |
179,750 | from setuptools import find_packages, setup
from typing import List
def parse_requirements(file_name: str) -> List[str]:
with open(file_name) as f:
return [
require.strip() for require in f
if require.strip() and not require.startswith('#')
] | null |
179,751 | from setuptools import find_packages, setup
from typing import List
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content | null |
179,752 | from setuptools import find_packages, setup
from typing import List
version_file = 'modelscope_agent/version.py'
def get_version():
with open(version_file, 'r', encoding='utf-8') as f:
exec(compile(f.read(), version_file, 'exec'))
return locals()['__version__'] | null |
179,753 | from __future__ import annotations
import os
import sys
from functools import partial
import gradio as gr
from dotenv import load_dotenv
from gradio_chatbot import ChatBot
from modelscope_agent.agent import AgentExecutor
from modelscope_agent.llm import LLMFactory
from predict import stream_predict, upload_image
from m... | null |
179,754 | from __future__ import annotations
import os
import re
import traceback
import uuid
from copy import deepcopy
import gradio as gr
import json
def stream_predict(
chatbot, # ChatBot
user_input, # Textbox
upload_image_url, # imageUrl
agent # agent
):
print(f'upload_image_url: {upl... | null |
179,755 | from __future__ import annotations
import os
import re
import traceback
import uuid
from copy import deepcopy
import gradio as gr
import json
def upload_image(file):
gr_file_path = f'./file={file.name}'
return [
gr.HTML.update(
f"<div class=\"uploaded-image-box\"><img src=\"{gr_file_path}... | null |
179,756 | import os
import random
import shutil
import traceback
import gradio as gr
import modelscope_gradio_components as mgr
from config_utils import get_avatar_image, get_ci_dir, parse_configuration
from gradio_utils import format_cover_html
from modelscope_agent.schemas import Message
from modelscope_agent.utils.logger impo... | null |
179,757 | import os
import random
import shutil
import traceback
import gradio as gr
import json
import modelscope_gradio_components as mgr
import yaml
from builder_core import (beauty_output, gen_response_and_process,
init_builder_chatbot_agent)
from config_utils import (DEFAULT_AGENT_DIR, Config, get_... | null |
179,758 | import os
import random
import shutil
import traceback
import gradio as gr
import json
import modelscope_gradio_components as mgr
import yaml
from builder_core import (beauty_output, gen_response_and_process,
init_builder_chatbot_agent)
from config_utils import (DEFAULT_AGENT_DIR, Config, get_... | null |
179,759 | import os
import random
import shutil
import traceback
import gradio as gr
import json
import modelscope_gradio_components as mgr
import yaml
from builder_core import (beauty_output, gen_response_and_process,
init_builder_chatbot_agent)
from config_utils import (DEFAULT_AGENT_DIR, Config, get_... | null |
179,760 | import os
import random
import shutil
import traceback
import gradio as gr
import json
import modelscope_gradio_components as mgr
import yaml
from builder_core import (beauty_output, gen_response_and_process,
init_builder_chatbot_agent)
from config_utils import (DEFAULT_AGENT_DIR, Config, get_... | null |
179,761 | import os
import random
import shutil
import traceback
import gradio as gr
import json
import modelscope_gradio_components as mgr
import yaml
from builder_core import (beauty_output, gen_response_and_process,
init_builder_chatbot_agent)
from config_utils import (DEFAULT_AGENT_DIR, Config, get_... | null |
179,762 | import os
import random
import shutil
import traceback
import gradio as gr
import json
import modelscope_gradio_components as mgr
import yaml
from builder_core import (beauty_output, gen_response_and_process,
init_builder_chatbot_agent)
from config_utils import (DEFAULT_AGENT_DIR, Config, get_... | null |
179,763 | import os
import random
import shutil
import traceback
import gradio as gr
import json
import modelscope_gradio_components as mgr
import yaml
from builder_core import (beauty_output, gen_response_and_process,
init_builder_chatbot_agent)
from config_utils import (DEFAULT_AGENT_DIR, Config, get_... | null |
179,764 | import os
import random
import shutil
import traceback
import gradio as gr
import json
import modelscope_gradio_components as mgr
import yaml
from builder_core import (beauty_output, gen_response_and_process,
init_builder_chatbot_agent)
from config_utils import (DEFAULT_AGENT_DIR, Config, get_... | null |
179,765 |
The provided code snippet includes necessary dependencies for implementing the `parse_action_response` function. Write a Python function `def parse_action_response(response: str) -> Tuple[str, Dict]` to solve the following problem:
parse response of llm to get tool name and parameters Args: response (str): llm respon... | parse response of llm to get tool name and parameters Args: response (str): llm response, it should conform to some predefined format Returns: tuple[str, dict]: tuple of tool name and parameters |
179,766 |
def convert_url(text, new_filename):
# Define the pattern to search for
# This pattern captures the text inside the square brackets, the path, and the filename
pattern = r'!\[([^\]]+)\]\(([^)]+)\)'
# Define the replacement pattern
# \1 is a backreference to the text captured by the first group ([... | null |
179,767 |
def postprocess_messages(
message_pairs: list[list[str | tuple[str] | tuple[str, str] | None]
| tuple]
) -> list[list[str | dict | None]]:
if message_pairs is None:
return []
processed_messages = []
for message_pair in message_pairs:
assert isinstance(
... | null |
179,768 | import os
from typing import Dict, Iterator, List, Optional
from zhipuai import ZhipuAI
from .base import BaseChatModel, register_llm
def stream_output(response, **kwargs):
func_call = {
'name': None,
'arguments': '',
}
for chunk in response:
delta = chunk.choices[0].delta
i... | null |
179,769 | from abc import ABC, abstractmethod
from typing import Dict, Iterator, List, Optional, Union
from modelscope_agent.utils.retry import retry
from modelscope_agent.utils.tokenization_utils import count_tokens
from modelscope_agent.utils.utils import print_traceback
LLM_REGISTRY = {}
def register_llm(name):
def deco... | null |
179,770 | import os
from http import HTTPStatus
from typing import Dict, Iterator, List, Optional, Union
import dashscope
from modelscope_agent.utils.logger import agent_logger as logger
from modelscope_agent.utils.tokenization_utils import count_tokens
from .base import BaseChatModel, register_llm
def stream_output(response, *... | null |
179,771 | import hashlib
import os
from modelscope_agent.utils.logger import agent_logger as logger
from modelscope_agent.utils.utils import (print_traceback, read_text_from_file,
save_text_to_file)
from .base import BaseStorage
def hash_sha256(key):
hash_object = hashlib.sha256(key... | null |
179,772 | import copy
import datetime
import os
import re
from typing import Dict, List
from urllib.parse import unquote, urlparse
import json
import json5
from modelscope_agent.schemas import Document
from modelscope_agent.storage import BaseStorage, DocumentStorage
from modelscope_agent.tools.base import BaseTool, register_too... | null |
179,773 | import copy
import datetime
import os
import re
from typing import Dict, List
from urllib.parse import unquote, urlparse
import json
import json5
from modelscope_agent.schemas import Document
from modelscope_agent.storage import BaseStorage, DocumentStorage
from modelscope_agent.tools.base import BaseTool, register_too... | null |
179,774 | import copy
import datetime
import os
import re
from typing import Dict, List
from urllib.parse import unquote, urlparse
import json
import json5
from modelscope_agent.schemas import Document
from modelscope_agent.storage import BaseStorage, DocumentStorage
from modelscope_agent.tools.base import BaseTool, register_too... | filter records from meta-data |
179,775 | import copy
import datetime
import os
import re
from typing import Dict, List
from urllib.parse import unquote, urlparse
import json
import json5
from modelscope_agent.schemas import Document
from modelscope_agent.storage import BaseStorage, DocumentStorage
from modelscope_agent.tools.base import BaseTool, register_too... | null |
179,776 | import os
from enum import Enum
from pydantic import BaseModel, model_validator
class AuthenticationKey(Enum):
def to_dict(cls):
class BingWebSearcher(WebSearcher):
def __init__(
self,
timeout=3000,
mkt='en-US',
endpoint='https://api.bing.microsoft.com/v7.0/sea... | null |
179,777 | import os
import re
from typing import List, Optional
import json
import requests
from jsonschema import RefResolver
from modelscope_agent.tools.base import BaseTool, register_tool
from pydantic import BaseModel, ValidationError
from requests.exceptions import RequestException, Timeout
def parse_responses_parameters(p... | null |
179,778 | import os
import subprocess
from http import HTTPStatus
from typing import Any, Dict, List, Optional
from modelscope_agent.tools.base import BaseTool, register_tool
from pydantic import ValidationError
def _preprocess(input_file, output_file):
ret = subprocess.call([
'ffmpeg', '-y', '-i', input_file, '-f',... | null |
179,779 | from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Union
import json
import json5
from modelscope_agent.tools.base import BaseTool
from modelscope_agent.utils.utils import has_chinese_chars
TOOL_REGISTRY = {}
def register_tool(name):
def decorator(cls):
TOOL_REGISTRY[name] = cls
... | null |
179,780 | import math import os
import re
import signal
import json
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib.font_manager import FontProperties
from sympy import Eq, solve, symbols
def input(*args, **kwargs): # noqa
raise NotImplem... | null |
179,781 | import math import os
import re
import signal
import json
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib.font_manager import FontProperties
from sympy import Eq, solve, symbols
def _m6_timout_handler(_signum=None, _frame=None):
... | null |
179,782 | from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Union
import json
import json5
from modelscope_agent.utils.utils import has_chinese_chars
TOOL_REGISTRY = {}
def register_tool(name):
def decorator(cls):
TOOL_REGISTRY[name] = cls
return cls
return decorator | null |
179,783 | import hashlib
from typing import Dict, Optional
from modelscope_agent.storage import DocumentStorage
from modelscope_agent.tools.base import BaseTool, register_tool
def hash_sha256(key):
hash_object = hashlib.sha256(key.encode())
key = hash_object.hexdigest()
return key | null |
179,784 | import os
import re
import tempfile
import uuid
from typing import Dict
import numpy as np
import requests
from PIL import Image
from requests.exceptions import RequestException
class OutputWrapper:
"""
Wrapper for output of tool execution when output is image, video, audio, etc.
In this wrapper, __repr__()... | null |
179,785 | import datetime
import os
import re
import socket
import sys
import traceback
from typing import Literal, Optional, Union
from urllib.parse import unquote_plus, urlparse
import jieba
import json5
from dashscope.common.error import InvalidInput, UploadFileException
from dashscope.utils.oss_utils import OssUtils
from jie... | null |
179,786 | import datetime
import os
import re
import socket
import sys
import traceback
from typing import Literal, Optional, Union
from urllib.parse import unquote_plus, urlparse
import jieba
import json5
from dashscope.common.error import InvalidInput, UploadFileException
from dashscope.utils.oss_utils import OssUtils
from jie... | null |
179,787 | import datetime
import os
import re
import socket
import sys
import traceback
from typing import Literal, Optional, Union
from urllib.parse import unquote_plus, urlparse
import jieba
import json5
from dashscope.common.error import InvalidInput, UploadFileException
from dashscope.utils.oss_utils import OssUtils
from jie... | null |
179,788 | import datetime
import os
import re
import socket
import sys
import traceback
from typing import Literal, Optional, Union
from urllib.parse import unquote_plus, urlparse
import jieba
import json5
from dashscope.common.error import InvalidInput, UploadFileException
from dashscope.utils.oss_utils import OssUtils
from jie... | null |
179,789 | import datetime
import os
import re
import socket
import sys
import traceback
from typing import Literal, Optional, Union
from urllib.parse import unquote_plus, urlparse
import jieba
import json5
from dashscope.common.error import InvalidInput, UploadFileException
from dashscope.utils.oss_utils import OssUtils
from jie... | null |
179,790 | import datetime
import os
import re
import socket
import sys
import traceback
from typing import Literal, Optional, Union
from urllib.parse import unquote_plus, urlparse
import jieba
import json5
from dashscope.common.error import InvalidInput, UploadFileException
from dashscope.utils.oss_utils import OssUtils
from jie... | null |
179,791 | import datetime
import os
import re
import socket
import sys
import traceback
from typing import Literal, Optional, Union
from urllib.parse import unquote_plus, urlparse
import jieba
import json5
from dashscope.common.error import InvalidInput, UploadFileException
from dashscope.utils.oss_utils import OssUtils
from jie... | null |
179,792 | import datetime
import os
import re
import socket
import sys
import traceback
from typing import Literal, Optional, Union
from urllib.parse import unquote_plus, urlparse
import jieba
import json5
from dashscope.common.error import InvalidInput, UploadFileException
from dashscope.utils.oss_utils import OssUtils
from jie... | null |
179,793 | import datetime
import os
import re
import socket
import sys
import traceback
from typing import Literal, Optional, Union
from urllib.parse import unquote_plus, urlparse
import jieba
import json5
from dashscope.common.error import InvalidInput, UploadFileException
from dashscope.utils.oss_utils import OssUtils
from jie... | This function is used to convert local file to get its oss url. Args: model(str): Theoretically, you can set this parameter freely. It will only affect the information of the oss url and will not affect the function function. file_to_upload(str): the local file path which you need to convert to oss url.And it should st... |
179,794 | import datetime
import os
import re
import socket
import sys
import traceback
from typing import Literal, Optional, Union
from urllib.parse import unquote_plus, urlparse
import jieba
import json5
from dashscope.common.error import InvalidInput, UploadFileException
from dashscope.utils.oss_utils import OssUtils
from jie... | Check the input length and limit the length, Args: check_body: the input to be checked, should be a list of message or single prompt string max_length: the maximum length of the check_body Returns: the output with the length limited |
179,795 | import time
from functools import wraps
from modelscope_agent.utils.logger import agent_logger as logger
The provided code snippet includes necessary dependencies for implementing the `retry` function. Write a Python function `def retry(max_retries=3, delay_seconds=1, return_str=False)` to solve the following problem:... | Retry decorator with exponential backoff. Args: max_retries: max retry times delay_seconds: delay seconds between retries return_str: want to return in str format, set it to True Returns:func |
179,796 | import base64
import logging
import os
import unicodedata
from dataclasses import dataclass, field
from pathlib import Path
from typing import Collection, Dict, List, Set, Tuple, Union
import tiktoken
def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
with open(tiktoken_bpe_file, 'rb') as f:
... | null |
179,797 | import logging
import os
from datetime import datetime
from logging.handlers import RotatingFileHandler
from typing import Dict
import json
class JsonFormatter(logging.Formatter):
"""
Custom formatter to output logs in JSON format.
"""
def format(self, record):
log_record = {
'timest... | null |
179,798 | import os
from dataclasses import dataclass, field
from functools import partial
from typing import Optional
import json
import torch
from swift import Swift, get_logger
from swift.utils import parse_args, print_model_info, seed_everything
from tqdm import tqdm
from transformers import BitsAndBytesConfig, GenerationCon... | null |
179,799 | import os
from dataclasses import dataclass, field
from functools import partial
from typing import List, Optional
import torch
import torch.distributed as dist
from swift import (HubStrategy, LoraConfig, Seq2SeqTrainer,
Seq2SeqTrainingArguments, Swift, get_logger)
from swift.llm.utils import data_co... | null |
179,800 | import os
import re
from typing import List, Optional, Tuple
import json
import matplotlib.pyplot as plt
import torch
import torch.distributed as dist
from rouge import Rouge
from swift import get_logger
from swift.utils.tb_utils import (TB_COLOR, TB_COLOR_SMOOTH,
read_tensorboard_file... | null |
179,801 | import os
import re
from typing import List, Optional, Tuple
import json
import matplotlib.pyplot as plt
import torch
import torch.distributed as dist
from rouge import Rouge
from swift import get_logger
from swift.utils.tb_utils import (TB_COLOR, TB_COLOR_SMOOTH,
read_tensorboard_file... | null |
179,802 | import os
import re
from typing import List, Optional, Tuple
import json
import matplotlib.pyplot as plt
import torch
import torch.distributed as dist
from rouge import Rouge
from swift import get_logger
from swift.utils.tb_utils import (TB_COLOR, TB_COLOR_SMOOTH,
read_tensorboard_file... | null |
179,803 | import os
import re
from typing import List, Optional, Tuple
import json
import matplotlib.pyplot as plt
import torch
import torch.distributed as dist
from rouge import Rouge
from swift import get_logger
from swift.utils.tb_utils import (TB_COLOR, TB_COLOR_SMOOTH,
read_tensorboard_file... | null |
179,804 | import os
import re
from typing import List, Optional, Tuple
import json
import matplotlib.pyplot as plt
import torch
import torch.distributed as dist
from rouge import Rouge
from swift import get_logger
from swift.utils.tb_utils import (TB_COLOR, TB_COLOR_SMOOTH,
read_tensorboard_file... | dtype: Literal['fp16', 'bf16', 'fp32'] |
179,805 | import os
import re
from typing import List, Optional, Tuple
import json
import matplotlib.pyplot as plt
import torch
import torch.distributed as dist
from rouge import Rouge
from swift import get_logger
from swift.utils.tb_utils import (TB_COLOR, TB_COLOR_SMOOTH,
read_tensorboard_file... | ref: https://github.com/artidoro/qlora |
179,806 | import os
import re
from typing import List, Optional, Tuple
import json
import matplotlib.pyplot as plt
import torch
import torch.distributed as dist
from rouge import Rouge
from swift import get_logger
from swift.utils.tb_utils import (TB_COLOR, TB_COLOR_SMOOTH,
read_tensorboard_file... | null |
179,807 | import os
import re
from typing import List, Optional, Tuple
import json
import matplotlib.pyplot as plt
import torch
import torch.distributed as dist
from rouge import Rouge
from swift import get_logger
from swift.utils.tb_utils import (TB_COLOR, TB_COLOR_SMOOTH,
read_tensorboard_file... | string: main rank: str other rank: None return: all rank: str |
179,808 | import os
import re
from typing import List, Optional, Tuple
import json
import matplotlib.pyplot as plt
import torch
import torch.distributed as dist
from rouge import Rouge
from swift import get_logger
from swift.utils.tb_utils import (TB_COLOR, TB_COLOR_SMOOTH,
read_tensorboard_file... | null |
179,809 | import os
from types import MethodType
from typing import Any, Dict, NamedTuple, Optional
import torch
from swift import get_logger
from torch import dtype as Dtype
from modelscope import (AutoConfig, AutoModelForCausalLM, AutoTokenizer, Model,
read_config, snapshot_download)
from modelscope.mod... | null |
179,810 | import os
from types import MethodType
from typing import Any, Dict, NamedTuple, Optional
import torch
from swift import get_logger
from torch import dtype as Dtype
from modelscope import (AutoConfig, AutoModelForCausalLM, AutoTokenizer, Model,
read_config, snapshot_download)
from modelscope.mod... | null |
179,811 | import os
from types import MethodType
from typing import Any, Dict, NamedTuple, Optional
import torch
from swift import get_logger
from torch import dtype as Dtype
from modelscope import (AutoConfig, AutoModelForCausalLM, AutoTokenizer, Model,
read_config, snapshot_download)
from modelscope.mod... | null |
179,812 | import os
from types import MethodType
from typing import Any, Dict, NamedTuple, Optional
import torch
from swift import get_logger
from torch import dtype as Dtype
from modelscope import (AutoConfig, AutoModelForCausalLM, AutoTokenizer, Model,
read_config, snapshot_download)
from modelscope.mod... | null |
179,813 | import ast
import os
import re
from typing import List, Optional, Tuple
import json
import numpy as np
import torch
from datasets import Dataset as HfDataset
from datasets import IterableDataset, concatenate_datasets
from swift.utils import get_seed
from modelscope import MsDataset
def get_ms_tool_dataset(dataset_name... | null |
179,814 | import ast
import os
import re
from typing import List, Optional, Tuple
import json
import numpy as np
import torch
from datasets import Dataset as HfDataset
from datasets import IterableDataset, concatenate_datasets
from swift.utils import get_seed
from modelscope import MsDataset
def get_ms_tool_dataset_test(dataset... | null |
179,815 | import ast
import os
import re
from typing import List, Optional, Tuple
import json
import numpy as np
import torch
from datasets import Dataset as HfDataset
from datasets import IterableDataset, concatenate_datasets
from swift.utils import get_seed
from modelscope import MsDataset
def process_dataset(dataset: HfDatas... | null |
179,816 | import ast
import os
import re
from typing import List, Optional, Tuple
import json
import numpy as np
import torch
from datasets import Dataset as HfDataset
from datasets import IterableDataset, concatenate_datasets
from swift.utils import get_seed
from modelscope import MsDataset
IGNORE_INDEX = -100
def tokenize_fun... | null |
179,817 | import argparse
import json
from tqdm import tqdm
import datasets
import transformers
def preprocess(tokenizer, config, example, max_seq_length, version):
if version == 'v1':
prompt = example["context"]
target = example["target"]
prompt_ids = tokenizer.encode(prompt, max_length=max_seq_lengt... | null |
179,818 | import argparse
import json
from tqdm import tqdm
def format_example(example: dict) -> dict:
context = f"Instruction: {example['instruction']}\n"
if example.get("input"):
context += f"Input: {example['input']}\n"
context += "Answer: "
target = example["output"]
return {"context": context, "... | null |
179,819 | import os
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Optional
from github import Github
from github.Issue import Issue
from github.Repository import Repository
from pytz import timezone
import typer
from typer import Typer
class IssueData:
def __init__(self, iss... | null |
179,820 | import os
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Optional
from github import Github
from github.Issue import Issue
from github.Repository import Repository
from pytz import timezone
import typer
from typer import Typer
DATETIME_FORMAT: str = "%m/%d/%Y %I:%M %p"
C... | null |
179,821 | import os
import re
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, TypeVar
The provided code snippet includes necessary dependencies for implementing the `iter_folder` function. Write a Python function `def iter_folder(folder, is_dir=False, ext=None)` to solve the following problem:
... | Args: folder (str): is_dir (bool): True to iter directories only ext (str): File extension, such as `.yaml` Yields: str: Absolute path of files |
179,822 | import os
import re
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, TypeVar
class DataProcessInfo:
proc: object # psutil.Process or psutil._pswindows.Process
pid: int
def name(self):
name = self.proc.name()
return name
def cmdline(self):
try:
... | null |
179,823 | import os
import re
from deploy.Windows.logger import logger
def patch_trust_env(file):
"""
People use proxies, but they never realize that proxy software leaves a
global proxy pointing to itself even when the software is not running.
In most situations we set `session.trust_env = False` in requests, bu... | null |
179,824 | import logging
import os
from deploy.Windows.emulator import EmulatorManager
from deploy.Windows.logger import Progress, logger
logger = logging.getLogger("deploy")
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
logger.hr = hr
logger.attr = attr
def show_fix_tip(module):
logger.info(f"""
To fix ... | null |
179,826 | import sys
import typing as t
from deploy.Windows.utils import poor_yaml_read, poor_yaml_write, DEPLOY_TEMPLATE
def get_args() -> t.Dict[str, str]:
args = {}
for arg in sys.argv[1:]:
if '=' not in arg:
continue
k, v = arg.split('=')
k, v = k.strip(), v.strip()
args[k... | null |
179,827 | import itertools
from pponnxcr.predict_system import BoxedResult
from module.base.utils import area_in_area, area_offset
def area_cross_area(area1, area2, thres_x=20, thres_y=20):
"""
Args:
area1: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
area2: (upper_left_x, upper_left_y, b... | Args: buttons: thres_x: Merge results with horizontal box distance <= `thres_x` thres_y: Merge results with vertical box distance <= `thres_y` Returns: |
179,828 | import itertools
from pponnxcr.predict_system import BoxedResult
from module.base.utils import area_in_area, area_offset
def split_and_pair_buttons(buttons, split_func, relative_area):
"""
Pair buttons in group1 with those in group2 in the relative_area.
Args:
buttons (list[OcrResultButton]):
... | Pair buttons in group1 with those in group2 in the relative_area, and treat group2 as the BUTTON attribute of group1. Args: buttons (list[OcrResultButton]): split_func (callable): A function that accepts an OcrResultButton object returns a bool, button that has a True return join group1, False join group2. relative_are... |
179,829 | from pponnxcr import TextSystem as TextSystem_
from module.base.decorator import cached_property, del_cached_property
from module.exception import ScriptError
DIC_LANG_TO_MODEL = {
'cn': 'zhs',
'en': 'en',
'jp': 'ja',
'tw': 'zht',
}
The provided code snippet includes necessary dependencies for implemen... | Args: lang: In-game language name, defined in VALID_LANG Returns: str: Model name, defined in pponnxcr.utility |
179,830 | from pponnxcr import TextSystem as TextSystem_
from module.base.decorator import cached_property, del_cached_property
from module.exception import ScriptError
DIC_LANG_TO_MODEL = {
'cn': 'zhs',
'en': 'en',
'jp': 'ja',
'tw': 'zht',
}
The provided code snippet includes necessary dependencies for implemen... | Args: model: Model name, defined in pponnxcr.utility Returns: str: In-game language name, defined in VALID_LANG |
179,831 | import re
from dataclasses import dataclass
from functools import cached_property
from typing import ClassVar
import module.config.server as server
from module.exception import ScriptError
def parse_name(n):
n = REGEX_PUNCTUATION.sub('', str(n)).lower()
return n.strip() | null |
179,832 | import time
import typing as t
import numpy as np
from rich.table import Table
from rich.text import Text
from module.base.utils import float2str as float2str_
from module.base.utils import random_rectangle_point
from module.daemon.daemon_base import DaemonBase
from module.exception import RequestHumanTakeover
from mod... | null |
179,833 | import os
from typing import Callable, Generic, TypeVar
The provided code snippet includes necessary dependencies for implementing the `iter_folder` function. Write a Python function `def iter_folder(folder, is_dir=False, ext=None)` to solve the following problem:
Args: folder (str): is_dir (bool): True to iter direct... | Args: folder (str): is_dir (bool): True to iter directories only ext (str): File extension, such as `.yaml` Yields: str: Absolute path of files |
179,834 | import codecs
import os
import re
import typing as t
import winreg
from dataclasses import dataclass
from module.device.platform.utils import cached_property, iter_folder
from module.device.platform.emulator_base import EmulatorBase, EmulatorInstanceBase, EmulatorManagerBase
class RegValue:
name: str
value: str... | List all values in a reg key |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.