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 |
|---|---|---|---|---|---|---|---|
async def get_chat(self, room_id: str) -> YChat:
"""
Retrieves the YChat instance associated with a room ID. This method
is cached, i.e. successive calls with the same room ID quickly return a
cached value.
"""
if room_id in self.ychats_by_room:
return self.yc... |
Retrieves the YChat instance associated with a room ID. This method
is cached, i.e. successive calls with the same room ID quickly return a
cached value.
| get_chat | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/extension.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/extension.py | BSD-3-Clause |
async def stop_extension(self):
"""
Public method called by Jupyter Server when the server is stopping.
This calls the cleanup code defined in `self._stop_exception()` inside
an exception handler, as the server halts if this method raises an
exception.
"""
try:
... |
Public method called by Jupyter Server when the server is stopping.
This calls the cleanup code defined in `self._stop_exception()` inside
an exception handler, as the server halts if this method raises an
exception.
| stop_extension | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/extension.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/extension.py | BSD-3-Clause |
async def _stop_extension(self):
"""
Private method that defines the cleanup code to run when the server is
stopping.
"""
# TODO: explore if cleanup is necessary |
Private method that defines the cleanup code to run when the server is
stopping.
| _stop_extension | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/extension.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/extension.py | BSD-3-Clause |
def _init_persona_manager(self, ychat: YChat) -> Optional[PersonaManager]:
"""
Initializes a `PersonaManager` instance scoped to a `YChat`.
This method should not raise an exception. Upon encountering an
exception, this method will catch it, log it, and return `None`.
"""
... |
Initializes a `PersonaManager` instance scoped to a `YChat`.
This method should not raise an exception. Upon encountering an
exception, this method will catch it, log it, and return `None`.
| _init_persona_manager | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/extension.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/extension.py | BSD-3-Clause |
def _filter_blocked_models(self, providers: list[ListProvidersEntry]):
"""
Satisfy the model-level allow/blocklist by filtering models accordingly.
The provider-level allow/blocklist is already handled in
`AiExtension.initialize_settings()`.
"""
if self.blocked_models is ... |
Satisfy the model-level allow/blocklist by filtering models accordingly.
The provider-level allow/blocklist is already handled in
`AiExtension.initialize_settings()`.
| _filter_blocked_models | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/handlers.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/handlers.py | BSD-3-Clause |
def messages(self) -> list[BaseMessage]: # type:ignore[override]
"""
Returns the last `2 * k` messages preceding the latest message. If
`k` is set to `None`, return all preceding messages.
"""
# TODO: consider bounding history based on message size (e.g. total
# char/tok... |
Returns the last `2 * k` messages preceding the latest message. If
`k` is set to `None`, return all preceding messages.
| messages | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/history.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/history.py | BSD-3-Clause |
def _convert_to_langchain_messages(self, jchat_messages: list[JChatMessage]):
"""
Accepts a list of Jupyter Chat messages, and returns them as a list of
LangChain messages.
"""
messages: list[BaseMessage] = []
for jchat_message in jchat_messages:
if jchat_mess... |
Accepts a list of Jupyter Chat messages, and returns them as a list of
LangChain messages.
| _convert_to_langchain_messages | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/history.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/history.py | BSD-3-Clause |
async def handle_request(self, message: InlineCompletionRequest) -> None:
"""
Handles an inline completion request, without streaming. Subclasses
must define this method and write a reply via `self.reply()`.
The method definition does not need to be wrapped in a try/except block.
... |
Handles an inline completion request, without streaming. Subclasses
must define this method and write a reply via `self.reply()`.
The method definition does not need to be wrapped in a try/except block.
| handle_request | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/completions/handlers/base.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/completions/handlers/base.py | BSD-3-Clause |
async def handle_stream_request(self, message: InlineCompletionRequest) -> None:
"""
Handles an inline completion request, **with streaming**.
Implementations may optionally define this method. Implementations that
do so should stream replies via successive calls to `self.reply()`.
... |
Handles an inline completion request, **with streaming**.
Implementations may optionally define this method. Implementations that
do so should stream replies via successive calls to `self.reply()`.
The method definition does not need to be wrapped in a try/except block.
| handle_stream_request | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/completions/handlers/base.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/completions/handlers/base.py | BSD-3-Clause |
async def on_message(self, message):
"""Public Tornado method that is called when the client sends a message
over this connection. This should **not** be overriden by subclasses."""
# first, verify that the message is an `InlineCompletionRequest`.
self.log.debug("Message received: %s", ... | Public Tornado method that is called when the client sends a message
over this connection. This should **not** be overriden by subclasses. | on_message | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/completions/handlers/base.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/completions/handlers/base.py | BSD-3-Clause |
async def handle_exc(self, e: Exception, request: InlineCompletionRequest):
"""
Handles an exception raised in either `handle_request()` or
`handle_stream_request()`. This base class provides a default
implementation, which may be overridden by subclasses.
"""
title = e.a... |
Handles an exception raised in either `handle_request()` or
`handle_stream_request()`. This base class provides a default
implementation, which may be overridden by subclasses.
| handle_exc | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/completions/handlers/base.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/completions/handlers/base.py | BSD-3-Clause |
async def handle_request(self, request: InlineCompletionRequest):
"""Handles an inline completion request without streaming."""
llm = self.get_llm()
if not llm:
raise ValueError("Please select a model for inline completion.")
reply = await llm.generate_inline_completions(req... | Handles an inline completion request without streaming. | handle_request | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/completions/handlers/default.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/completions/handlers/default.py | BSD-3-Clause |
def defaults(self) -> PersonaDefaults:
"""
Returns a `PersonaDefaults` data model that represents the default
settings of this persona.
This is an abstract method that must be implemented by subclasses.
""" |
Returns a `PersonaDefaults` data model that represents the default
settings of this persona.
This is an abstract method that must be implemented by subclasses.
| defaults | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/personas/base_persona.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/personas/base_persona.py | BSD-3-Clause |
async def process_message(self, message: Message) -> None:
"""
Processes a new message. This method exclusively defines how new
messages are handled by a persona, and should be considered the "main
entry point" to this persona. Reading chat history and streaming a reply
can be do... |
Processes a new message. This method exclusively defines how new
messages are handled by a persona, and should be considered the "main
entry point" to this persona. Reading chat history and streaming a reply
can be done through method calls to `self.ychat`. See
`JupyternautPerso... | process_message | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/personas/base_persona.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/personas/base_persona.py | BSD-3-Clause |
def id(self) -> str:
"""
Returns a static & unique ID for this persona. This sets the `username`
field in the data model returned by `self.as_user()`.
The ID is guaranteed to follow the format
`jupyter-ai-personas::<package-name>::<persona-class-name>`. The prefix
allows... |
Returns a static & unique ID for this persona. This sets the `username`
field in the data model returned by `self.as_user()`.
The ID is guaranteed to follow the format
`jupyter-ai-personas::<package-name>::<persona-class-name>`. The prefix
allows consumers to easily distinguish... | id | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/personas/base_persona.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/personas/base_persona.py | BSD-3-Clause |
def as_user(self) -> User:
"""
Returns the `jupyterlab_chat.models:User` model that represents this
persona in the chat. This model also includes all attributes from
`jupyter_server.auth:JupyterUser`, the user model returned by the
`IdentityProvider` in Jupyter Server.
T... |
Returns the `jupyterlab_chat.models:User` model that represents this
persona in the chat. This model also includes all attributes from
`jupyter_server.auth:JupyterUser`, the user model returned by the
`IdentityProvider` in Jupyter Server.
This method is provided by `BasePersona... | as_user | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/personas/base_persona.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/personas/base_persona.py | BSD-3-Clause |
async def stream_message(self, reply_stream: "AsyncIterator") -> None:
"""
Takes an async iterator, dubbed the 'reply stream', and streams it to a
new message by this persona in the YChat.
- Creates a new message upon receiving the first chunk from the reply
stream, then continu... |
Takes an async iterator, dubbed the 'reply stream', and streams it to a
new message by this persona in the YChat.
- Creates a new message upon receiving the first chunk from the reply
stream, then continuously updates it until the stream is closed.
- Automatically manages its ... | stream_message | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/personas/base_persona.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/personas/base_persona.py | BSD-3-Clause |
def as_custom_client(self) -> "Iterator[None]":
"""
Context manager that automatically:
- Sets the awareness client ID to the custom client ID created by this
instance upon entering.
- Resets the awareness client ID back to the original client ID upon
exiting.
"... |
Context manager that automatically:
- Sets the awareness client ID to the custom client ID created by this
instance upon entering.
- Resets the awareness client ID back to the original client ID upon
exiting.
| as_custom_client | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/personas/persona_awareness.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/personas/persona_awareness.py | BSD-3-Clause |
async def _start_heartbeat(self):
"""
Background task that updates this instance's local state every
`0.8 * self.outdated_timeout` milliseconds. `pycrdt` and `yjs`
automatically disconnect clients if they do not make updates in
a long time (default: 30000 ms). This task keeps per... |
Background task that updates this instance's local state every
`0.8 * self.outdated_timeout` milliseconds. `pycrdt` and `yjs`
automatically disconnect clients if they do not make updates in
a long time (default: 30000 ms). This task keeps personas alive
after 30 seconds of no us... | _start_heartbeat | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/personas/persona_awareness.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/personas/persona_awareness.py | BSD-3-Clause |
def _init_persona_classes(self) -> None:
"""
Initializes the list of persona *classes* by retrieving the
`jupyter-ai.personas` entry points group.
This list is cached in the `PersonaManager._persona_classes` class
attribute, i.e. this method should only run once in the extension... |
Initializes the list of persona *classes* by retrieving the
`jupyter-ai.personas` entry points group.
This list is cached in the `PersonaManager._persona_classes` class
attribute, i.e. this method should only run once in the extension
lifecycle.
| _init_persona_classes | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/personas/persona_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/personas/persona_manager.py | BSD-3-Clause |
def _init_personas(self) -> dict[str, BasePersona]:
"""
Initializes the list of persona instances for the YChat instance passed
to the constructor.
"""
# Ensure that persona classes were initialized first
persona_classes = PersonaManager._persona_classes
assert is... |
Initializes the list of persona instances for the YChat instance passed
to the constructor.
| _init_personas | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/personas/persona_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/personas/persona_manager.py | BSD-3-Clause |
def get_mentioned_personas(self, new_message: Message) -> list[BasePersona]:
"""
Returns a list of all personas `@`-mentioned in a chat message, given a
reference to the chat message.
"""
mentioned_ids = set(new_message.mentions or [])
persona_list: list[BasePersona] = []... |
Returns a list of all personas `@`-mentioned in a chat message, given a
reference to the chat message.
| get_mentioned_personas | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/personas/persona_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/personas/persona_manager.py | BSD-3-Clause |
def route_message(self, new_message: Message):
"""
Method that routes an incoming message to the correct persona by calling
its `process_message()` method.
- (TODO) If the chat contains only one persona & one user, then this
method routes all new messages to that persona.
... |
Method that routes an incoming message to the correct persona by calling
its `process_message()` method.
- (TODO) If the chat contains only one persona & one user, then this
method routes all new messages to that persona.
- Otherwise, this method only routes new messages to pe... | route_message | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/personas/persona_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/personas/persona_manager.py | BSD-3-Clause |
def config_file_with_model_fields(jp_data_dir):
"""
Fixture that creates a `config.json` file with the chat model set to
`openai-chat:gpt-4o` and fields for that model. Returns path to the file.
"""
config_data = {
"model_provider_id:": "openai-chat:gpt-4o",
"embeddings_provider_id":... |
Fixture that creates a `config.json` file with the chat model set to
`openai-chat:gpt-4o` and fields for that model. Returns path to the file.
| config_file_with_model_fields | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def common_cm_kwargs(config_path, schema_path):
"""Kwargs that are commonly used when initializing the CM."""
log = logging.getLogger()
lm_providers = get_lm_providers()
em_providers = get_em_providers()
return {
"log": log,
"lm_providers": lm_providers,
"em_providers": em_pr... | Kwargs that are commonly used when initializing the CM. | common_cm_kwargs | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def reset(config_path, schema_path):
"""Fixture that deletes the config and config schema after each test."""
yield
try:
os.remove(config_path)
except OSError:
pass
try:
os.remove(schema_path)
except OSError:
pass | Fixture that deletes the config and config schema after each test. | reset | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def config_with_bad_provider_ids(tmp_path):
"""Fixture that creates a `config.json` with `model_provider_id` and `embeddings_provider_id` values that would not associate with models. File is created in `tmp_path` folder. Function returns path to the file."""
config_data = {
"model_provider_id:": "foo:b... | Fixture that creates a `config.json` with `model_provider_id` and `embeddings_provider_id` values that would not associate with models. File is created in `tmp_path` folder. Function returns path to the file. | config_with_bad_provider_ids | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def configure_to_cohere(cm: ConfigManager):
"""Configures the ConfigManager to use Cohere language and embedding models
with the API key set. Returns a 3-tuple of the keyword arguments used."""
LM_GID = "cohere:xlarge"
EM_GID = "cohere:large"
API_KEYS = {"COHERE_API_KEY": "foobar"}
# the params ... | Configures the ConfigManager to use Cohere language and embedding models
with the API key set. Returns a 3-tuple of the keyword arguments used. | configure_to_cohere | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def configure_to_openai(cm: ConfigManager):
"""Configures the ConfigManager to use OpenAI language and embedding models
with the API key set. Returns a 3-tuple of the keyword arguments used."""
LM_GID = "openai-chat:gpt-3.5-turbo"
EM_GID = "openai:text-embedding-ada-002"
API_KEYS = {"OPENAI_API_KEY"... | Configures the ConfigManager to use OpenAI language and embedding models
with the API key set. Returns a 3-tuple of the keyword arguments used. | configure_to_openai | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def configure_with_fields(cm: ConfigManager, completions: bool = False):
"""
Default behavior: Configures the ConfigManager with fields and API keys.
Returns the expected result of `cm.lm_provider_params`.
If `completions` is set to `True`, this configures the ConfigManager with
completion model fi... |
Default behavior: Configures the ConfigManager with fields and API keys.
Returns the expected result of `cm.lm_provider_params`.
If `completions` is set to `True`, this configures the ConfigManager with
completion model fields, and returns the expected result of
`cm.completions_lm_provider_params`... | configure_with_fields | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def test_init_with_default_values(
cm_with_defaults: ConfigManager,
config_path: str,
schema_path: str,
common_cm_kwargs,
):
"""
Test that the ConfigManager initializes with the expected default values.
Args:
cm_with_defaults (ConfigManager): A ConfigManager instance with default va... |
Test that the ConfigManager initializes with the expected default values.
Args:
cm_with_defaults (ConfigManager): A ConfigManager instance with default values.
config_path (str): The path to the configuration file.
schema_path (str): The path to the schema file.
| test_init_with_default_values | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def test_property_access_on_default_config(cm: ConfigManager):
"""Asserts that the CM behaves well with an empty, default
configuration."""
assert cm.lm_gid == None
assert cm.em_gid == None
assert cm.lm_provider == None
assert cm.lm_provider_params == None
assert cm.em_provider == None
a... | Asserts that the CM behaves well with an empty, default
configuration. | test_property_access_on_default_config | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def test_indentation_depth(common_cm_kwargs, config_path):
"""Asserts that the CM indents the configuration and respects the
`indentation_depth` trait when specified."""
INDENT_DEPTH = 7
ConfigManager(**common_cm_kwargs, indentation_depth=INDENT_DEPTH)
with open(config_path) as f:
config_fil... | Asserts that the CM indents the configuration and respects the
`indentation_depth` trait when specified. | test_indentation_depth | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def test_update_api_key(cm: ConfigManager):
"""Asserts that updates via direct edits to the config file are immediately
reflected by the ConfigManager."""
LM_GID, EM_GID, LM_LID, EM_LID, _ = configure_to_cohere(cm)
cm.update_config(UpdateConfigRequest(api_keys={"COHERE_API_KEY": "barfoo"}))
config_... | Asserts that updates via direct edits to the config file are immediately
reflected by the ConfigManager. | test_update_api_key | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def test_returns_chat_model_fields(cm):
"""
Asserts that `ConfigManager.lm_provider_params` returns model fields set by
the user.
"""
expected_model_args = configure_with_fields(cm)
assert cm.lm_provider_params == expected_model_args |
Asserts that `ConfigManager.lm_provider_params` returns model fields set by
the user.
| test_returns_chat_model_fields | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def test_config_manager_does_not_write_to_defaults(
config_file_with_model_fields, schema_path
):
"""
Asserts that `ConfigManager` does not write to the `defaults` argument when
the configured chat model differs from the one specified in `defaults`.
"""
from copy import deepcopy
config_path... |
Asserts that `ConfigManager` does not write to the `defaults` argument when
the configured chat model differs from the one specified in `defaults`.
| test_config_manager_does_not_write_to_defaults | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
def test_config_manager_updates_schema(jp_data_dir, common_cm_kwargs):
"""
Asserts that the ConfigManager adds new keys to the user's config schema
which are present in Jupyter AI's schema on init. Asserts that the main
issue reported in #1291 does not occur again in the future.
"""
schema_path ... |
Asserts that the ConfigManager adds new keys to the user's config schema
which are present in Jupyter AI's schema on init. Asserts that the main
issue reported in #1291 does not occur again in the future.
| test_config_manager_updates_schema | python | jupyterlab/jupyter-ai | packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai/jupyter_ai/tests/test_config_manager.py | BSD-3-Clause |
async def _call_in_executor(self, *args, **kwargs) -> Coroutine[Any, Any, str]:
"""
Calls self._call() asynchronously in a separate thread for providers
without an async implementation. Requires the event loop to be running.
"""
executor = ThreadPoolExecutor(max_workers=1)
... |
Calls self._call() asynchronously in a separate thread for providers
without an async implementation. Requires the event loop to be running.
| _call_in_executor | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/base_provider.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/base_provider.py | BSD-3-Clause |
async def _generate_in_executor(
self, *args, **kwargs
) -> Coroutine[Any, Any, LLMResult]:
"""
Calls self._generate() asynchronously in a separate thread for providers
without an async implementation. Requires the event loop to be running.
"""
executor = ThreadPoolEx... |
Calls self._generate() asynchronously in a separate thread for providers
without an async implementation. Requires the event loop to be running.
| _generate_in_executor | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/base_provider.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/base_provider.py | BSD-3-Clause |
def get_prompt_template(self, format) -> PromptTemplate:
"""
Produce a prompt template suitable for use with a particular model, to
produce output in a desired format.
"""
if format in self.prompt_templates:
return self.prompt_templates[format]
else:
... |
Produce a prompt template suitable for use with a particular model, to
produce output in a desired format.
| get_prompt_template | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/base_provider.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/base_provider.py | BSD-3-Clause |
def get_chat_prompt_template(self) -> PromptTemplate:
"""
Produce a prompt template optimised for chat conversation.
The template should take two variables: history and input.
"""
name = self.__class__.name
if self.is_chat_provider:
return ChatPromptTemplate.f... |
Produce a prompt template optimised for chat conversation.
The template should take two variables: history and input.
| get_chat_prompt_template | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/base_provider.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/base_provider.py | BSD-3-Clause |
def get_completion_prompt_template(self) -> PromptTemplate:
"""
Produce a prompt template optimised for inline code or text completion.
The template should take variables: prefix, suffix, language, filename.
"""
if self.is_chat_provider:
return ChatPromptTemplate.from... |
Produce a prompt template optimised for inline code or text completion.
The template should take variables: prefix, suffix, language, filename.
| get_completion_prompt_template | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/base_provider.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/base_provider.py | BSD-3-Clause |
def post_process_suggestion(suggestion: str, request: InlineCompletionRequest) -> str:
"""Remove spurious fragments from the suggestion.
While most models (especially instruct and infill models do not require
any pre-processing, some models such as gpt-4 which only have chat APIs
may require removing s... | Remove spurious fragments from the suggestion.
While most models (especially instruct and infill models do not require
any pre-processing, some models such as gpt-4 which only have chat APIs
may require removing spurious fragments. This function uses heuristics
and request data to remove such fragments... | post_process_suggestion | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/completion_utils.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/completion_utils.py | BSD-3-Clause |
def _decompose_model_id(self, model_id: str):
"""Breaks down a model ID into a two-tuple (provider_id, local_model_id). Returns (None, None) if indeterminate."""
# custom_model_registry maps keys to either a model name (a string) or an LLMChain.
# If this is an alias to another model, expand the... | Breaks down a model ID into a two-tuple (provider_id, local_model_id). Returns (None, None) if indeterminate. | _decompose_model_id | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/magics.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/magics.py | BSD-3-Clause |
def _get_provider(self, provider_id: Optional[str]) -> BaseProvider:
"""Returns the model provider ID and class for a model ID. Returns None if indeterminate."""
if provider_id is None or provider_id not in self.providers:
return None
return self.providers[provider_id] | Returns the model provider ID and class for a model ID. Returns None if indeterminate. | _get_provider | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/magics.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/magics.py | BSD-3-Clause |
def cell_magic_parser(context: click.Context, **kwargs):
"""
Invokes a language model identified by MODEL_ID, with the prompt being
contained in all lines after the first. Both local model IDs and global
model IDs (with the provider ID explicitly prefixed, followed by a colon)
are accepted.
To ... |
Invokes a language model identified by MODEL_ID, with the prompt being
contained in all lines after the first. Both local model IDs and global
model IDs (with the provider ID explicitly prefixed, followed by a colon)
are accepted.
To view available language models, please run `%ai list`.
| cell_magic_parser | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/parsers.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/parsers.py | BSD-3-Clause |
def error_subparser(context: click.Context, **kwargs):
"""
Explains the most recent error. Takes the same options (except -r) as
the basic `%%ai` command.
"""
if not kwargs["model_id"] and context.default_map:
kwargs["model_id"] = context.default_map["error_subparser"]["model_id"]
return... |
Explains the most recent error. Takes the same options (except -r) as
the basic `%%ai` command.
| error_subparser | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/parsers.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/parsers.py | BSD-3-Clause |
def is_api_key_exc(cls, e: Exception):
"""
Determine if the exception is an AI21 API key error.
"""
if isinstance(e, ValueError):
return "status code 401" in str(e)
return False |
Determine if the exception is an AI21 API key error.
| is_api_key_exc | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/providers.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/providers.py | BSD-3-Clause |
def _call(
self, prompt: str, stop: Optional[list[str]] = None, **kwargs: Any
) -> str:
"""Call out to Hugging Face Hub's inference endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
... | Call out to Hugging Face Hub's inference endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string or image generated by the model.
Example:
.. code-block:: python
... | _call | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/providers.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/providers.py | BSD-3-Clause |
def get_lm_provider(
model_id: str, lm_providers: LmProvidersDict
) -> tuple[str, type[BaseProvider]]:
"""Gets a two-tuple (<local-model-id>, <provider-class>) specified by a
global model ID."""
return _get_provider(model_id, lm_providers) | Gets a two-tuple (<local-model-id>, <provider-class>) specified by a
global model ID. | get_lm_provider | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/utils.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/utils.py | BSD-3-Clause |
def import_attr(
attr_name: str,
module_name: Union[str, None],
package: Union[str, None],
) -> object:
"""Import an attribute from a module located in a package.
This utility function is used in custom __getattr__ methods within __init__.py
files to dynamically import attributes.
Args:
... | Import an attribute from a module located in a package.
This utility function is used in custom __getattr__ methods within __init__.py
files to dynamically import attributes.
Args:
attr_name: The name of the attribute to import.
module_name: The name of the module to import from. If None, ... | import_attr | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/_import_utils.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/_import_utils.py | BSD-3-Clause |
def is_api_key_exc(cls, e: Exception):
"""
Determine if the exception is an Anthropic API key error.
"""
import anthropic
if isinstance(e, anthropic.AuthenticationError):
return e.status_code == 401 and "Invalid API Key" in str(e)
return False |
Determine if the exception is an Anthropic API key error.
| is_api_key_exc | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/partner_providers/anthropic.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/partner_providers/anthropic.py | BSD-3-Clause |
def is_api_key_exc(cls, e: Exception):
"""
Determine if the exception is an OpenAI API key error.
"""
import openai
if isinstance(e, openai.AuthenticationError):
error_details = e.json_body.get("error", {})
return error_details.get("code") == "invalid_api... |
Determine if the exception is an OpenAI API key error.
| is_api_key_exc | python | jupyterlab/jupyter-ai | packages/jupyter-ai-magics/jupyter_ai_magics/partner_providers/openai.py | https://github.com/jupyterlab/jupyter-ai/blob/master/packages/jupyter-ai-magics/jupyter_ai_magics/partner_providers/openai.py | BSD-3-Clause |
def _get_size(self, tokenL):
""" return the size of the next object."""
if tokenL == 0xF:
m = self._fp.read(1)[0]
if not _check_py3():
m = ord(m)
m = m & 0x3
s = 1 << m
f = '>' + _BINARY_FORMAT[s]
return struct.unpac... | return the size of the next object. | _get_size | python | corpnewt/GenSMBIOS | Scripts/plist.py | https://github.com/corpnewt/GenSMBIOS/blob/master/Scripts/plist.py | MIT |
def _read_object(self, ref):
"""
read the object by reference.
May recursively read sub-objects (content of an array/dict/set)
"""
result = self._objects[ref]
if result is not _undefined:
return result
offset = self._object_offsets[ref]
self._... |
read the object by reference.
May recursively read sub-objects (content of an array/dict/set)
| _read_object | python | corpnewt/GenSMBIOS | Scripts/plist.py | https://github.com/corpnewt/GenSMBIOS/blob/master/Scripts/plist.py | MIT |
def inner(text, rl=False):
"""
Every raw_input with color sequences should be called with
rl=True to avoid readline messed up the length calculation
"""
c = code
if rl:
return "\001\033[%sm\002%s\001\033[0m\002" % (c, text)
else:
return "\0... |
Every raw_input with color sequences should be called with
rl=True to avoid readline messed up the length calculation
| inner | python | orakaro/rainbowstream | rainbowstream/colors.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/colors.py | MIT |
def user_filepath():
"""
Determine the user's config file location
"""
if 'RAINBOW_CONFIG' in os.environ:
return os.environ['RAINBOW_CONFIG']
return os.path.expanduser("~") + os.sep + '.rainbow_config.json' |
Determine the user's config file location
| user_filepath | python | orakaro/rainbowstream | rainbowstream/config.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/config.py | MIT |
def fixup(adict, k, v):
"""
Fix up a key in json format
"""
for key in adict.keys():
if key == k:
adict[key] = v
elif isinstance(adict[key], dict):
fixup(adict[key], k, v) |
Fix up a key in json format
| fixup | python | orakaro/rainbowstream | rainbowstream/config.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/config.py | MIT |
def get_default_config(key):
"""
Get default value of a config key
"""
try:
path = os.path.dirname(__file__) + '/colorset/config'
data = load_config(path)
return data[key]
except:
raise Exception('This config key does not exist in default.') |
Get default value of a config key
| get_default_config | python | orakaro/rainbowstream | rainbowstream/config.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/config.py | MIT |
def set_config(key, value):
"""
Set a config key with specific value
"""
# Modify value
if value.isdigit():
value = int(value)
elif value.lower() == 'true':
value = True
elif value.lower() == 'false':
value = False
# Update global config
c[key] = value
# L... |
Set a config key with specific value
| set_config | python | orakaro/rainbowstream | rainbowstream/config.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/config.py | MIT |
def call_c():
"""
Call the C program for converting RGB to Ansi colors
"""
library = expanduser('~/.image.so')
sauce = join(dirname(__file__), 'image.c')
if not exists(library) or getmtime(sauce) > getmtime(library):
build = "cc -fPIC -shared -o %s %s" % (library, sauce)
os.syste... |
Call the C program for converting RGB to Ansi colors
| call_c | python | orakaro/rainbowstream | rainbowstream/c_image.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/c_image.py | MIT |
def pixel_print(pixel):
"""
Print a pixel with given Ansi color
"""
r, g, b = pixel[:3]
if c['24BIT'] is True:
sys.stdout.write('\033[48;2;%d;%d;%dm \033[0m'
% (r, g, b))
else:
ansicolor = rgb2short(r, g, b)
sys.stdout.write('\033[48;5;%sm \033[0... |
Print a pixel with given Ansi color
| pixel_print | python | orakaro/rainbowstream | rainbowstream/c_image.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/c_image.py | MIT |
def order_rainbow(s):
"""
Print a string with ordered color with each character
"""
colors_shuffle = [globals()[i.encode('utf8')]
if not str(i).isdigit()
else term_color(int(i))
for i in c['CYCLE_COLOR']]
colored = [colors_shuffle[i %... |
Print a string with ordered color with each character
| order_rainbow | python | orakaro/rainbowstream | rainbowstream/draw.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/draw.py | MIT |
def random_rainbow(s):
"""
Print a string with random color with each character
"""
colors_shuffle = [globals()[i.encode('utf8')]
if not str(i).isdigit()
else term_color(int(i))
for i in c['CYCLE_COLOR']]
colored = [random.choice(colo... |
Print a string with random color with each character
| random_rainbow | python | orakaro/rainbowstream | rainbowstream/draw.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/draw.py | MIT |
def reload_theme(value, prev):
"""
Check current theme and update if necessary
"""
if value != prev:
config = os.path.dirname(
__file__) + '/colorset/' + value + '.json'
# Load new config
data = load_config(config)
if data:
for d in data:
... |
Check current theme and update if necessary
| reload_theme | python | orakaro/rainbowstream | rainbowstream/draw.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/draw.py | MIT |
def color_func(func_name):
"""
Call color function base on name
"""
if str(func_name).isdigit():
return term_color(int(func_name))
return globals()[func_name] |
Call color function base on name
| color_func | python | orakaro/rainbowstream | rainbowstream/draw.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/draw.py | MIT |
def fallback_humanize(date, fallback_format=None, use_fallback=False):
"""
Format date with arrow and a fallback format
"""
# Convert to local timezone
date = arrow.get(date).to('local')
# Set default fallback format
if not fallback_format:
fallback_format = '%Y/%m/%d %H:%M:%S'
#... |
Format date with arrow and a fallback format
| fallback_humanize | python | orakaro/rainbowstream | rainbowstream/draw.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/draw.py | MIT |
def get_full_text(t):
"""Handle RTs and extended tweets to always display all the available text"""
if t.get('retweeted_status'):
rt_status = t['retweeted_status']
if rt_status.get('extended_tweet'):
elem = rt_status['extended_tweet']
else:
elem = rt_status
... | Handle RTs and extended tweets to always display all the available text | get_full_text | python | orakaro/rainbowstream | rainbowstream/draw.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/draw.py | MIT |
def print_right_message(m):
"""
Print a message on the right of screen
"""
h, w = os.popen('stty size', 'r').read().split()
w = int(w)
frame_width = w // 3 - dg['frame_margin']
frame_width = max(c['THREAD_MIN_WIDTH'], frame_width)
step = frame_width - 2 * dg['frame_margin']
slicing =... |
Print a message on the right of screen
| print_right_message | python | orakaro/rainbowstream | rainbowstream/draw.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/draw.py | MIT |
def print_left_message(m):
"""
Print a message on the left of screen
"""
h, w = os.popen('stty size', 'r').read().split()
w = int(w)
frame_width = w // 3 - dg['frame_margin']
frame_width = max(c['THREAD_MIN_WIDTH'], frame_width)
step = frame_width - 2 * dg['frame_margin']
slicing = t... |
Print a message on the left of screen
| print_left_message | python | orakaro/rainbowstream | rainbowstream/draw.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/draw.py | MIT |
def show_calendar(month, date, rel):
"""
Show the calendar in rainbow mode
"""
month = random_rainbow(month)
date = ' '.join([cycle_color(i) for i in date.split(' ')])
today = str(int(os.popen('date +\'%d\'').read().strip()))
# Display
printNicely(month)
printNicely(date)
for lin... |
Show the calendar in rainbow mode
| show_calendar | python | orakaro/rainbowstream | rainbowstream/draw.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/draw.py | MIT |
def upgrade_center():
"""
Check latest and notify to upgrade
"""
try:
current = pkg_resources.get_distribution('rainbowstream').version
url = 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
readme = requests.get(url).text
latest = readme.split('vers... |
Check latest and notify to upgrade
| upgrade_center | python | orakaro/rainbowstream | rainbowstream/rainbow.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/rainbow.py | MIT |
def upload_twitter_media(image_paths):
"""
Upload media and images to wtiter using their api
"""
image_ids = []
for image_path in image_paths:
image_path = image_path.strip()
image_path = os.path.expanduser(image_path)
image_data = open(image_path, 'rb').read()
#... |
Upload media and images to wtiter using their api
| upload_twitter_media | python | orakaro/rainbowstream | rainbowstream/rainbow.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/rainbow.py | MIT |
def pocket():
"""
Add new link to Pocket along with tweet id
"""
if not c['POCKET_SUPPORT']:
printNicely(yellow('Pocket isn\'t enabled.'))
printNicely(yellow('You need to "config POCKET_SUPPORT = true"'))
return
# Get tweet infos
p = pckt_authen()
t = Twitter(auth=a... |
Add new link to Pocket along with tweet id
| pocket | python | orakaro/rainbowstream | rainbowstream/rainbow.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/rainbow.py | MIT |
def share():
"""
Copy url of a tweet to clipboard
"""
t = Twitter(auth=authen())
try:
id = int(g['stuff'].split()[0])
tid = c['tweet_dict'][id]
except:
printNicely(red('Tweet id is not valid.'))
return
kwargs = {'id': tid}
kwargs = add_tweetmode_parameter(... |
Copy url of a tweet to clipboard
| share | python | orakaro/rainbowstream | rainbowstream/rainbow.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/rainbow.py | MIT |
def add_tweetmode_parameter(kwargs):
"""
Add support for extended mode to Twitter API calls unless explicitly stated in config
"""
if not c.get('DISABLE_EXTENDED_TWEETS'):
kwargs['tweet_mode'] = 'extended'
return kwargs |
Add support for extended mode to Twitter API calls unless explicitly stated in config
| add_tweetmode_parameter | python | orakaro/rainbowstream | rainbowstream/util.py | https://github.com/orakaro/rainbowstream/blob/master/rainbowstream/util.py | MIT |
def predict_check(pred_variable, gold_variable, mask_variable, sentence_classification=False):
"""
input:
pred_variable (batch_size, sent_len): pred tag result, in numpy format
gold_variable (batch_size, sent_len): gold result variable
mask_variable (batch_size, sent_len)... |
input:
pred_variable (batch_size, sent_len): pred tag result, in numpy format
gold_variable (batch_size, sent_len): gold result variable
mask_variable (batch_size, sent_len): mask variable
| predict_check | python | jiesutd/NCRFpp | main.py | https://github.com/jiesutd/NCRFpp/blob/master/main.py | Apache-2.0 |
def recover_label(pred_variable, gold_variable, mask_variable, label_alphabet, word_recover, sentence_classification=False):
"""
input:
pred_variable (batch_size, sent_len): pred tag result
gold_variable (batch_size, sent_len): gold result variable
mask_variable (batch_si... |
input:
pred_variable (batch_size, sent_len): pred tag result
gold_variable (batch_size, sent_len): gold result variable
mask_variable (batch_size, sent_len): mask variable
| recover_label | python | jiesutd/NCRFpp | main.py | https://github.com/jiesutd/NCRFpp/blob/master/main.py | Apache-2.0 |
def recover_nbest_label(pred_variable, mask_variable, label_alphabet, word_recover):
"""
input:
pred_variable (batch_size, sent_len, nbest): pred tag result
mask_variable (batch_size, sent_len): mask variable
word_recover (batch_size)
output:
nbest_pre... |
input:
pred_variable (batch_size, sent_len, nbest): pred tag result
mask_variable (batch_size, sent_len): mask variable
word_recover (batch_size)
output:
nbest_pred_label list: [batch_size, nbest, each_seq_len]
| recover_nbest_label | python | jiesutd/NCRFpp | main.py | https://github.com/jiesutd/NCRFpp/blob/master/main.py | Apache-2.0 |
def batchify_sequence_labeling_with_label(input_batch_list, gpu, if_train=True):
"""
input: list of words, chars and labels, various length. [[words, features, chars, labels],[words, features, chars,labels],...]
words: word ids for one sentence. (batch_size, sent_len)
features: featu... |
input: list of words, chars and labels, various length. [[words, features, chars, labels],[words, features, chars,labels],...]
words: word ids for one sentence. (batch_size, sent_len)
features: features ids for one sentence. (batch_size, sent_len, feature_num)
chars: char id... | batchify_sequence_labeling_with_label | python | jiesutd/NCRFpp | main.py | https://github.com/jiesutd/NCRFpp/blob/master/main.py | Apache-2.0 |
def batchify_sentence_classification_with_label(input_batch_list, gpu, if_train=True):
"""
input: list of words, chars and labels, various length. [[words, features, chars, labels],[words, features, chars,labels],...]
words: word ids for one sentence. (batch_size, sent_len)
features:... |
input: list of words, chars and labels, various length. [[words, features, chars, labels],[words, features, chars,labels],...]
words: word ids for one sentence. (batch_size, sent_len)
features: features ids for one sentence. (batch_size, feature_num), each sentence has one set of featur... | batchify_sentence_classification_with_label | python | jiesutd/NCRFpp | main.py | https://github.com/jiesutd/NCRFpp/blob/master/main.py | Apache-2.0 |
def batchify_with_label(input_batch_list, gpu, volatile_flag=False):
"""
input: list of words, chars and labels, various length. [[words,chars, labels],[words,chars,labels],...]
words: word ids for one sentence. (batch_size, sent_len)
chars: char ids for on sentences, various length... |
input: list of words, chars and labels, various length. [[words,chars, labels],[words,chars,labels],...]
words: word ids for one sentence. (batch_size, sent_len)
chars: char ids for on sentences, various length. (batch_size, sent_len, each_word_length)
output:
zero ... | batchify_with_label | python | jiesutd/NCRFpp | main_parse.py | https://github.com/jiesutd/NCRFpp/blob/master/main_parse.py | Apache-2.0 |
def get_last_hiddens(self, input, seq_lengths):
"""
input:
input: Variable(batch_size, word_length)
seq_lengths: numpy array (batch_size, 1)
output:
Variable(batch_size, char_hidden_dim)
Note it only accepts ordered (length) va... |
input:
input: Variable(batch_size, word_length)
seq_lengths: numpy array (batch_size, 1)
output:
Variable(batch_size, char_hidden_dim)
Note it only accepts ordered (length) variable, length size is recorded in seq_lengths
| get_last_hiddens | python | jiesutd/NCRFpp | model/charbigru.py | https://github.com/jiesutd/NCRFpp/blob/master/model/charbigru.py | Apache-2.0 |
def get_all_hiddens(self, input, seq_lengths):
"""
input:
input: Variable(batch_size, word_length)
seq_lengths: numpy array (batch_size, 1)
output:
Variable(batch_size, word_length, char_hidden_dim)
Note it only accepts ordere... |
input:
input: Variable(batch_size, word_length)
seq_lengths: numpy array (batch_size, 1)
output:
Variable(batch_size, word_length, char_hidden_dim)
Note it only accepts ordered (length) variable, length size is recorded in seq_length... | get_all_hiddens | python | jiesutd/NCRFpp | model/charbigru.py | https://github.com/jiesutd/NCRFpp/blob/master/model/charbigru.py | Apache-2.0 |
def log_sum_exp(vec, m_size):
"""
calculate log of exp sum
args:
vec (batch_size, vanishing_dim, hidden_dim) : input tensor
m_size : hidden_dim
return:
batch_size, hidden_dim
"""
_, idx = torch.max(vec, 1) # B * 1 * M
max_score = torch.gather(vec, 1, idx.view(-1, 1, ... |
calculate log of exp sum
args:
vec (batch_size, vanishing_dim, hidden_dim) : input tensor
m_size : hidden_dim
return:
batch_size, hidden_dim
| log_sum_exp | python | jiesutd/NCRFpp | model/crf.py | https://github.com/jiesutd/NCRFpp/blob/master/model/crf.py | Apache-2.0 |
def _calculate_PZ(self, feats, mask):
"""
input:
feats: (batch, seq_len, self.tag_size+2)
masks: (batch, seq_len)
"""
batch_size = feats.size(0)
seq_len = feats.size(1)
tag_size = feats.size(2)
# print feats.view(seq_len, tag_si... |
input:
feats: (batch, seq_len, self.tag_size+2)
masks: (batch, seq_len)
| _calculate_PZ | python | jiesutd/NCRFpp | model/crf.py | https://github.com/jiesutd/NCRFpp/blob/master/model/crf.py | Apache-2.0 |
def _viterbi_decode(self, feats, mask):
"""
input:
feats: (batch, seq_len, self.tag_size+2)
mask: (batch, seq_len)
output:
decode_idx: (batch, seq_len) decoded sequence
path_score: (batch, 1) corresponding score for each seq... |
input:
feats: (batch, seq_len, self.tag_size+2)
mask: (batch, seq_len)
output:
decode_idx: (batch, seq_len) decoded sequence
path_score: (batch, 1) corresponding score for each sequence (to be implementated)
| _viterbi_decode | python | jiesutd/NCRFpp | model/crf.py | https://github.com/jiesutd/NCRFpp/blob/master/model/crf.py | Apache-2.0 |
def _score_sentence(self, scores, mask, tags):
"""
input:
scores: variable (seq_len, batch, tag_size, tag_size)
mask: (batch, seq_len)
tags: tensor (batch, seq_len)
output:
score: sum of score for gold sequences within whol... |
input:
scores: variable (seq_len, batch, tag_size, tag_size)
mask: (batch, seq_len)
tags: tensor (batch, seq_len)
output:
score: sum of score for gold sequences within whole batch
| _score_sentence | python | jiesutd/NCRFpp | model/crf.py | https://github.com/jiesutd/NCRFpp/blob/master/model/crf.py | Apache-2.0 |
def _viterbi_decode_nbest(self, feats, mask, nbest):
"""
input:
feats: (batch, seq_len, self.tag_size+2)
mask: (batch, seq_len)
output:
decode_idx: (batch, nbest, seq_len) decoded sequence
path_score: (batch, nbest) correspo... |
input:
feats: (batch, seq_len, self.tag_size+2)
mask: (batch, seq_len)
output:
decode_idx: (batch, nbest, seq_len) decoded sequence
path_score: (batch, nbest) corresponding score for each sequence (to be implementated)
... | _viterbi_decode_nbest | python | jiesutd/NCRFpp | model/crf.py | https://github.com/jiesutd/NCRFpp/blob/master/model/crf.py | Apache-2.0 |
def forward(self, word_inputs,feature_inputs, word_seq_lengths, char_inputs, char_seq_lengths, char_seq_recover):
"""
input:
word_inputs: (batch_size, sent_len)
features: list [(batch_size, sent_len), (batch_len, sent_len),...]
word_seq_lengths: list o... |
input:
word_inputs: (batch_size, sent_len)
features: list [(batch_size, sent_len), (batch_len, sent_len),...]
word_seq_lengths: list of batch_size, (batch_size,1)
char_inputs: (batch_size*sent_len, word_length)
char_seq_lengths... | forward | python | jiesutd/NCRFpp | model/wordrep.py | https://github.com/jiesutd/NCRFpp/blob/master/model/wordrep.py | Apache-2.0 |
def forward(self, word_inputs, feature_inputs, word_seq_lengths, char_inputs, char_seq_lengths, char_seq_recover):
"""
input:
word_inputs: (batch_size, sent_len)
feature_inputs: [(batch_size, sent_len), ...] list of variables
word_seq_lengths: list of ... |
input:
word_inputs: (batch_size, sent_len)
feature_inputs: [(batch_size, sent_len), ...] list of variables
word_seq_lengths: list of batch_size, (batch_size,1)
char_inputs: (batch_size*sent_len, word_length)
char_seq_lengths: l... | forward | python | jiesutd/NCRFpp | model/wordsequence.py | https://github.com/jiesutd/NCRFpp/blob/master/model/wordsequence.py | Apache-2.0 |
def sentence_representation(self, word_inputs, feature_inputs, word_seq_lengths, char_inputs, char_seq_lengths, char_seq_recover):
"""
input:
word_inputs: (batch_size, sent_len)
feature_inputs: [(batch_size, ), ...] list of variables
word_seq_lengths: ... |
input:
word_inputs: (batch_size, sent_len)
feature_inputs: [(batch_size, ), ...] list of variables
word_seq_lengths: list of batch_size, (batch_size,1)
char_inputs: (batch_size*sent_len, word_length)
char_seq_lengths: list of w... | sentence_representation | python | jiesutd/NCRFpp | model/wordsequence.py | https://github.com/jiesutd/NCRFpp/blob/master/model/wordsequence.py | Apache-2.0 |
def save(self, output_directory, name=None):
"""
Save both alhpabet records to the given directory.
:param output_directory: Directory to save model and weights.
:param name: The alphabet saving name, optional.
:return:
"""
saving_name = name if name else self.__n... |
Save both alhpabet records to the given directory.
:param output_directory: Directory to save model and weights.
:param name: The alphabet saving name, optional.
:return:
| save | python | jiesutd/NCRFpp | utils/alphabet.py | https://github.com/jiesutd/NCRFpp/blob/master/utils/alphabet.py | Apache-2.0 |
def load(self, input_directory, name=None):
"""
Load model architecture and weights from the give directory. This allow we use old models even the structure
changes.
:param input_directory: Directory to save model and weights
:return:
"""
loading_name = name if na... |
Load model architecture and weights from the give directory. This allow we use old models even the structure
changes.
:param input_directory: Directory to save model and weights
:return:
| load | python | jiesutd/NCRFpp | utils/alphabet.py | https://github.com/jiesutd/NCRFpp/blob/master/utils/alphabet.py | Apache-2.0 |
def read_requirements(path,
strict_bounds,
conda_format=False,
filter_names=None):
"""
Read a requirements.txt file, expressed as a path relative to Catalyst root.
Returns requirements with the pinned versions as lower bounds
if `strict_... |
Read a requirements.txt file, expressed as a path relative to Catalyst root.
Returns requirements with the pinned versions as lower bounds
if `strict_bounds` is falsey.
| read_requirements | python | scrtlabs/catalyst | setup.py | https://github.com/scrtlabs/catalyst/blob/master/setup.py | Apache-2.0 |
def __init__(self, *args, **kwargs):
"""Initialize sids and other state variables.
:Arguments:
:Optional:
initialize : function
Function that is called with a single
argument at the begninning of the simulation.
handle_data : function
... | Initialize sids and other state variables.
:Arguments:
:Optional:
initialize : function
Function that is called with a single
argument at the begninning of the simulation.
handle_data : function
Function that is called with 2 argum... | __init__ | python | scrtlabs/catalyst | catalyst/algorithm.py | https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py | Apache-2.0 |
def run(self, data=None, overwrite_sim_params=True):
"""Run the algorithm.
:Arguments:
source : DataPortal
:Returns:
daily_stats : pandas.DataFrame
Daily performance metrics such as returns, alpha etc.
"""
self._assets_from_source = []
... | Run the algorithm.
:Arguments:
source : DataPortal
:Returns:
daily_stats : pandas.DataFrame
Daily performance metrics such as returns, alpha etc.
| run | python | scrtlabs/catalyst | catalyst/algorithm.py | https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py | Apache-2.0 |
def get_environment(self, field='platform'):
"""Query the execution environment.
Parameters
----------
field : {'platform', 'arena', 'data_frequency',
'start', 'end', 'capital_base', 'platform', '*'}
The field to query. The options have the following meaning... | Query the execution environment.
Parameters
----------
field : {'platform', 'arena', 'data_frequency',
'start', 'end', 'capital_base', 'platform', '*'}
The field to query. The options have the following meanings:
arena : str {'backtest', 'live'}
... | get_environment | python | scrtlabs/catalyst | catalyst/algorithm.py | https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py | Apache-2.0 |
def fetch_csv(self,
url,
pre_func=None,
post_func=None,
date_column='date',
date_format=None,
timezone=pytz.utc.zone,
symbol=None,
mask=True,
symbol_column=No... | Fetch a csv from a remote url and register the data so that it is
queryable from the ``data`` object.
Parameters
----------
url : str
The url of the csv file to load.
pre_func : callable[pd.DataFrame -> pd.DataFrame], optional
A callback to allow preproce... | fetch_csv | python | scrtlabs/catalyst | catalyst/algorithm.py | https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py | Apache-2.0 |
def schedule_function(self,
func,
date_rule=None,
time_rule=None,
half_days=True,
calendar=None):
"""Schedules a function to be called according to some timed rules.
Paramet... | Schedules a function to be called according to some timed rules.
Parameters
----------
func : callable[(context, data) -> None]
The function to execute when the rule is triggered.
date_rule : EventRule, optional
The rule for the dates to execute this function.
... | schedule_function | python | scrtlabs/catalyst | catalyst/algorithm.py | https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.