code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def handle_request(cls, request, dispatcher): """ Handle request data. At this moment request has correct jsonrpc format. :param dict request: data parsed from request_str. :param jsonrpc.dispatcher.Dispatcher dispatcher: .. versionadded: 1.8.0 """ rs = reques...
Handle request data. At this moment request has correct jsonrpc format. :param dict request: data parsed from request_str. :param jsonrpc.dispatcher.Dispatcher dispatcher: .. versionadded: 1.8.0
handle_request
python
AirtestProject/Poco
poco/utils/simplerpc/jsonrpc/manager.py
https://github.com/AirtestProject/Poco/blob/master/poco/utils/simplerpc/jsonrpc/manager.py
Apache-2.0
def _get_responses(cls, requests, dispatcher): """ Response to each single JSON-RPC Request. :return iterator(JSONRPC20Response): .. versionadded: 1.9.0 TypeError inside the function is distinguished from Invalid Params. """ for request in requests: def r...
Response to each single JSON-RPC Request. :return iterator(JSONRPC20Response): .. versionadded: 1.9.0 TypeError inside the function is distinguished from Invalid Params.
_get_responses
python
AirtestProject/Poco
poco/utils/simplerpc/jsonrpc/manager.py
https://github.com/AirtestProject/Poco/blob/master/poco/utils/simplerpc/jsonrpc/manager.py
Apache-2.0
def default(self, o): """ Encode JSON. :return str: A JSON encoded string """ if isinstance(o, decimal.Decimal): return float(o) if isinstance(o, (datetime.datetime, datetime.date)): return o.isoformat() return json.JSONEncoder.default(self, o)
Encode JSON. :return str: A JSON encoded string
default
python
AirtestProject/Poco
poco/utils/simplerpc/jsonrpc/utils.py
https://github.com/AirtestProject/Poco/blob/master/poco/utils/simplerpc/jsonrpc/utils.py
Apache-2.0
def is_invalid_params(func, *args, **kwargs): """ Check, whether function 'func' accepts parameters 'args', 'kwargs'. NOTE: Method is called after funct(*args, **kwargs) generated TypeError, it is aimed to destinguish TypeError because of invalid parameters from TypeError from inside the function. ...
Check, whether function 'func' accepts parameters 'args', 'kwargs'. NOTE: Method is called after funct(*args, **kwargs) generated TypeError, it is aimed to destinguish TypeError because of invalid parameters from TypeError from inside the function. .. versionadded: 1.9.0
is_invalid_params
python
AirtestProject/Poco
poco/utils/simplerpc/jsonrpc/utils.py
https://github.com/AirtestProject/Poco/blob/master/poco/utils/simplerpc/jsonrpc/utils.py
Apache-2.0
def jsonrpc_map(self, request): """ Map of json-rpc available calls. :return str: """ result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([ "{0}: {1}".format(fname, f.__doc__) for fname, f in self.dispatcher.items() ])) return HttpR...
Map of json-rpc available calls. :return str:
jsonrpc_map
python
AirtestProject/Poco
poco/utils/simplerpc/jsonrpc/backend/django.py
https://github.com/AirtestProject/Poco/blob/master/poco/utils/simplerpc/jsonrpc/backend/django.py
Apache-2.0
def __init__(self, dispatcher=None, check_content_type=True): """ :param dispatcher: methods dispatcher :param check_content_type: if True - content-type must be "application/json" :return: """ self.dispatcher = dispatcher if dispatcher is not None \ ...
:param dispatcher: methods dispatcher :param check_content_type: if True - content-type must be "application/json" :return:
__init__
python
AirtestProject/Poco
poco/utils/simplerpc/jsonrpc/backend/flask.py
https://github.com/AirtestProject/Poco/blob/master/poco/utils/simplerpc/jsonrpc/backend/flask.py
Apache-2.0
def test_method_validation_str_rpc_prefix(self): """ Test method SHOULD NOT starts with rpc. """ self.request_params.update({"method": "rpc."}) with self.assertRaises(ValueError): JSONRPC20Request(**self.request_params) self.request_params.update({"method": "rpc.test"}) ...
Test method SHOULD NOT starts with rpc.
test_method_validation_str_rpc_prefix
python
AirtestProject/Poco
poco/utils/simplerpc/jsonrpc/tests/test_jsonrpc2.py
https://github.com/AirtestProject/Poco/blob/master/poco/utils/simplerpc/jsonrpc/tests/test_jsonrpc2.py
Apache-2.0
def update_attributes(self, options=None): "Updates fast attributes and everything else outside of self.options" if options is None: options = self.options self.benchmark_interval = options.get('benchmark_interval', self.benchmark_interval) self.logger_table_font = options.g...
Updates fast attributes and everything else outside of self.options
update_attributes
python
busimus/cutelog
cutelog/config.py
https://github.com/busimus/cutelog/blob/master/cutelog/config.py
MIT
def wait_and_read(n_bytes): """ Convenience function that simplifies reading and checking for stop events, etc. Returns a byte string of length n_bytes or None if socket needs to be closed. """ data = b"" while len(data) < n_bytes: ...
Convenience function that simplifies reading and checking for stop events, etc. Returns a byte string of length n_bytes or None if socket needs to be closed.
wait_and_read
python
busimus/cutelog
cutelog/listener.py
https://github.com/busimus/cutelog/blob/master/cutelog/listener.py
MIT
def handle_internal_command(self, data): """ Used for managing listener options from non-Python clients. Command data must start with a special prefix (see self.internal_prefix), followed by a command in a key=value format. Supported commands: format - changes the se...
Used for managing listener options from non-Python clients. Command data must start with a special prefix (see self.internal_prefix), followed by a command in a key=value format. Supported commands: format - changes the serialization format to one specified in ...
handle_internal_command
python
busimus/cutelog
cutelog/listener.py
https://github.com/busimus/cutelog/blob/master/cutelog/listener.py
MIT
def eventFilter(self, object, event): """ The problem with headerView.sectionResized is that it gets called way too much, often pointlessly or in annoying ways. So I decided that instead I'll listen for mouse releases on the headerView and save the whole header whenever that even...
The problem with headerView.sectionResized is that it gets called way too much, often pointlessly or in annoying ways. So I decided that instead I'll listen for mouse releases on the headerView and save the whole header whenever that event comes through the filter. Is this the ...
eventFilter
python
busimus/cutelog
cutelog/logger_table_header.py
https://github.com/busimus/cutelog/blob/master/cutelog/logger_table_header.py
MIT
async def get_response( messages: str | list[str] | list[dict[str, Any]], philosopher_id: str, philosopher_name: str, philosopher_perspective: str, philosopher_style: str, philosopher_context: str, new_thread: bool = False, ) -> tuple[str, PhilosopherState]: """Run a conversation through...
Run a conversation through the workflow graph. Args: message: Initial message to start the conversation. philosopher_id: Unique identifier for the philosopher. philosopher_name: Name of the philosopher. philosopher_perspective: Philosopher's perspective on the topic. philoso...
get_response
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/conversation_service/generate_response.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/conversation_service/generate_response.py
MIT
async def get_streaming_response( messages: str | list[str] | list[dict[str, Any]], philosopher_id: str, philosopher_name: str, philosopher_perspective: str, philosopher_style: str, philosopher_context: str, new_thread: bool = False, ) -> AsyncGenerator[str, None]: """Run a conversation ...
Run a conversation through the workflow graph with streaming response. Args: messages: Initial message to start the conversation. philosopher_id: Unique identifier for the philosopher. philosopher_name: Name of the philosopher. philosopher_perspective: Philosopher's perspective on t...
get_streaming_response
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/conversation_service/generate_response.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/conversation_service/generate_response.py
MIT
def __format_messages( messages: Union[str, list[dict[str, Any]]], ) -> list[Union[HumanMessage, AIMessage]]: """Convert various message formats to a list of LangChain message objects. Args: messages: Can be one of: - A single string message - A list of string messages ...
Convert various message formats to a list of LangChain message objects. Args: messages: Can be one of: - A single string message - A list of string messages - A list of dictionaries with 'role' and 'content' keys Returns: List[Union[HumanMessage, AIMessage]]...
__format_messages
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/conversation_service/generate_response.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/conversation_service/generate_response.py
MIT
async def reset_conversation_state() -> dict: """Deletes all conversation state data from MongoDB. This function removes all stored conversation checkpoints and writes, effectively resetting all philosopher conversations. Returns: dict: Status message indicating success or failure with details...
Deletes all conversation state data from MongoDB. This function removes all stored conversation checkpoints and writes, effectively resetting all philosopher conversations. Returns: dict: Status message indicating success or failure with details about which collections were deleted ...
reset_conversation_state
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/conversation_service/reset_conversation.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/conversation_service/reset_conversation.py
MIT
def deduplicate_documents( documents: List[Document], threshold: float = 0.7 ) -> List[Document]: """Remove duplicate documents from a list based on content similarity. Uses MinHash algorithm to identify similar documents and removes duplicates based on the specified similarity threshold. Args: ...
Remove duplicate documents from a list based on content similarity. Uses MinHash algorithm to identify similar documents and removes duplicates based on the specified similarity threshold. Args: documents: List of documents to deduplicate. threshold: Similarity threshold to consider docume...
deduplicate_documents
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/data/deduplicate_documents.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/data/deduplicate_documents.py
MIT
def find_duplicates( documents: List[Document], threshold: float = 0.7, num_perm: int = int(settings.RAG_CHUNK_SIZE * 0.5), ) -> List[Tuple[int, int, float]]: """Find duplicate documents using MinHash algorithm. Creates MinHash signatures for each document and uses Locality Sensitive Hashing (LSH) ...
Find duplicate documents using MinHash algorithm. Creates MinHash signatures for each document and uses Locality Sensitive Hashing (LSH) to efficiently find similar document pairs. Args: documents: List of documents to check for duplicates. threshold: Similarity threshold (0.0-1.0) to cons...
find_duplicates
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/data/deduplicate_documents.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/data/deduplicate_documents.py
MIT
def get_extraction_generator( philosophers: list[PhilosopherExtract], ) -> Generator[tuple[Philosopher, list[Document]], None, None]: """Extract documents for a list of philosophers, yielding one at a time. Args: philosophers: A list of PhilosopherExtract objects containing philosopher information....
Extract documents for a list of philosophers, yielding one at a time. Args: philosophers: A list of PhilosopherExtract objects containing philosopher information. Yields: tuple[Philosopher, list[Document]]: A tuple containing the philosopher object and a list of documents extracted...
get_extraction_generator
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/data/extract.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/data/extract.py
MIT
def extract(philosopher: Philosopher, extract_urls: list[str]) -> list[Document]: """Extract documents for a single philosopher from all sources and deduplicate them. Args: philosopher: Philosopher object containing philosopher information. extract_urls: List of URLs to extract content from. ...
Extract documents for a single philosopher from all sources and deduplicate them. Args: philosopher: Philosopher object containing philosopher information. extract_urls: List of URLs to extract content from. Returns: list[Document]: List of deduplicated documents extracted for the phil...
extract
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/data/extract.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/data/extract.py
MIT
def extract_wikipedia(philosopher: Philosopher) -> list[Document]: """Extract documents for a single philosopher from Wikipedia. Args: philosopher: Philosopher object containing philosopher information. Returns: list[Document]: List of documents extracted from Wikipedia for the philosopher...
Extract documents for a single philosopher from Wikipedia. Args: philosopher: Philosopher object containing philosopher information. Returns: list[Document]: List of documents extracted from Wikipedia for the philosopher.
extract_wikipedia
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/data/extract.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/data/extract.py
MIT
def extract_stanford_encyclopedia_of_philosophy( philosopher: Philosopher, urls: list[str] ) -> list[Document]: """Extract documents for a single philosopher from Stanford Encyclopedia of Philosophy. Args: philosopher: Philosopher object containing philosopher information. urls: List of URL...
Extract documents for a single philosopher from Stanford Encyclopedia of Philosophy. Args: philosopher: Philosopher object containing philosopher information. urls: List of URLs to extract content from. Returns: list[Document]: List of documents extracted from Stanford Encyclopedia for...
extract_stanford_encyclopedia_of_philosophy
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/data/extract.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/data/extract.py
MIT
async def evaluation_task(x: dict) -> dict: """Calls agentic app logic to evaluate philosopher responses. Args: x: Dictionary containing evaluation data with the following keys: messages: List of conversation messages where all but the last are inputs and the last is the exp...
Calls agentic app logic to evaluate philosopher responses. Args: x: Dictionary containing evaluation data with the following keys: messages: List of conversation messages where all but the last are inputs and the last is the expected output philosopher_id: ID of the ...
evaluation_task
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/evaluation/evaluate.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/evaluation/evaluate.py
MIT
def evaluate_agent( dataset: opik.Dataset | None, workers: int = 2, nb_samples: int | None = None, ) -> None: """Evaluates an agent using specified metrics and dataset. Runs evaluation using Opik framework with configured metrics for hallucination, answer relevance, moderation, and context reca...
Evaluates an agent using specified metrics and dataset. Runs evaluation using Opik framework with configured metrics for hallucination, answer relevance, moderation, and context recall. Args: dataset: Dataset containing evaluation examples. Must contain messages and philosopher_id. ...
evaluate_agent
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/evaluation/evaluate.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/evaluation/evaluate.py
MIT
def get_embedding_model( model_id: str, device: str = "cpu", ) -> EmbeddingsModel: """Gets an instance of a HuggingFace embedding model. Args: model_id (str): The ID/name of the HuggingFace embedding model to use device (str): The compute device to run the model on (e.g. "cpu", "cuda")....
Gets an instance of a HuggingFace embedding model. Args: model_id (str): The ID/name of the HuggingFace embedding model to use device (str): The compute device to run the model on (e.g. "cpu", "cuda"). Defaults to "cpu" Returns: EmbeddingsModel: A configured HuggingFace emb...
get_embedding_model
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/rag/embeddings.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/rag/embeddings.py
MIT
def get_huggingface_embedding_model( model_id: str, device: str ) -> HuggingFaceEmbeddings: """Gets a HuggingFace embedding model instance. Args: model_id (str): The ID/name of the HuggingFace embedding model to use device (str): The compute device to run the model on (e.g. "cpu", "cuda") ...
Gets a HuggingFace embedding model instance. Args: model_id (str): The ID/name of the HuggingFace embedding model to use device (str): The compute device to run the model on (e.g. "cpu", "cuda") Returns: HuggingFaceEmbeddings: A configured HuggingFace embeddings model instance ...
get_huggingface_embedding_model
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/rag/embeddings.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/rag/embeddings.py
MIT
def get_retriever( embedding_model_id: str, k: int = 3, device: str = "cpu", ) -> Retriever: """Creates and returns a hybrid search retriever with the specified embedding model. Args: embedding_model_id (str): The identifier for the embedding model to use. k (int, optional): Number ...
Creates and returns a hybrid search retriever with the specified embedding model. Args: embedding_model_id (str): The identifier for the embedding model to use. k (int, optional): Number of documents to retrieve. Defaults to 3. device (str, optional): Device to run the embedding model on. D...
get_retriever
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/rag/retrievers.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/rag/retrievers.py
MIT
def get_hybrid_search_retriever( embedding_model: HuggingFaceEmbeddings, k: int ) -> MongoDBAtlasHybridSearchRetriever: """Creates a MongoDB Atlas hybrid search retriever with the given embedding model. Args: embedding_model (HuggingFaceEmbeddings): The embedding model to use for vector search. ...
Creates a MongoDB Atlas hybrid search retriever with the given embedding model. Args: embedding_model (HuggingFaceEmbeddings): The embedding model to use for vector search. k (int): Number of documents to retrieve. Returns: MongoDBAtlasHybridSearchRetriever: A configured hybrid search ...
get_hybrid_search_retriever
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/rag/retrievers.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/rag/retrievers.py
MIT
def get_splitter(chunk_size: int) -> Splitter: """Returns a token-based text splitter with overlap. Args: chunk_size: Number of tokens for each text chunk. Returns: Splitter: A configured text splitter instance that splits text into overlapping chunks based on token count. ...
Returns a token-based text splitter with overlap. Args: chunk_size: Number of tokens for each text chunk. Returns: Splitter: A configured text splitter instance that splits text into overlapping chunks based on token count.
get_splitter
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/application/rag/splitters.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/application/rag/splitters.py
MIT
def save_to_json(self, file_path: Path) -> None: """Saves the evaluation dataset to a JSON file. Args: file_path: The path where the JSON file will be saved. Returns: None Raises: IOError: If there's an error writing to the file. """ ...
Saves the evaluation dataset to a JSON file. Args: file_path: The path where the JSON file will be saved. Returns: None Raises: IOError: If there's an error writing to the file.
save_to_json
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/domain/evaluation.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/domain/evaluation.py
MIT
def get_philosopher(id: str) -> Philosopher: """Creates a philosopher instance based on the provided ID. Args: id (str): Identifier of the philosopher to create Returns: Philosopher: Instance of the philosopher Raises: ValueError: If philosopher ID ...
Creates a philosopher instance based on the provided ID. Args: id (str): Identifier of the philosopher to create Returns: Philosopher: Instance of the philosopher Raises: ValueError: If philosopher ID is not found in configurations
get_philosopher
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/domain/philosopher_factory.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/domain/philosopher_factory.py
MIT
async def lifespan(app: FastAPI): """Handles startup and shutdown events for the API.""" # Startup code (if any) goes here yield # Shutdown code goes here opik_tracer = OpikTracer() opik_tracer.flush()
Handles startup and shutdown events for the API.
lifespan
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/infrastructure/api.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/infrastructure/api.py
MIT
async def reset_conversation(): """Resets the conversation state. It deletes the two collections needed for keeping LangGraph state in MongoDB. Raises: HTTPException: If there is an error resetting the conversation state. Returns: dict: A dictionary containing the result of the reset operat...
Resets the conversation state. It deletes the two collections needed for keeping LangGraph state in MongoDB. Raises: HTTPException: If there is an error resetting the conversation state. Returns: dict: A dictionary containing the result of the reset operation.
reset_conversation
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/infrastructure/api.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/infrastructure/api.py
MIT
def __init__( self, model: Type[T], collection_name: str, database_name: str = settings.MONGO_DB_NAME, mongodb_uri: str = settings.MONGO_URI, ) -> None: """Initialize a connection to the MongoDB collection. Args: model (Type[T]): The Pydantic mode...
Initialize a connection to the MongoDB collection. Args: model (Type[T]): The Pydantic model class to use for document serialization. collection_name (str): Name of the MongoDB collection to use. database_name (str, optional): Name of the MongoDB database to use. ...
__init__
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/infrastructure/mongo/client.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/infrastructure/mongo/client.py
MIT
def clear_collection(self) -> None: """Remove all documents from the collection. This method deletes all documents in the collection to avoid duplicates during reingestion. Raises: errors.PyMongoError: If the deletion operation fails. """ try: r...
Remove all documents from the collection. This method deletes all documents in the collection to avoid duplicates during reingestion. Raises: errors.PyMongoError: If the deletion operation fails.
clear_collection
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/infrastructure/mongo/client.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/infrastructure/mongo/client.py
MIT
def ingest_documents(self, documents: list[T]) -> None: """Insert multiple documents into the MongoDB collection. Args: documents: List of Pydantic model instances to insert. Raises: ValueError: If documents is empty or contains non-Pydantic model items. err...
Insert multiple documents into the MongoDB collection. Args: documents: List of Pydantic model instances to insert. Raises: ValueError: If documents is empty or contains non-Pydantic model items. errors.PyMongoError: If the insertion operation fails.
ingest_documents
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/infrastructure/mongo/client.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/infrastructure/mongo/client.py
MIT
def __parse_documents(self, documents: list[dict]) -> list[T]: """Convert MongoDB documents to Pydantic model instances. Converts MongoDB ObjectId fields to strings and transforms the document structure to match the Pydantic model schema. Args: documents (list[dict]): List ...
Convert MongoDB documents to Pydantic model instances. Converts MongoDB ObjectId fields to strings and transforms the document structure to match the Pydantic model schema. Args: documents (list[dict]): List of MongoDB documents to parse. Returns: list[T]: List...
__parse_documents
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/infrastructure/mongo/client.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/infrastructure/mongo/client.py
MIT
def get_collection_count(self) -> int: """Count the total number of documents in the collection. Returns: Total number of documents in the collection. Raises: errors.PyMongoError: If the count operation fails. """ try: return self.collection...
Count the total number of documents in the collection. Returns: Total number of documents in the collection. Raises: errors.PyMongoError: If the count operation fails.
get_collection_count
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/infrastructure/mongo/client.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/infrastructure/mongo/client.py
MIT
def close(self) -> None: """Close the MongoDB connection. This method should be called when the service is no longer needed to properly release resources, unless using the context manager. """ self.client.close() logger.debug("Closed MongoDB connection.")
Close the MongoDB connection. This method should be called when the service is no longer needed to properly release resources, unless using the context manager.
close
python
neural-maze/philoagents-course
philoagents-api/src/philoagents/infrastructure/mongo/client.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/src/philoagents/infrastructure/mongo/client.py
MIT
def async_command(f): """Decorator to run an async click command.""" @wraps(f) def wrapper(*args, **kwargs): return asyncio.run(f(*args, **kwargs)) return wrapper
Decorator to run an async click command.
async_command
python
neural-maze/philoagents-course
philoagents-api/tools/call_agent.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/tools/call_agent.py
MIT
async def main(philosopher_id: str, query: str) -> None: """CLI command to query a philosopher. Args: philosopher_id: ID of the philosopher to call. query: Query to call the agent with. """ philosopher_factory = PhilosopherFactory() philosopher = philosopher_factory.get_philosopher...
CLI command to query a philosopher. Args: philosopher_id: ID of the philosopher to call. query: Query to call the agent with.
main
python
neural-maze/philoagents-course
philoagents-api/tools/call_agent.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/tools/call_agent.py
MIT
def main(metadata_file: Path) -> None: """CLI command to create long-term memory for philosophers. Args: metadata_file: Path to the philosophers extraction metadata JSON file. """ philosophers = PhilosopherExtract.from_json(metadata_file) long_term_memory_creator = LongTermMemoryCreator.bu...
CLI command to create long-term memory for philosophers. Args: metadata_file: Path to the philosophers extraction metadata JSON file.
main
python
neural-maze/philoagents-course
philoagents-api/tools/create_long_term_memory.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/tools/create_long_term_memory.py
MIT
def main(collection_name: str, mongo_uri: str, db_name: str) -> None: """Command line interface to delete a MongoDB collection. Args: collection_name: Name of the collection to delete. mongo_uri: The MongoDB connection URI string. db_name: The name of the database containing the collect...
Command line interface to delete a MongoDB collection. Args: collection_name: Name of the collection to delete. mongo_uri: The MongoDB connection URI string. db_name: The name of the database containing the collection.
main
python
neural-maze/philoagents-course
philoagents-api/tools/delete_long_term_memory.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/tools/delete_long_term_memory.py
MIT
def main(name: str, data_path: Path, workers: int, nb_samples: int) -> None: """ Evaluate an agent on a dataset. Args: name: Name of the dataset data_path: Path to the dataset file workers: Number of workers to use for evaluation nb_samples: Number of samples to evaluate ...
Evaluate an agent on a dataset. Args: name: Name of the dataset data_path: Path to the dataset file workers: Number of workers to use for evaluation nb_samples: Number of samples to evaluate
main
python
neural-maze/philoagents-course
philoagents-api/tools/evaluate_agent.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/tools/evaluate_agent.py
MIT
def main(metadata_file: Path, temperature: float, max_samples: int) -> None: """ Generate an evaluation dataset from philosopher extracts. Args: metadata_file: Path to the metadata file containing philosopher extracts temperature: Temperature parameter for generation max_samples: Ma...
Generate an evaluation dataset from philosopher extracts. Args: metadata_file: Path to the metadata file containing philosopher extracts temperature: Temperature parameter for generation max_samples: Maximum number of samples to generate
main
python
neural-maze/philoagents-course
philoagents-api/tools/generate_evaluation_dataset.py
https://github.com/neural-maze/philoagents-course/blob/master/philoagents-api/tools/generate_evaluation_dataset.py
MIT
def from_dict( cls: Type[BaseT], dict_: Mapping, strict: bool = False, cast: bool = False, ) -> BaseT: """Return an instance constructed from a dictionary. Instantiate an object whose attributes and the corresponding values are given as a dictionary. ...
Return an instance constructed from a dictionary. Instantiate an object whose attributes and the corresponding values are given as a dictionary. Parameters ---------- dict_ : dict or mapping A dictionary that stores the attributes and their values as key...
from_dict
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def to_ordered_dict( self, skip_missing: bool = True, deepcopy: bool = True ) -> OrderedDict: """Return the object as an OrderedDict. Return an ordered dictionary that stores the attributes and their values as key-value pairs. Parameters ---------- skip_miss...
Return the object as an OrderedDict. Return an ordered dictionary that stores the attributes and their values as key-value pairs. Parameters ---------- skip_missing : bool, default: True Whether to skip attributes with value None or those that are empty ...
to_ordered_dict
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def pretty_str(self, skip_missing: bool = True) -> str: """Return the attributes as a string in a YAML-like format. Parameters ---------- skip_missing : bool, default: True Whether to skip attributes with value None or those that are empty lists. Returns...
Return the attributes as a string in a YAML-like format. Parameters ---------- skip_missing : bool, default: True Whether to skip attributes with value None or those that are empty lists. Returns ------- str Stored data as a string in...
pretty_str
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def validate_type( self: BaseT, attr: str = None, recursive: bool = True ) -> BaseT: """Raise an error if an attribute is of an invalid type. This will apply recursively to an attribute's attributes. Parameters ---------- attr : str, optional Attribute t...
Raise an error if an attribute is of an invalid type. This will apply recursively to an attribute's attributes. Parameters ---------- attr : str, optional Attribute to validate. Defaults to validate all attributes. recursive : bool, default: True Whether...
validate_type
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def validate( self: BaseT, attr: str = None, recursive: bool = True ) -> BaseT: """Raise an error if an attribute has an invalid type or value. This will apply recursively to an attribute's attributes. Parameters ---------- attr : str, optional Attribute...
Raise an error if an attribute has an invalid type or value. This will apply recursively to an attribute's attributes. Parameters ---------- attr : str, optional Attribute to validate. Defaults to validate all attributes. recursive : bool, default: True ...
validate
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def is_valid_type(self, attr: str = None, recursive: bool = True) -> bool: """Return True if an attribute is of a valid type. This will apply recursively to an attribute's attributes. Parameters ---------- attr : str, optional Attribute to validate. Defaults to vali...
Return True if an attribute is of a valid type. This will apply recursively to an attribute's attributes. Parameters ---------- attr : str, optional Attribute to validate. Defaults to validate all attributes. recursive : bool, default: True Whether to ap...
is_valid_type
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def is_valid(self, attr: str = None, recursive: bool = True) -> bool: """Return True if an attribute has a valid type and value. This will recursively apply to an attribute's attributes. Parameters ---------- attr : str, optional Attribute to validate. Defaults to v...
Return True if an attribute has a valid type and value. This will recursively apply to an attribute's attributes. Parameters ---------- attr : str, optional Attribute to validate. Defaults to validate all attributes. recursive : bool, default: True Wheth...
is_valid
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def adjust_time( self: BaseT, func: Callable[[int], int], attr: str = None, recursive: bool = True, ) -> BaseT: """Adjust the timing of time-stamped objects. Parameters ---------- func : callable The function used to compute the new timing...
Adjust the timing of time-stamped objects. Parameters ---------- func : callable The function used to compute the new timing from the old timing, i.e., `new_time = func(old_time)`. attr : str, optional Attribute to adjust. Defaults to adjust all attri...
adjust_time
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def fix_type( self: BaseT, attr: str = None, recursive: bool = True ) -> BaseT: """Fix the types of attributes. Parameters ---------- attr : str, optional Attribute to adjust. Defaults to adjust all attributes. recursive : bool, default: True ...
Fix the types of attributes. Parameters ---------- attr : str, optional Attribute to adjust. Defaults to adjust all attributes. recursive : bool, default: True Whether to apply recursively. Returns ------- Object itself.
fix_type
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def extend( self: ComplexBaseT, other: Union[ComplexBaseT, Iterable], deepcopy: bool = False, ) -> ComplexBaseT: """Extend the list(s) with another object or iterable. Parameters ---------- other : :class:`muspy.ComplexBase` or iterable If an obje...
Extend the list(s) with another object or iterable. Parameters ---------- other : :class:`muspy.ComplexBase` or iterable If an object of the same type is given, extend the list attributes with the corresponding list attributes of the other object. If an itera...
extend
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def remove_invalid( self: ComplexBaseT, attr: str = None, recursive: bool = True ) -> ComplexBaseT: """Remove invalid items from a list attribute. Parameters ---------- attr : str, optional Attribute to validate. Defaults to validate all attributes. recur...
Remove invalid items from a list attribute. Parameters ---------- attr : str, optional Attribute to validate. Defaults to validate all attributes. recursive : bool, default: True Whether to apply recursively. Returns ------- Object itself...
remove_invalid
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def remove_duplicate( self: ComplexBaseT, attr: str = None, recursive: bool = True ) -> ComplexBaseT: """Remove duplicate items from a list attribute. Parameters ---------- attr : str, optional Attribute to check. Defaults to check all attributes. recursi...
Remove duplicate items from a list attribute. Parameters ---------- attr : str, optional Attribute to check. Defaults to check all attributes. recursive : bool, default: True Whether to apply recursively. Returns ------- Object itself. ...
remove_duplicate
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def sort( self: ComplexBaseT, attr: str = None, recursive: bool = True ) -> ComplexBaseT: """Sort a list attribute. Parameters ---------- attr : str, optional Attribute to sort. Defaults to sort all attributes. recursive : bool, default: True ...
Sort a list attribute. Parameters ---------- attr : str, optional Attribute to sort. Defaults to sort all attributes. recursive : bool, default: True Whether to apply recursively. Returns ------- Object itself.
sort
python
salu133445/muspy
muspy/base.py
https://github.com/salu133445/muspy/blob/master/muspy/base.py
MIT
def get_end_time(list_: List, is_sorted: bool = False, attr: str = "time"): """Return the end time of a list of objects. Parameters ---------- list_ : list List of objects. is_sorted : bool, default: False Whether the list is sorted. attr : str, default: 'time' Attribute...
Return the end time of a list of objects. Parameters ---------- list_ : list List of objects. is_sorted : bool, default: False Whether the list is sorted. attr : str, default: 'time' Attribute to look for.
get_end_time
python
salu133445/muspy
muspy/classes.py
https://github.com/salu133445/muspy/blob/master/muspy/classes.py
MIT
def adjust_time( self: NoteT, func: Callable[[int], int], attr: str = None, recursive: bool = True, ) -> NoteT: """Adjust the timing of the note. Parameters ---------- func : callable The function used to compute the new timing from the ol...
Adjust the timing of the note. Parameters ---------- func : callable The function used to compute the new timing from the old timing, i.e., `new_time = func(old_time)`. attr : str, optional Attribute to adjust. Defaults to adjust all attributes. ...
adjust_time
python
salu133445/muspy
muspy/classes.py
https://github.com/salu133445/muspy/blob/master/muspy/classes.py
MIT
def clip(self: NoteT, lower: int = 0, upper: int = 127) -> NoteT: """Clip the velocity of the note. Parameters ---------- lower : int, default: 0 Lower bound. upper : int, default: 127 Upper bound. Returns ------- Object itself. ...
Clip the velocity of the note. Parameters ---------- lower : int, default: 0 Lower bound. upper : int, default: 127 Upper bound. Returns ------- Object itself.
clip
python
salu133445/muspy
muspy/classes.py
https://github.com/salu133445/muspy/blob/master/muspy/classes.py
MIT
def adjust_time( self: ChordT, func: Callable[[int], int], attr: str = None, recursive: bool = True, ) -> ChordT: """Adjust the timing of the chord. Parameters ---------- func : callable The function used to compute the new timing from the...
Adjust the timing of the chord. Parameters ---------- func : callable The function used to compute the new timing from the old timing, i.e., `new_time = func(old_time)`. attr : str, optional Attribute to adjust. Defaults to adjust all attributes. ...
adjust_time
python
salu133445/muspy
muspy/classes.py
https://github.com/salu133445/muspy/blob/master/muspy/classes.py
MIT
def clip(self: ChordT, lower: int = 0, upper: int = 127) -> ChordT: """Clip the velocity of the chord. Parameters ---------- lower : int, default: 0 Lower bound. upper : int, default: 127 Upper bound. Returns ------- Object itself...
Clip the velocity of the chord. Parameters ---------- lower : int, default: 0 Lower bound. upper : int, default: 127 Upper bound. Returns ------- Object itself.
clip
python
salu133445/muspy
muspy/classes.py
https://github.com/salu133445/muspy/blob/master/muspy/classes.py
MIT
def get_end_time(self, is_sorted: bool = False) -> int: """Return the time of the last event. This includes notes, chords, lyrics and annotations. Parameters ---------- is_sorted : bool, default: False Whether all the list attributes are sorted. """ ...
Return the time of the last event. This includes notes, chords, lyrics and annotations. Parameters ---------- is_sorted : bool, default: False Whether all the list attributes are sorted.
get_end_time
python
salu133445/muspy
muspy/classes.py
https://github.com/salu133445/muspy/blob/master/muspy/classes.py
MIT
def clip(self: TrackT, lower: int = 0, upper: int = 127) -> TrackT: """Clip the velocity of each note. Parameters ---------- lower : int, default: 0 Lower bound. upper : int, default: 127 Upper bound. Returns ------- Object itself...
Clip the velocity of each note. Parameters ---------- lower : int, default: 0 Lower bound. upper : int, default: 127 Upper bound. Returns ------- Object itself.
clip
python
salu133445/muspy
muspy/classes.py
https://github.com/salu133445/muspy/blob/master/muspy/classes.py
MIT
def trim(self: TrackT, end: int) -> TrackT: """Trim the track. Parameters ---------- end : int End time, excluding (i.e, the max time will be `end` - 1). Returns ------- Object itself. """ self.notes = _trim_list(self.notes, end) ...
Trim the track. Parameters ---------- end : int End time, excluding (i.e, the max time will be `end` - 1). Returns ------- Object itself.
trim
python
salu133445/muspy
muspy/classes.py
https://github.com/salu133445/muspy/blob/master/muspy/classes.py
MIT
def adjust_resolution( music: MusicT, target: int = None, factor: float = None, rounding: Union[str, Callable] = "round", ) -> MusicT: """Adjust resolution and timing of all time-stamped objects. Parameters ---------- music : :class:`muspy.Music` Object to adjust the resolution....
Adjust resolution and timing of all time-stamped objects. Parameters ---------- music : :class:`muspy.Music` Object to adjust the resolution. target : int, optional Target resolution. factor : int or float, optional Factor used to adjust the resolution based on the formula: ...
adjust_resolution
python
salu133445/muspy
muspy/core.py
https://github.com/salu133445/muspy/blob/master/muspy/core.py
MIT
def extend( obj1: ComplexBaseT, obj2, deepcopy: bool = False ) -> ComplexBaseT: """Extend the list(s) with another object or iterable. Parameters ---------- obj1 : :class:`muspy.ComplexBase` Object to extend. obj2 If an object of the same type as `obj1` is given, extend the ...
Extend the list(s) with another object or iterable. Parameters ---------- obj1 : :class:`muspy.ComplexBase` Object to extend. obj2 If an object of the same type as `obj1` is given, extend the list attributes with the corresponding list attributes of `obj2`. If an iterabl...
extend
python
salu133445/muspy
muspy/core.py
https://github.com/salu133445/muspy/blob/master/muspy/core.py
MIT
def clip( obj: MusicTrackNoteT, lower: int = 0, upper: int = 127 ) -> MusicTrackNoteT: """Clip the velocity of each note. Parameters ---------- obj : :class:`muspy.Music`, :class:`muspy.Track` or \ :class:`muspy.Note` Object to clip. lower : int or float, default: 0 ...
Clip the velocity of each note. Parameters ---------- obj : :class:`muspy.Music`, :class:`muspy.Track` or :class:`muspy.Note` Object to clip. lower : int or float, default: 0 Lower bound. upper : int or float, default: 127 Upper bound.
clip
python
salu133445/muspy
muspy/core.py
https://github.com/salu133445/muspy/blob/master/muspy/core.py
MIT
def to_ordered_dict( obj: Base, skip_missing: bool = True, deepcopy: bool = True ) -> OrderedDict: """Return an OrderedDict converted from a Music object. Parameters ---------- obj : :class:`muspy.Base` Object to convert. skip_missing : bool, default: True Whether to skip attrib...
Return an OrderedDict converted from a Music object. Parameters ---------- obj : :class:`muspy.Base` Object to convert. skip_missing : bool, default: True Whether to skip attributes with value None or those that are empty lists. deepcopy : bool, default: True Whether...
to_ordered_dict
python
salu133445/muspy
muspy/core.py
https://github.com/salu133445/muspy/blob/master/muspy/core.py
MIT
def download_bravura_font(overwrite: bool = False): """Download the Bravura font. Parameters ---------- overwrite : bool, default: False Whether to overwrite an existing file. """ if not overwrite and get_bravura_font_path().is_file(): print("Skip downloading as the Bravura fon...
Download the Bravura font. Parameters ---------- overwrite : bool, default: False Whether to overwrite an existing file.
download_bravura_font
python
salu133445/muspy
muspy/external.py
https://github.com/salu133445/muspy/blob/master/muspy/external.py
MIT
def download_musescore_soundfont(overwrite: bool = False): """Download the MuseScore General soundfont. Parameters ---------- overwrite : bool, default: False Whether to overwrite an existing file. """ if not overwrite and get_musescore_soundfont_path().is_file(): print("Skip d...
Download the MuseScore General soundfont. Parameters ---------- overwrite : bool, default: False Whether to overwrite an existing file.
download_musescore_soundfont
python
salu133445/muspy
muspy/external.py
https://github.com/salu133445/muspy/blob/master/muspy/external.py
MIT
def get_end_time(self, is_sorted: bool = False) -> int: """Return the time of the last event across all the tracks. This includes tempos, key signatures, time signatures, barlines, beats, lyrics, annotations, note offsets and chord offsets. Parameters ---------- is_sort...
Return the time of the last event across all the tracks. This includes tempos, key signatures, time signatures, barlines, beats, lyrics, annotations, note offsets and chord offsets. Parameters ---------- is_sorted : bool, default: False Whether all the list attribut...
get_end_time
python
salu133445/muspy
muspy/music.py
https://github.com/salu133445/muspy/blob/master/muspy/music.py
MIT
def get_real_end_time(self, is_sorted: bool = False) -> float: """Return the end time in realtime. This includes tempos, key signatures, time signatures, note offsets, lyrics and annotations. Assume 120 qpm (quarter notes per minute) if no tempo information is available. Parame...
Return the end time in realtime. This includes tempos, key signatures, time signatures, note offsets, lyrics and annotations. Assume 120 qpm (quarter notes per minute) if no tempo information is available. Parameters ---------- is_sorted : bool, default: False ...
get_real_end_time
python
salu133445/muspy
muspy/music.py
https://github.com/salu133445/muspy/blob/master/muspy/music.py
MIT
def infer_barlines(self: MusicT, overwrite: bool = False) -> MusicT: """Infer barlines from the time signatures. This assumes that there is a barline at each time signature change. Parameters ---------- overwrite : bool, default: False Whether to overwrite e...
Infer barlines from the time signatures. This assumes that there is a barline at each time signature change. Parameters ---------- overwrite : bool, default: False Whether to overwrite existing barlines. Returns ------- Object itself. ...
infer_barlines
python
salu133445/muspy
muspy/music.py
https://github.com/salu133445/muspy/blob/master/muspy/music.py
MIT
def infer_barlines_and_beats( self: MusicT, overwrite: bool = False ) -> MusicT: """Infer barlines and beats from the time signature changes. This assumes that there is a downbeat at each time signature change (this is not always true, e.g., for a pickup measure). Return an ...
Infer barlines and beats from the time signature changes. This assumes that there is a downbeat at each time signature change (this is not always true, e.g., for a pickup measure). Return an empty list if no time signature is found. Parameters ---------- overwrite : boo...
infer_barlines_and_beats
python
salu133445/muspy
muspy/music.py
https://github.com/salu133445/muspy/blob/master/muspy/music.py
MIT
def adjust_resolution( self: MusicT, target: int = None, factor: float = None, rounding: Union[str, Callable] = "round", ) -> MusicT: """Adjust resolution and timing of all time-stamped objects. Parameters ---------- target : int, optional ...
Adjust resolution and timing of all time-stamped objects. Parameters ---------- target : int, optional Target resolution. factor : int or float, optional Factor used to adjust the resolution based on the formula: `new_resolution = old_resolution * fac...
adjust_resolution
python
salu133445/muspy
muspy/music.py
https://github.com/salu133445/muspy/blob/master/muspy/music.py
MIT
def clip(self: MusicT, lower: int = 0, upper: int = 127) -> MusicT: """Clip the velocity of each note for each track. Parameters ---------- lower : int, default: 0 Lower bound. upper : int, default: 127 Upper bound. Returns ------- ...
Clip the velocity of each note for each track. Parameters ---------- lower : int, default: 0 Lower bound. upper : int, default: 127 Upper bound. Returns ------- Object itself.
clip
python
salu133445/muspy
muspy/music.py
https://github.com/salu133445/muspy/blob/master/muspy/music.py
MIT
def encode(self, music: Music) -> ndarray: """Encode a Music object into note-based representation. Parameters ---------- music : :class:`muspy.Music` object Music object to encode. Returns ------- ndarray (np.uint8) Encoded array in note...
Encode a Music object into note-based representation. Parameters ---------- music : :class:`muspy.Music` object Music object to encode. Returns ------- ndarray (np.uint8) Encoded array in note-based representation. See Also -----...
encode
python
salu133445/muspy
muspy/processors.py
https://github.com/salu133445/muspy/blob/master/muspy/processors.py
MIT
def decode(self, array: ndarray) -> Music: """Decode note-based representation into a Music object. Parameters ---------- array : ndarray Array in note-based representation to decode. Cast to integer if not of integer type. Returns ------- ...
Decode note-based representation into a Music object. Parameters ---------- array : ndarray Array in note-based representation to decode. Cast to integer if not of integer type. Returns ------- :class:`muspy.Music` object Decoded Musi...
decode
python
salu133445/muspy
muspy/processors.py
https://github.com/salu133445/muspy/blob/master/muspy/processors.py
MIT
def encode(self, music: Music) -> ndarray: """Encode a Music object into event-based representation. Parameters ---------- music : :class:`muspy.Music` object Music object to encode. Returns ------- ndarray (np.uint16) Encoded array in ev...
Encode a Music object into event-based representation. Parameters ---------- music : :class:`muspy.Music` object Music object to encode. Returns ------- ndarray (np.uint16) Encoded array in event-based representation. See Also --...
encode
python
salu133445/muspy
muspy/processors.py
https://github.com/salu133445/muspy/blob/master/muspy/processors.py
MIT
def decode(self, array: ndarray) -> Music: """Decode event-based representation into a Music object. Parameters ---------- array : ndarray Array in event-based representation to decode. Cast to integer if not of integer type. Returns ------- ...
Decode event-based representation into a Music object. Parameters ---------- array : ndarray Array in event-based representation to decode. Cast to integer if not of integer type. Returns ------- :class:`muspy.Music` object Decoded Mu...
decode
python
salu133445/muspy
muspy/processors.py
https://github.com/salu133445/muspy/blob/master/muspy/processors.py
MIT
def encode(self, music: Music) -> ndarray: """Encode a Music object into pitch-based representation. Parameters ---------- music : :class:`muspy.Music` object Music object to encode. Returns ------- ndarray (np.uint8) Encoded array in pit...
Encode a Music object into pitch-based representation. Parameters ---------- music : :class:`muspy.Music` object Music object to encode. Returns ------- ndarray (np.uint8) Encoded array in pitch-based representation. See Also ---...
encode
python
salu133445/muspy
muspy/processors.py
https://github.com/salu133445/muspy/blob/master/muspy/processors.py
MIT
def decode(self, array: ndarray) -> Music: """Decode pitch-based representation into a Music object. Parameters ---------- array : ndarray Array in pitch-based representation to decode. Cast to integer if not of integer type. Returns ------- ...
Decode pitch-based representation into a Music object. Parameters ---------- array : ndarray Array in pitch-based representation to decode. Cast to integer if not of integer type. Returns ------- :class:`muspy.Music` object Decoded Mu...
decode
python
salu133445/muspy
muspy/processors.py
https://github.com/salu133445/muspy/blob/master/muspy/processors.py
MIT
def encode(self, music: Music) -> ndarray: """Encode a Music object into piano-roll representation. Parameters ---------- music : :class:`muspy.Music` object Music object to encode. Returns ------- ndarray (np.uint8) Encoded array in pian...
Encode a Music object into piano-roll representation. Parameters ---------- music : :class:`muspy.Music` object Music object to encode. Returns ------- ndarray (np.uint8) Encoded array in piano-roll representation. See Also -----...
encode
python
salu133445/muspy
muspy/processors.py
https://github.com/salu133445/muspy/blob/master/muspy/processors.py
MIT
def decode(self, array: ndarray) -> Music: """Decode piano-roll representation into a Music object. Parameters ---------- array : ndarray Array in piano-roll representation to decode. Cast to integer if not of integer type. If `encode_velocity` is Tru...
Decode piano-roll representation into a Music object. Parameters ---------- array : ndarray Array in piano-roll representation to decode. Cast to integer if not of integer type. If `encode_velocity` is True, casted to boolean if not of boolean type. ...
decode
python
salu133445/muspy
muspy/processors.py
https://github.com/salu133445/muspy/blob/master/muspy/processors.py
MIT
def note_str_to_note_num(note_str: str): """Return the note number of a note string. The regular expression for the note string is `[A-G][#b]*`. The base note must be capitalized. There can be multiple accidentals, where '#' denotes a sharp and 'b' denotes a flat. Some examples include 'C'->0, 'D#'...
Return the note number of a note string. The regular expression for the note string is `[A-G][#b]*`. The base note must be capitalized. There can be multiple accidentals, where '#' denotes a sharp and 'b' denotes a flat. Some examples include 'C'->0, 'D#'->3, 'Eb'->3. Parameters ---------- ...
note_str_to_note_num
python
salu133445/muspy
muspy/utils.py
https://github.com/salu133445/muspy/blob/master/muspy/utils.py
MIT
def yaml_dump( data, Dumper=None, allow_unicode: bool = True, **kwargs ): # pylint: disable=invalid-name """Dump data to YAML, which supports OrderedDict. Code adapted from https://stackoverflow.com/a/21912744. """ if Dumper is None: Dumper = OrderedDumper return yaml.dump( dat...
Dump data to YAML, which supports OrderedDict. Code adapted from https://stackoverflow.com/a/21912744.
yaml_dump
python
salu133445/muspy
muspy/utils.py
https://github.com/salu133445/muspy/blob/master/muspy/utils.py
MIT
def save( self, root: Union[str, Path], kind: str = "json", n_jobs: int = 1, ignore_exceptions: bool = True, verbose: bool = True, **kwargs, ): """Save all the music objects to a directory. Parameters ---------- root : str or P...
Save all the music objects to a directory. Parameters ---------- root : str or Path Root directory to save the data. kind : {'json', 'yaml'}, default: 'json' File format to save the data. n_jobs : int, default: 1 Maximum number of concurrently...
save
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def split( self, filename: Union[str, Path] = None, splits: Sequence[float] = None, random_state: Any = None, ) -> Dict[str, List[int]]: """Return the dataset as a PyTorch dataset. Parameters ---------- filename : str or Path, optional If ...
Return the dataset as a PyTorch dataset. Parameters ---------- filename : str or Path, optional If given and exists, path to the file to read the split from. If None or not exists, path to save the split. splits : float or list of float, optional Rati...
split
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def to_pytorch_dataset( self, factory: Callable = None, representation: str = None, split_filename: Union[str, Path] = None, splits: Sequence[float] = None, random_state: Any = None, **kwargs: Any, ) -> Union["TorchDataset", Dict[str, "TorchDataset"]]: ...
Return the dataset as a PyTorch dataset. Parameters ---------- factory : Callable, optional Function to be applied to the Music objects. The input is a Music object, and the output is an array or a tensor. representation : str, optional Target represe...
to_pytorch_dataset
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def to_tensorflow_dataset( self, factory: Callable = None, representation: str = None, split_filename: Union[str, Path] = None, splits: Sequence[float] = None, random_state: Any = None, **kwargs: Any, ) -> Union["TFDataset", Dict[str, "TFDataset"]]: ""...
Return the dataset as a TensorFlow dataset. Parameters ---------- factory : Callable, optional Function to be applied to the Music objects. The input is a Music object, and the output is an array or a tensor. representation : str, optional Target repr...
to_tensorflow_dataset
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def exists(self) -> bool: """Return True if the dataset exists, otherwise False.""" if not (self.root / ".muspy.success").is_file(): return False return True
Return True if the dataset exists, otherwise False.
exists
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def source_exists(self) -> bool: """Return True if all the sources exist, otherwise False.""" for source in self._sources.values(): filename = self.root / source["filename"] if not filename.is_file(): return False if "size" in source and not check_size...
Return True if all the sources exist, otherwise False.
source_exists
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def download( self: RemoteDatasetT, overwrite: bool = False, verbose: bool = True ) -> RemoteDatasetT: """Download the dataset source(s). Parameters ---------- overwrite : bool, default: False Whether to overwrite existing file(s). verbose : bool, default...
Download the dataset source(s). Parameters ---------- overwrite : bool, default: False Whether to overwrite existing file(s). verbose : bool, default: True Whether to be verbose. Returns ------- Object itself.
download
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def extract( self: RemoteDatasetT, cleanup: bool = False, verbose: bool = True ) -> RemoteDatasetT: """Extract the downloaded archive(s). Parameters ---------- cleanup : bool, default: False Whether to remove the source archive after extraction. verbose :...
Extract the downloaded archive(s). Parameters ---------- cleanup : bool, default: False Whether to remove the source archive after extraction. verbose : bool, default: True Whether to be verbose. Returns ------- Object itself.
extract
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def download_and_extract( self: RemoteDatasetT, overwrite: bool = False, cleanup: bool = False, verbose: bool = True, ) -> RemoteDatasetT: """Download source datasets and extract the downloaded archives. Parameters ---------- overwrite : bool, default...
Download source datasets and extract the downloaded archives. Parameters ---------- overwrite : bool, default: False Whether to overwrite existing file(s). cleanup : bool, default: False Whether to remove the source archive(s). verbose : bool, default: Tr...
download_and_extract
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def converted_exists(self) -> bool: """Return True if the saved dataset exists, otherwise False.""" if not (self.converted_dir / ".muspy.success").is_file(): return False return True
Return True if the saved dataset exists, otherwise False.
converted_exists
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def use_converted(self: FolderDatasetT) -> FolderDatasetT: """Disable on-the-fly mode and use converted data. Returns ------- Object itself. """ if not self.converted_exists(): raise RuntimeError( "Converted data not found. Run `convert()` to...
Disable on-the-fly mode and use converted data. Returns ------- Object itself.
use_converted
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def on_the_fly(self: FolderDatasetT) -> FolderDatasetT: """Enable on-the-fly mode and convert the data on the fly. Returns ------- Object itself. """ if not self.raw_filenames: self.raw_filenames = self.get_raw_filenames() self._filenames = self.raw_...
Enable on-the-fly mode and convert the data on the fly. Returns ------- Object itself.
on_the_fly
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT
def convert( self: FolderDatasetT, kind: str = "json", n_jobs: int = 1, ignore_exceptions: bool = True, verbose: bool = True, **kwargs, ) -> FolderDatasetT: """Convert and save the Music objects. The converted files will be named by its index and save...
Convert and save the Music objects. The converted files will be named by its index and saved to ``root/_converted``. The original filenames can be found in the ``filenames`` attribute. For example, the file at ``filenames[i]`` will be converted and saved to ``{i}.json``. Parame...
convert
python
salu133445/muspy
muspy/datasets/base.py
https://github.com/salu133445/muspy/blob/master/muspy/datasets/base.py
MIT