index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
5,870
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/migrations/versions/sqlite/2024_04_04_114538_8644a9595a08_add_deployment_version_to_flow_run.py
18,19
1,33
upgrade
19,30
19,30
"""add_deployment_version_to_flow_run Revision ID: 8644a9595a08 Revises: 07ed05dfd4ec Create Date: 2024-04-02 11:45:38.210743 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "8644a9595a08" down_revision = "07ed05dfd4ec" branch_labels = None depends_on = None d...
"""add_deployment_version_to_flow_run Revision ID: 8644a9595a08 Revises: 07ed05dfd4ec Create Date: 2024-04-02 11:45:38.210743 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "8644a9595a08" down_revision = "07ed05dfd4ec" branch_labels = None depends_on = None d...
op.add_column( "flow_run", sa.Column("deployment_version", sa.String(), nullable=True) ) op.create_index( op.f("ix_flow_run__deployment_version"), "flow_run", ["deployment_version"], unique=False, )
op.add_column( "flow_run", sa.Column("deployment_version", sa.String(), nullable=True) ) op.create_index( op.f("ix_flow_run__deployment_version"), "flow_run", ["deployment_version"], unique=False, )
12
229
98
327
"""add_deployment_version_to_flow_run Revision ID: 8644a9595a08 Revises: 07ed05dfd4ec Create Date: 2024-04-02 11:45:38.210743 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "8644a9595a08" down_revision = "07ed05dfd4ec" branch_labels = None depends_on = None d...
"""add_deployment_version_to_flow_run Revision ID: 8644a9595a08 Revises: 07ed05dfd4ec Create Date: 2024-04-02 11:45:38.210743 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "8644a9595a08" down_revision = "07ed05dfd4ec" branch_labels = None depends_on = None d...
5,871
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/migrations/versions/sqlite/2024_04_23_094701_75c8f17b8b51_work_status_fields.py
19,20
1,60
upgrade
20,51
20,51
"""Work status fields Revision ID: 75c8f17b8b51 Revises: 824e9edafa60 Create Date: 2024-04-23 09:47:01.931872 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "75c8f17b8b51" down_revision = "824e9edafa60" branch_labels = None depends_on = None def upgrade(): F...
"""Work status fields Revision ID: 75c8f17b8b51 Revises: 824e9edafa60 Create Date: 2024-04-23 09:47:01.931872 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "75c8f17b8b51" down_revision = "824e9edafa60" branch_labels = None depends_on = None def upgrade(): F...
with op.batch_alter_table("deployment", schema=None) as batch_op: batch_op.add_column( sa.Column( "status", sa.Enum("READY", "NOT_READY", name="deployment_status"), nullable=False, server_default="NOT_READY", ) )...
with op.batch_alter_table("deployment", schema=None) as batch_op: batch_op.add_column( sa.Column( "status", sa.Enum("READY", "NOT_READY", name="deployment_status"), nullable=False, server_default="NOT_READY", ) )...
47
282
325
607
"""Work status fields Revision ID: 75c8f17b8b51 Revises: 824e9edafa60 Create Date: 2024-04-23 09:47:01.931872 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "75c8f17b8b51" down_revision = "824e9edafa60" branch_labels = None depends_on = None def upgrade(): F...
"""Work status fields Revision ID: 75c8f17b8b51 Revises: 824e9edafa60 Create Date: 2024-04-23 09:47:01.931872 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "75c8f17b8b51" down_revision = "824e9edafa60" branch_labels = None depends_on = None def upgrade(): F...
5,872
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/database/migrations/versions/sqlite/2024_05_01_103824_20fbd53b3cef_add_catchup_fields_to_deploymentschedule.py
30,31
1,35
downgrade
31,35
31,35
"""add catchup fields to DeploymentSchedule Revision ID: 20fbd53b3cef Revises: a8e62d4c72cf Create Date: 2024-05-01 10:38:24.336255 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "20fbd53b3cef" down_revision = "a8e62d4c72cf" branch_labels = None depends_on = N...
"""add catchup fields to DeploymentSchedule Revision ID: 20fbd53b3cef Revises: a8e62d4c72cf Create Date: 2024-05-01 10:38:24.336255 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "20fbd53b3cef" down_revision = "a8e62d4c72cf" branch_labels = None depends_on = N...
with op.batch_alter_table("deployment_schedule", schema=None) as batch_op: batch_op.drop_column("catchup") batch_op.drop_column("max_scheduled_runs") batch_op.drop_column("max_active_runs")
with op.batch_alter_table("deployment_schedule", schema=None) as batch_op: batch_op.drop_column("catchup") batch_op.drop_column("max_scheduled_runs") batch_op.drop_column("max_active_runs")
8
308
78
386
"""add catchup fields to DeploymentSchedule Revision ID: 20fbd53b3cef Revises: a8e62d4c72cf Create Date: 2024-05-01 10:38:24.336255 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "20fbd53b3cef" down_revision = "a8e62d4c72cf" branch_labels = None depends_on = N...
"""add catchup fields to DeploymentSchedule Revision ID: 20fbd53b3cef Revises: a8e62d4c72cf Create Date: 2024-05-01 10:38:24.336255 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "20fbd53b3cef" down_revision = "a8e62d4c72cf" branch_labels = None depends_on = N...
5,873
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/clients.py
107,115
50,195
assert_emitted_event_with
AssertingEventsClient
116,179
115,179
class AssertingEventsClient(EventsClient): """An implementation of the Prefect Events client that records all events sent to it for inspection during tests.""" last: ClassVar[Optional["AssertingEventsClient"]] = None all: ClassVar[List["AssertingEventsClient"]] = [] args: Tuple kwargs: Dict[st...
class AssertingEventsClient(EventsClient): """An implementation of the Prefect Events client that records all events sent to it for inspection during tests.""" last: ClassVar[Optional["AssertingEventsClient"]] = None all: ClassVar[List["AssertingEventsClient"]] = [] args: Tuple kwargs: Dict[st...
assert cls.last is not None and cls.all, "No event client was created" emitted_events = [ event for client in cls.all for event in reversed(client.events) ] resource_spec = ResourceSpecification.parse_obj(resource) if resource else None related_specs = ( ...
"""Assert that an event was emitted containing the given properties.""" assert cls.last is not None and cls.all, "No event client was created" emitted_events = [ event for client in cls.all for event in reversed(client.events) ] resource_spec = ResourceSpecification...
157
791
645
1,436
import abc from textwrap import dedent from types import TracebackType from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, Union from uuid import UUID import httpx from typing_extensions import Self, TypeAlias from prefect.client.base import PrefectHttpxAsyncClient from prefect.logging import get_log...
import abc from textwrap import dedent from types import TracebackType from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, Union from uuid import UUID import httpx from typing_extensions import Self, TypeAlias from prefect.client.base import PrefectHttpxAsyncClient from prefect.logging import get_log...
5,874
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/clients.py
27,29
24,43
emit
EventsClient
29,31
29,31
class EventsClient(abc.ABC): """The abstract interface for a Prefect Events client""" @abc.abstractmethod async def emit(self, event: Event) -> Optional[Event]: FILL_FUNC_BODY async def __aenter__(self) -> Self: return self async def __aexit__( self, exc_type: Optional[Type[...
class EventsClient(abc.ABC): """The abstract interface for a Prefect Events client""" @abc.abstractmethod async def emit(self, event: Event) -> Optional[Event]: FILL_FUNC_BODY async def __aenter__(self) -> Self: return self async def __aexit__( self, exc_type: Optional[Type[...
...
...
1
139
6
145
import abc from textwrap import dedent from types import TracebackType from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, Union from uuid import UUID import httpx from typing_extensions import Self, TypeAlias from prefect.client.base import PrefectHttpxAsyncClient from prefect.logging import get_log...
import abc from textwrap import dedent from types import TracebackType from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, Union from uuid import UUID import httpx from typing_extensions import Self, TypeAlias from prefect.client.base import PrefectHttpxAsyncClient from prefect.logging import get_log...
5,875
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/clients.py
253,254
223,257
resume_automation
PrefectServerEventsAPIClient
254,257
254,257
class PrefectServerEventsAPIClient: _http_client: PrefectHttpxAsyncClient def __init__(self, additional_headers: Dict[str, str] = {}): from prefect.server.api.server import create_app # create_app caches application instances, and invoking it with no arguments # will point it to the th...
class PrefectServerEventsAPIClient: _http_client: PrefectHttpxAsyncClient def __init__(self, additional_headers: Dict[str, str] = {}): from prefect.server.api.server import create_app # create_app caches application instances, and invoking it with no arguments # will point it to the th...
return await self._http_client.patch( f"/automations/{automation_id}", json={"enabled": True} )
return await self._http_client.patch( f"/automations/{automation_id}", json={"enabled": True} )
7
361
38
399
import abc from textwrap import dedent from types import TracebackType from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, Union from uuid import UUID import httpx from typing_extensions import Self, TypeAlias from prefect.client.base import PrefectHttpxAsyncClient from prefect.logging import get_log...
import abc from textwrap import dedent from types import TracebackType from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, Union from uuid import UUID import httpx from typing_extensions import Self, TypeAlias from prefect.client.base import PrefectHttpxAsyncClient from prefect.logging import get_log...
5,876
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/clients.py
212,213
195,223
emit
PrefectServerEventsClient
213,223
213,223
class PrefectServerEventsClient(EventsClient): _publisher: messaging.EventPublisher async def __aenter__(self) -> Self: self._publisher = messaging.create_event_publisher() return self async def __aexit__( self, exc_type: Optional[Type[Exception]], exc_val: Optional...
class PrefectServerEventsClient(EventsClient): _publisher: messaging.EventPublisher async def __aenter__(self) -> Self: self._publisher = messaging.create_event_publisher() return self async def __aexit__( self, exc_type: Optional[Type[Exception]], exc_val: Optional...
if not hasattr(self, "_publisher"): raise TypeError( "Events may only be emitted while this client is being used as a " "context manager" ) received_event = event.receive() await self._publisher.publish_event(event) return received_...
if not hasattr(self, "_publisher"): raise TypeError( "Events may only be emitted while this client is being used as a " "context manager" ) received_event = event.receive() await self._publisher.publish_event(event) return received_...
30
177
91
268
import abc from textwrap import dedent from types import TracebackType from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, Union from uuid import UUID import httpx from typing_extensions import Self, TypeAlias from prefect.client.base import PrefectHttpxAsyncClient from prefect.logging import get_log...
import abc from textwrap import dedent from types import TracebackType from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, Union from uuid import UUID import httpx from typing_extensions import Self, TypeAlias from prefect.client.base import PrefectHttpxAsyncClient from prefect.logging import get_log...
5,877
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/jinja_filters.py
29,31
1,103
ui_url
37,71
31,71
import urllib.parse from typing import Any, Mapping, Optional from jinja2 import pass_context from prefect.server.schemas.core import ( Deployment, Flow, FlowRun, TaskRun, WorkPool, WorkQueue, ) from prefect.server.schemas.responses import WorkQueueWithStatus from prefect.server.utilities.sche...
import urllib.parse from typing import Any, Mapping, Optional from jinja2 import pass_context from prefect.server.schemas.core import ( Deployment, Flow, FlowRun, TaskRun, WorkPool, WorkQueue, ) from prefect.server.schemas.responses import WorkQueueWithStatus from prefect.server.utilities.sche...
from prefect.server.events.schemas.automations import Automation from prefect.server.events.schemas.events import ReceivedEvent, Resource url = None url_formats = { "prefect.deployment": "deployments/deployment/{id}", "prefect.flow": "flows/flow/{id}", "prefect.flow-run": "flow...
"""Return the UI URL for the given object. Supports Automation, Resource, Deployment, Flow, FlowRun, TaskRun, and WorkQueue objects. Within a Resource, deployment, flow, flow-run, task-run, and work-queue are supported. If the given object is of a different type or an unsupported Resource `None` is...
81
751
470
1,221
import urllib.parse from typing import Any, Mapping, Optional from jinja2 import pass_context from prefect.server.schemas.core import ( Deployment, Flow, FlowRun, TaskRun, WorkPool, WorkQueue, ) from prefect.server.schemas.responses import WorkQueueWithStatus from prefect.server.utilities.sche...
import urllib.parse from typing import Any, Mapping, Optional from jinja2 import pass_context from prefect.server.schemas.core import ( Deployment, Flow, FlowRun, TaskRun, WorkPool, WorkQueue, ) from prefect.server.schemas.responses import WorkQueueWithStatus from prefect.server.utilities.sche...
5,878
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/messaging.py
11,12
1,68
publish
13,18
12,18
from typing import Iterable from prefect.logging import get_logger from prefect.server.events.schemas.events import ReceivedEvent from prefect.server.utilities.messaging import Publisher, create_publisher from prefect.settings import PREFECT_EVENTS_MAXIMUM_SIZE_BYTES logger = get_logger(__name__) async def publish(...
from typing import Iterable from prefect.logging import get_logger from prefect.server.events.schemas.events import ReceivedEvent from prefect.server.utilities.messaging import Publisher, create_publisher from prefect.settings import PREFECT_EVENTS_MAXIMUM_SIZE_BYTES logger = get_logger(__name__) async def publish(...
async with create_event_publisher() as publisher: for event in events: await publisher.publish_event(event)
"""Send the given events as a batch via the default publisher""" async with create_event_publisher() as publisher: for event in events: await publisher.publish_event(event)
11
544
40
584
from typing import Iterable from prefect.logging import get_logger from prefect.server.events.schemas.events import ReceivedEvent from prefect.server.utilities.messaging import Publisher, create_publisher from prefect.settings import PREFECT_EVENTS_MAXIMUM_SIZE_BYTES logger = get_logger(__name__) async def publish(...
from typing import Iterable from prefect.logging import get_logger from prefect.server.events.schemas.events import ReceivedEvent from prefect.server.utilities.messaging import Publisher, create_publisher from prefect.settings import PREFECT_EVENTS_MAXIMUM_SIZE_BYTES logger = get_logger(__name__) async def publish(...
5,879
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/messaging.py
34,35
18,61
publish_event
EventPublisher
41,61
35,61
class EventPublisher(Publisher): _publisher: Publisher def __init__(self, publisher: Publisher = None): self._publisher = publisher async def __aenter__(self): await self._publisher.__aenter__() return self async def __aexit__(self, *args): await self._publisher.__aexi...
class EventPublisher(Publisher): _publisher: Publisher def __init__(self, publisher: Publisher = None): self._publisher = publisher async def __aenter__(self): await self._publisher.__aenter__() return self async def __aexit__(self, *args): await self._publisher.__aexi...
encoded = event.json().encode() if len(encoded) > PREFECT_EVENTS_MAXIMUM_SIZE_BYTES.value(): logger.warning( "Refusing to publish event of size %s", extra={ "event_id": str(event.id), "event": event.event[:100], ...
""" Publishes the given events Args: event: the event to publish """ encoded = event.json().encode() if len(encoded) > PREFECT_EVENTS_MAXIMUM_SIZE_BYTES.value(): logger.warning( "Refusing to publish event of size %s", ...
35
187
172
359
from typing import Iterable from prefect.logging import get_logger from prefect.server.events.schemas.events import ReceivedEvent from prefect.server.utilities.messaging import Publisher, create_publisher from prefect.settings import PREFECT_EVENTS_MAXIMUM_SIZE_BYTES logger = get_logger(__name__) async def publish(...
from typing import Iterable from prefect.logging import get_logger from prefect.server.events.schemas.events import ReceivedEvent from prefect.server.utilities.messaging import Publisher, create_publisher from prefect.settings import PREFECT_EVENTS_MAXIMUM_SIZE_BYTES logger = get_logger(__name__) async def publish(...
5,880
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/models/composite_trigger_child_firing.py
84,91
1,114
clear_old_child_firings
91,100
91,100
from typing import TYPE_CHECKING, Sequence from uuid import UUID import pendulum import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.ext.asyncio import AsyncSession from prefect.server.database.dependencies import db_injector from prefect.server.database.interface import PrefectDBInterf...
from typing import TYPE_CHECKING, Sequence from uuid import UUID import pendulum import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.ext.asyncio import AsyncSession from prefect.server.database.dependencies import db_injector from prefect.server.database.interface import PrefectDBInterf...
await session.execute( sa.delete(db.CompositeTriggerChildFiring).filter( db.CompositeTriggerChildFiring.automation_id == trigger.automation.id, db.CompositeTriggerChildFiring.parent_trigger_id == trigger.id, db.CompositeTriggerChildFiring.child_fired_at < fired_before, ...
await session.execute( sa.delete(db.CompositeTriggerChildFiring).filter( db.CompositeTriggerChildFiring.automation_id == trigger.automation.id, db.CompositeTriggerChildFiring.parent_trigger_id == trigger.id, db.CompositeTriggerChildFiring.child_fired_at < fired_before, ...
14
1,045
111
1,156
from typing import TYPE_CHECKING, Sequence from uuid import UUID import pendulum import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.ext.asyncio import AsyncSession from prefect.server.database.dependencies import db_injector from prefect.server.database.interface import PrefectDBInterf...
from typing import TYPE_CHECKING, Sequence from uuid import UUID import pendulum import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.ext.asyncio import AsyncSession from prefect.server.database.dependencies import db_injector from prefect.server.database.interface import PrefectDBInterf...
5,881
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/schemas/labelling.py
105,106
74,107
has_all_labels
Labelled
106,107
106,107
class Labelled(PrefectBaseModel, extra="ignore"): """An object defined by string labels and values""" __root__: Dict[str, str] def keys(self) -> Iterable[str]: return self.__root__.keys() def items(self) -> Iterable[Tuple[str, str]]: return self.__root__.items() def __getitem__(s...
class Labelled(PrefectBaseModel, extra="ignore"): """An object defined by string labels and values""" __root__: Dict[str, str] def keys(self) -> Iterable[str]: return self.__root__.keys() def items(self) -> Iterable[Tuple[str, str]]: return self.__root__.items() def __getitem__(s...
return all(self.__root__.get(label) == value for label, value in labels.items())
return all(self.__root__.get(label) == value for label, value in labels.items())
9
344
26
370
from typing import Dict, Iterable, Iterator, List, Optional, Tuple from prefect.server.utilities.schemas import PrefectBaseModel class LabelDiver: """The LabelDiver supports templating use cases for any Labelled object, by presenting the labels as a graph of objects that may be accessed by attribute. For ...
from typing import Dict, Iterable, Iterator, List, Optional, Tuple from prefect.server.utilities.schemas import PrefectBaseModel class LabelDiver: """The LabelDiver supports templating use cases for any Labelled object, by presenting the labels as a graph of objects that may be accessed by attribute. For ...
5,882
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/services/actions.py
18,19
11,41
start
Actions
19,31
19,31
class Actions: """Runs actions triggered by Automatinos""" name: str = "Actions" consumer_task: Optional[asyncio.Task] = None async def start(self): FILL_FUNC_BODY async def stop(self): assert self.consumer_task is not None, "Actions not started" self.consumer_task.cancel() ...
class Actions: """Runs actions triggered by Automatinos""" name: str = "Actions" consumer_task: Optional[asyncio.Task] = None async def start(self): FILL_FUNC_BODY async def stop(self): assert self.consumer_task is not None, "Actions not started" self.consumer_task.cancel() ...
assert self.consumer_task is None, "Actions already started" self.consumer = create_consumer("actions") async with actions.consumer() as handler: self.consumer_task = asyncio.create_task(self.consumer.run(handler)) logger.debug("Actions started") try: ...
assert self.consumer_task is None, "Actions already started" self.consumer = create_consumer("actions") async with actions.consumer() as handler: self.consumer_task = asyncio.create_task(self.consumer.run(handler)) logger.debug("Actions started") try: ...
26
149
119
268
import asyncio from typing import Optional from prefect.logging import get_logger from prefect.server.events import actions from prefect.server.utilities.messaging import create_consumer logger = get_logger(__name__) class Actions: """Runs actions triggered by Automatinos""" name: str = "Actions" cons...
import asyncio from typing import Optional from prefect.logging import get_logger from prefect.server.events import actions from prefect.server.utilities.messaging import create_consumer logger = get_logger(__name__) class Actions: """Runs actions triggered by Automatinos""" name: str = "Actions" cons...
5,883
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/services/triggers.py
55,56
45,57
run_once
ProactiveTriggers
56,57
56,57
class ProactiveTriggers(LoopService): def __init__(self, loop_seconds: float = None, **kwargs): super().__init__( loop_seconds=( loop_seconds or PREFECT_EVENTS_PROACTIVE_GRANULARITY.value().total_seconds() ), **kwargs, ) async ...
class ProactiveTriggers(LoopService): def __init__(self, loop_seconds: float = None, **kwargs): super().__init__( loop_seconds=( loop_seconds or PREFECT_EVENTS_PROACTIVE_GRANULARITY.value().total_seconds() ), **kwargs, ) async ...
await triggers.evaluate_proactive_triggers()
await triggers.evaluate_proactive_triggers()
2
107
16
123
import asyncio from typing import Optional from prefect.logging import get_logger from prefect.server.events import triggers from prefect.server.services.loop_service import LoopService from prefect.server.utilities.messaging import create_consumer from prefect.settings import PREFECT_EVENTS_PROACTIVE_GRANULARITY log...
import asyncio from typing import Optional from prefect.logging import get_logger from prefect.server.events import triggers from prefect.server.services.loop_service import LoopService from prefect.server.utilities.messaging import create_consumer from prefect.settings import PREFECT_EVENTS_PROACTIVE_GRANULARITY log...
5,884
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/services/triggers.py
33,34
13,45
stop
ReactiveTriggers
34,45
34,45
class ReactiveTriggers: """Runs the reactive triggers consumer""" name: str = "ReactiveTriggers" consumer_task: Optional[asyncio.Task] = None async def start(self): assert self.consumer_task is None, "Reactive triggers already started" self.consumer = create_consumer("events") ...
class ReactiveTriggers: """Runs the reactive triggers consumer""" name: str = "ReactiveTriggers" consumer_task: Optional[asyncio.Task] = None async def start(self): assert self.consumer_task is None, "Reactive triggers already started" self.consumer = create_consumer("events") ...
assert self.consumer_task is not None, "Reactive triggers not started" self.consumer_task.cancel() try: await self.consumer_task except asyncio.CancelledError: pass finally: self.consumer_task = None logger.debug("Reactive triggers stop...
assert self.consumer_task is not None, "Reactive triggers not started" self.consumer_task.cancel() try: await self.consumer_task except asyncio.CancelledError: pass finally: self.consumer_task = None logger.debug("Reactive triggers stop...
23
187
96
283
import asyncio from typing import Optional from prefect.logging import get_logger from prefect.server.events import triggers from prefect.server.services.loop_service import LoopService from prefect.server.utilities.messaging import create_consumer from prefect.settings import PREFECT_EVENTS_PROACTIVE_GRANULARITY log...
import asyncio from typing import Optional from prefect.logging import get_logger from prefect.server.events import triggers from prefect.server.services.loop_service import LoopService from prefect.server.utilities.messaging import create_consumer from prefect.settings import PREFECT_EVENTS_PROACTIVE_GRANULARITY log...
5,885
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/stream.py
127,128
1,139
run_distributor
129,139
128,139
import asyncio from asyncio import Queue from contextlib import asynccontextmanager from typing import AsyncGenerator, AsyncIterable, Dict, Set from prefect.logging import get_logger from prefect.server.events.filters import EventFilter from prefect.server.events.schemas.events import ReceivedEvent from prefect.server...
import asyncio from asyncio import Queue from contextlib import asynccontextmanager from typing import AsyncGenerator, AsyncIterable, Dict, Set from prefect.logging import get_logger from prefect.server.events.filters import EventFilter from prefect.server.events.schemas.events import ReceivedEvent from prefect.server...
global _distributor_started async with messaging.ephemeral_subscription( topic="events", ) as create_consumer_kwargs: started.set() async with distributor() as handler: consumer = messaging.create_consumer(**create_consumer_kwargs) await consumer.run( ...
"""Runs the distributor consumer forever until it is cancelled""" global _distributor_started async with messaging.ephemeral_subscription( topic="events", ) as create_consumer_kwargs: started.set() async with distributor() as handler: consumer = messaging.create_consu...
22
1,003
105
1,108
import asyncio from asyncio import Queue from contextlib import asynccontextmanager from typing import AsyncGenerator, AsyncIterable, Dict, Set from prefect.logging import get_logger from prefect.server.events.filters import EventFilter from prefect.server.events.schemas.events import ReceivedEvent from prefect.server...
import asyncio from asyncio import Queue from contextlib import asynccontextmanager from typing import AsyncGenerator, AsyncIterable, Dict, Set from prefect.logging import get_logger from prefect.server.events.filters import EventFilter from prefect.server.events.schemas.events import ReceivedEvent from prefect.server...
5,886
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/events/stream.py
120,121
117,127
start
Distributor
121,123
121,123
class Distributor: name: str = "Distributor" async def start(self): FILL_FUNC_BODY async def stop(self): await stop_distributor()
class Distributor: name: str = "Distributor" async def start(self): FILL_FUNC_BODY async def stop(self): await stop_distributor()
await start_distributor()
await start_distributor()
2
55
12
67
import asyncio from asyncio import Queue from contextlib import asynccontextmanager from typing import AsyncGenerator, AsyncIterable, Dict, Set from prefect.logging import get_logger from prefect.server.events.filters import EventFilter from prefect.server.events.schemas.events import ReceivedEvent from prefect.server...
import asyncio from asyncio import Queue from contextlib import asynccontextmanager from typing import AsyncGenerator, AsyncIterable, Dict, Set from prefect.logging import get_logger from prefect.server.events.filters import EventFilter from prefect.server.events.schemas.events import ReceivedEvent from prefect.server...
5,887
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/models/agents.py
96,103
1,187
update_agent
114,126
103,126
""" Functions for interacting with agent ORM objects. Intended for internal use by the Prefect REST API. """ from typing import Union from uuid import UUID import pendulum import sqlalchemy as sa from sqlalchemy import delete, select from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as sc...
""" Functions for interacting with agent ORM objects. Intended for internal use by the Prefect REST API. """ from typing import Union from uuid import UUID import pendulum import sqlalchemy as sa from sqlalchemy import delete, select from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as sc...
update_stmt = ( sa.update(db.Agent) .where(db.Agent.id == agent_id) # exclude_unset=True allows us to only update values provided by # the user, ignoring any defaults on the model .values(**agent.dict(shallow=True, exclude_unset=True)) ) result = await session.execut...
""" Update a Agent by id. Args: session (AsyncSession): A database session agent: the work queue data agent_id (str): a Agent id Returns: bool: whether or not the Agent was deleted """ update_stmt = ( sa.update(db.Agent) .where(db.Agent.id == ag...
37
1,250
124
1,374
""" Functions for interacting with agent ORM objects. Intended for internal use by the Prefect REST API. """ from typing import Union from uuid import UUID import pendulum import sqlalchemy as sa from sqlalchemy import delete, select from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as sc...
""" Functions for interacting with agent ORM objects. Intended for internal use by the Prefect REST API. """ from typing import Union from uuid import UUID import pendulum import sqlalchemy as sa from sqlalchemy import delete, select from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as sc...
5,888
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/models/block_types.py
110,119
1,195
read_block_types
127,149
119,149
""" Functions for interacting with block type ORM objects. Intended for internal use by the Prefect REST API. """ import html from typing import TYPE_CHECKING, Optional from uuid import UUID import sqlalchemy as sa from prefect.server import schemas from prefect.server.database.dependencies import inject_db from pre...
""" Functions for interacting with block type ORM objects. Intended for internal use by the Prefect REST API. """ import html from typing import TYPE_CHECKING, Optional from uuid import UUID import sqlalchemy as sa from prefect.server import schemas from prefect.server.database.dependencies import inject_db from pre...
query = sa.select(db.BlockType).order_by(db.BlockType.name) if block_type_filter is not None: query = query.where(block_type_filter.as_sql_filter(db)) if block_schema_filter is not None: exists_clause = sa.select(db.BlockSchema).where( db.BlockSchema.block_type_id == db.BlockTy...
""" Reads block types with an optional limit and offset Args: Returns: List[db.BlockType]: List of """ query = sa.select(db.BlockType).order_by(db.BlockType.name) if block_type_filter is not None: query = query.where(block_type_filter.as_sql_filter(db)) if block_schem...
49
1,362
230
1,592
""" Functions for interacting with block type ORM objects. Intended for internal use by the Prefect REST API. """ import html from typing import TYPE_CHECKING, Optional from uuid import UUID import sqlalchemy as sa from prefect.server import schemas from prefect.server.database.dependencies import inject_db from pre...
""" Functions for interacting with block type ORM objects. Intended for internal use by the Prefect REST API. """ import html from typing import TYPE_CHECKING, Optional from uuid import UUID import sqlalchemy as sa from prefect.server import schemas from prefect.server.database.dependencies import inject_db from pre...
5,889
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/models/concurrency_limits.py
92,99
1,190
reset_concurrency_limit_by_tag
102,113
99,113
""" Functions for interacting with concurrency limit ORM objects. Intended for internal use by the Prefect REST API. """ from typing import List, Optional from uuid import UUID import pendulum import sqlalchemy as sa import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db ...
""" Functions for interacting with concurrency limit ORM objects. Intended for internal use by the Prefect REST API. """ from typing import List, Optional from uuid import UUID import pendulum import sqlalchemy as sa import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db ...
query = sa.select(db.ConcurrencyLimit).where(db.ConcurrencyLimit.tag == tag) result = await session.execute(query) concurrency_limit = result.scalar() if concurrency_limit: if slot_override is not None: concurrency_limit.active_slots = [str(slot) for slot in slot_override] el...
""" Resets a concurrency limit by tag. """ query = sa.select(db.ConcurrencyLimit).where(db.ConcurrencyLimit.tag == tag) result = await session.execute(query) concurrency_limit = result.scalar() if concurrency_limit: if slot_override is not None: concurrency_limit.active_s...
32
1,505
131
1,636
""" Functions for interacting with concurrency limit ORM objects. Intended for internal use by the Prefect REST API. """ from typing import List, Optional from uuid import UUID import pendulum import sqlalchemy as sa import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db ...
""" Functions for interacting with concurrency limit ORM objects. Intended for internal use by the Prefect REST API. """ from typing import List, Optional from uuid import UUID import pendulum import sqlalchemy as sa import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db ...
5,890
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/models/configuration.py
10,16
1,47
write_configuration
16,37
16,37
from typing import Optional import sqlalchemy as sa from prefect.server import schemas from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBInterface @inject_db async def write_configuration( session: sa.orm.Session, configuration: schemas.core.Co...
from typing import Optional import sqlalchemy as sa from prefect.server import schemas from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBInterface @inject_db async def write_configuration( session: sa.orm.Session, configuration: schemas.core.Co...
# first see if the key already exists query = sa.select(db.Configuration).where(db.Configuration.key == configuration.key) result = await session.execute(query) # type: ignore existing_configuration = result.scalar() # if it exists, update its value if existing_configuration: existing_c...
# first see if the key already exists query = sa.select(db.Configuration).where(db.Configuration.key == configuration.key) result = await session.execute(query) # type: ignore existing_configuration = result.scalar() # if it exists, update its value if existing_configuration: existing_c...
66
213
213
426
from typing import Optional import sqlalchemy as sa from prefect.server import schemas from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBInterface @inject_db async def write_configuration( session: sa.orm.Session, configuration: schemas.core.Co...
from typing import Optional import sqlalchemy as sa from prefect.server import schemas from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBInterface @inject_db async def write_configuration( session: sa.orm.Session, configuration: schemas.core.Co...
5,891
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/models/flow_run_input.py
53,60
1,91
read_flow_run_input
60,75
60,75
import uuid from typing import List, Optional import sqlalchemy as sa from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBInterface @inject_db async def create_flow_...
import uuid from typing import List, Optional import sqlalchemy as sa from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBInterface @inject_db async def create_flow_...
query = sa.select(db.FlowRunInput).where( sa.and_( db.FlowRunInput.flow_run_id == flow_run_id, db.FlowRunInput.key == key, ) ) result = await session.execute(query) model = result.scalar() if model: return schemas.core.FlowRunInput.from_orm(model) ...
query = sa.select(db.FlowRunInput).where( sa.and_( db.FlowRunInput.flow_run_id == flow_run_id, db.FlowRunInput.key == key, ) ) result = await session.execute(query) model = result.scalar() if model: return schemas.core.FlowRunInput.from_orm(model) ...
25
656
126
782
import uuid from typing import List, Optional import sqlalchemy as sa from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBInterface @inject_db async def create_flow_...
import uuid from typing import List, Optional import sqlalchemy as sa from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBInterface @inject_db async def create_flow_...
5,892
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/models/flow_run_notification_policies.py
74,82
1,175
read_flow_run_notification_policies
93,110
82,110
""" Functions for interacting with flow run notification policy ORM objects. Intended for internal use by the Prefect REST API. """ import textwrap from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select import prefect.server.schemas as schemas from prefect.server.database.dependencies im...
""" Functions for interacting with flow run notification policy ORM objects. Intended for internal use by the Prefect REST API. """ import textwrap from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select import prefect.server.schemas as schemas from prefect.server.database.dependencies im...
query = select(db.FlowRunNotificationPolicy).order_by( db.FlowRunNotificationPolicy.id ) if flow_run_notification_policy_filter: query = query.where(flow_run_notification_policy_filter.as_sql_filter(db)) if offset is not None: query = query.offset(offset) if limit is not N...
""" Read notification policies. Args: session (sa.orm.Session): A database session offset (int): Query offset limit(int): Query limit Returns: List[db.FlowRunNotificationPolicy]: Notification policies """ query = select(db.FlowRunNotificationPolicy).order_by( ...
32
1,346
153
1,499
""" Functions for interacting with flow run notification policy ORM objects. Intended for internal use by the Prefect REST API. """ import textwrap from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select import prefect.server.schemas as schemas from prefect.server.database.dependencies im...
""" Functions for interacting with flow run notification policy ORM objects. Intended for internal use by the Prefect REST API. """ import textwrap from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select import prefect.server.schemas as schemas from prefect.server.database.dependencies im...
5,893
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/models/flow_run_states.py
33,37
1,76
read_flow_run_states
47,57
37,57
""" Functions for interacting with flow run state ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBI...
""" Functions for interacting with flow run state ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBI...
query = ( select(db.FlowRunState) .filter_by(flow_run_id=flow_run_id) .order_by(db.FlowRunState.timestamp) ) result = await session.execute(query) return result.scalars().unique().all()
""" Reads flow runs states for a flow run. Args: session: A database session flow_run_id: the flow run id Returns: List[db.FlowRunState]: the flow run states """ query = ( select(db.FlowRunState) .filter_by(flow_run_id=flow_run_id) .order_by(db....
13
497
88
585
""" Functions for interacting with flow run state ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBI...
""" Functions for interacting with flow run state ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBI...
5,894
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/models/logs.py
48,57
1,78
read_logs
71,78
57,78
""" Functions for interacting with log ORM objects. Intended for internal use by the Prefect REST API. """ from typing import List from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from pre...
""" Functions for interacting with log ORM objects. Intended for internal use by the Prefect REST API. """ from typing import List from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from pre...
query = select(db.Log).order_by(sort.as_sql_sort(db)).offset(offset).limit(limit) if log_filter: query = query.where(log_filter.as_sql_filter(db)) result = await session.execute(query) return result.scalars().unique().all()
""" Read logs. Args: session: a database session db: the database interface log_filter: only select logs that match these filters offset: Query offset limit: Query limit sort: Query sort Returns: List[db.Log]: the matching logs """ query ...
14
583
91
674
""" Functions for interacting with log ORM objects. Intended for internal use by the Prefect REST API. """ from typing import List from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from pre...
""" Functions for interacting with log ORM objects. Intended for internal use by the Prefect REST API. """ from typing import List from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from pre...
5,895
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/models/saved_searches.py
128,132
1,147
delete_saved_search
142,147
132,147
""" Functions for interacting with saved search ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from prefect.serv...
""" Functions for interacting with saved search ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from prefect.serv...
result = await session.execute( delete(db.SavedSearch).where(db.SavedSearch.id == saved_search_id) ) return result.rowcount > 0
""" Delete a SavedSearch by id. Args: session (sa.orm.Session): A database session saved_search_id (str): a SavedSearch id Returns: bool: whether or not the SavedSearch was deleted """ result = await session.execute( delete(db.SavedSearch).where(db.SavedSearch....
12
1,078
53
1,131
""" Functions for interacting with saved search ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from prefect.serv...
""" Functions for interacting with saved search ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select import prefect.server.schemas as schemas from prefect.server.database.dependencies import inject_db from prefect.serv...
5,896
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/models/task_run_states.py
33,37
1,76
read_task_run_states
47,57
37,57
""" Functions for interacting with task run state ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBI...
""" Functions for interacting with task run state ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBI...
query = ( select(db.TaskRunState) .filter_by(task_run_id=task_run_id) .order_by(db.TaskRunState.timestamp) ) result = await session.execute(query) return result.scalars().unique().all()
""" Reads task runs states for a task run. Args: session: A database session task_run_id: the task run id Returns: List[db.TaskRunState]: the task run states """ query = ( select(db.TaskRunState) .filter_by(task_run_id=task_run_id) .order_by(db....
13
497
88
585
""" Functions for interacting with task run state ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBI...
""" Functions for interacting with task run state ORM objects. Intended for internal use by the Prefect REST API. """ from uuid import UUID import sqlalchemy as sa from sqlalchemy import delete, select from prefect.server.database.dependencies import inject_db from prefect.server.database.interface import PrefectDBI...
5,897
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/orchestration/dependencies.py
36,37
1,124
provide_task_orchestration_parameters
37,47
37,47
""" Injected orchestration dependencies """ from contextlib import contextmanager ORCHESTRATION_DEPENDENCIES = { "task_policy_provider": None, "flow_policy_provider": None, "task_orchestration_parameters_provider": None, "flow_orchestration_parameters_provider": None, } async def provide_task_policy(...
""" Injected orchestration dependencies """ from contextlib import contextmanager ORCHESTRATION_DEPENDENCIES = { "task_policy_provider": None, "flow_policy_provider": None, "task_orchestration_parameters_provider": None, "flow_orchestration_parameters_provider": None, } async def provide_task_policy(...
parameter_provider = ORCHESTRATION_DEPENDENCIES.get( "task_orchestration_parameters_provider" ) if parameter_provider is None: return dict() return await parameter_provider()
parameter_provider = ORCHESTRATION_DEPENDENCIES.get( "task_orchestration_parameters_provider" ) if parameter_provider is None: return dict() return await parameter_provider()
14
981
74
1,055
""" Injected orchestration dependencies """ from contextlib import contextmanager ORCHESTRATION_DEPENDENCIES = { "task_policy_provider": None, "flow_policy_provider": None, "task_orchestration_parameters_provider": None, "flow_orchestration_parameters_provider": None, } async def provide_task_policy(...
""" Injected orchestration dependencies """ from contextlib import contextmanager ORCHESTRATION_DEPENDENCIES = { "task_policy_provider": None, "flow_policy_provider": None, "task_orchestration_parameters_provider": None, "flow_orchestration_parameters_provider": None, } async def provide_task_policy(...
5,898
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/orchestration/policies.py
36,38
18,47
compile_transition_rules
BaseOrchestrationPolicy
41,47
38,47
class BaseOrchestrationPolicy(ABC): """ An abstract base class used to organize orchestration rules in priority order. Different collections of orchestration rules might be used to govern various kinds of transitions. For example, flow-run states and task-run states might require different orchestr...
class BaseOrchestrationPolicy(ABC): """ An abstract base class used to organize orchestration rules in priority order. Different collections of orchestration rules might be used to govern various kinds of transitions. For example, flow-run states and task-run states might require different orchestr...
transition_rules = [] for rule in cls.priority(): if from_state in rule.FROM_STATES and to_state in rule.TO_STATES: transition_rules.append(rule) return transition_rules
""" Returns rules in policy that are valid for the specified state transition. """ transition_rules = [] for rule in cls.priority(): if from_state in rule.FROM_STATES and to_state in rule.TO_STATES: transition_rules.append(rule) return transit...
18
184
66
250
""" Policies are collections of orchestration rules and transforms. Prefect implements (most) orchestration with logic that governs a Prefect flow or task changing state. Policies organize of orchestration logic both to provide an ordering mechanism as well as provide observability into the orchestration process. Whi...
""" Policies are collections of orchestration rules and transforms. Prefect implements (most) orchestration with logic that governs a Prefect flow or task changing state. Policies organize of orchestration logic both to provide an ordering mechanism as well as provide observability into the orchestration process. Whi...
5,899
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/sorting.py
164,165
155,176
as_sql_sort
ArtifactCollectionSort
166,176
165,176
class ArtifactCollectionSort(AutoEnum): """Defines artifact collection sorting options.""" CREATED_DESC = AutoEnum.auto() UPDATED_DESC = AutoEnum.auto() ID_DESC = AutoEnum.auto() KEY_DESC = AutoEnum.auto() KEY_ASC = AutoEnum.auto() def as_sql_sort(self, db: "PrefectDBInterface") -> "Column...
class ArtifactCollectionSort(AutoEnum): """Defines artifact collection sorting options.""" CREATED_DESC = AutoEnum.auto() UPDATED_DESC = AutoEnum.auto() ID_DESC = AutoEnum.auto() KEY_DESC = AutoEnum.auto() KEY_ASC = AutoEnum.auto() def as_sql_sort(self, db: "PrefectDBInterface") -> "Column...
sort_mapping = { "CREATED_DESC": db.ArtifactCollection.created.desc(), "UPDATED_DESC": db.ArtifactCollection.updated.desc(), "ID_DESC": db.ArtifactCollection.id.desc(), "KEY_DESC": db.ArtifactCollection.key.desc(), "KEY_ASC": db.ArtifactCollection.key....
"""Return an expression used to sort artifact collections""" sort_mapping = { "CREATED_DESC": db.ArtifactCollection.created.desc(), "UPDATED_DESC": db.ArtifactCollection.updated.desc(), "ID_DESC": db.ArtifactCollection.id.desc(), "KEY_DESC": db.ArtifactCol...
16
133
126
259
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
5,900
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/sorting.py
143,144
134,155
as_sql_sort
ArtifactSort
145,155
144,155
class ArtifactSort(AutoEnum): """Defines artifact sorting options.""" CREATED_DESC = AutoEnum.auto() UPDATED_DESC = AutoEnum.auto() ID_DESC = AutoEnum.auto() KEY_DESC = AutoEnum.auto() KEY_ASC = AutoEnum.auto() def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": FILL_FUNC_B...
class ArtifactSort(AutoEnum): """Defines artifact sorting options.""" CREATED_DESC = AutoEnum.auto() UPDATED_DESC = AutoEnum.auto() ID_DESC = AutoEnum.auto() KEY_DESC = AutoEnum.auto() KEY_ASC = AutoEnum.auto() def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": """...
sort_mapping = { "CREATED_DESC": db.Artifact.created.desc(), "UPDATED_DESC": db.Artifact.updated.desc(), "ID_DESC": db.Artifact.id.desc(), "KEY_DESC": db.Artifact.key.desc(), "KEY_ASC": db.Artifact.key.asc(), } return sort_mapping[self....
"""Return an expression used to sort artifacts""" sort_mapping = { "CREATED_DESC": db.Artifact.created.desc(), "UPDATED_DESC": db.Artifact.updated.desc(), "ID_DESC": db.Artifact.id.desc(), "KEY_DESC": db.Artifact.key.desc(), "KEY_ASC": db.Artif...
16
131
121
252
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
5,901
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/sorting.py
202,203
195,210
as_sql_sort
BlockDocumentSort
204,210
203,210
class BlockDocumentSort(AutoEnum): """Defines block document sorting options.""" NAME_DESC = "NAME_DESC" NAME_ASC = "NAME_ASC" BLOCK_TYPE_AND_NAME_ASC = "BLOCK_TYPE_AND_NAME_ASC" def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": FILL_FUNC_BODY
class BlockDocumentSort(AutoEnum): """Defines block document sorting options.""" NAME_DESC = "NAME_DESC" NAME_ASC = "NAME_ASC" BLOCK_TYPE_AND_NAME_ASC = "BLOCK_TYPE_AND_NAME_ASC" def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": """Return an expression used to sort block ...
sort_mapping = { "NAME_DESC": db.BlockDocument.name.desc(), "NAME_ASC": db.BlockDocument.name.asc(), "BLOCK_TYPE_AND_NAME_ASC": sa.text("block_type_name asc, name asc"), } return sort_mapping[self.value]
"""Return an expression used to sort block documents""" sort_mapping = { "NAME_DESC": db.BlockDocument.name.desc(), "NAME_ASC": db.BlockDocument.name.asc(), "BLOCK_TYPE_AND_NAME_ASC": sa.text("block_type_name asc, name asc"), } return sort_mapping[self...
15
122
90
212
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
5,902
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/sorting.py
123,124
115,134
as_sql_sort
DeploymentSort
125,134
124,134
class DeploymentSort(AutoEnum): """Defines deployment sorting options.""" CREATED_DESC = AutoEnum.auto() UPDATED_DESC = AutoEnum.auto() NAME_ASC = AutoEnum.auto() NAME_DESC = AutoEnum.auto() def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": FILL_FUNC_BODY
class DeploymentSort(AutoEnum): """Defines deployment sorting options.""" CREATED_DESC = AutoEnum.auto() UPDATED_DESC = AutoEnum.auto() NAME_ASC = AutoEnum.auto() NAME_DESC = AutoEnum.auto() def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": """Return an expression use...
sort_mapping = { "CREATED_DESC": db.Deployment.created.desc(), "UPDATED_DESC": db.Deployment.updated.desc(), "NAME_ASC": db.Deployment.name.asc(), "NAME_DESC": db.Deployment.name.desc(), } return sort_mapping[self.value]
"""Return an expression used to sort deployments""" sort_mapping = { "CREATED_DESC": db.Deployment.created.desc(), "UPDATED_DESC": db.Deployment.updated.desc(), "NAME_ASC": db.Deployment.name.asc(), "NAME_DESC": db.Deployment.name.desc(), } ...
14
119
103
222
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
5,903
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/sorting.py
34,35
21,56
as_sql_sort
FlowRunSort
35,56
35,56
class FlowRunSort(AutoEnum): """Defines flow run sorting options.""" ID_DESC = AutoEnum.auto() START_TIME_ASC = AutoEnum.auto() START_TIME_DESC = AutoEnum.auto() EXPECTED_START_TIME_ASC = AutoEnum.auto() EXPECTED_START_TIME_DESC = AutoEnum.auto() NAME_ASC = AutoEnum.auto() NAME_DESC = A...
class FlowRunSort(AutoEnum): """Defines flow run sorting options.""" ID_DESC = AutoEnum.auto() START_TIME_ASC = AutoEnum.auto() START_TIME_DESC = AutoEnum.auto() EXPECTED_START_TIME_ASC = AutoEnum.auto() EXPECTED_START_TIME_DESC = AutoEnum.auto() NAME_ASC = AutoEnum.auto() NAME_DESC = A...
from sqlalchemy.sql.functions import coalesce """Return an expression used to sort flow runs""" sort_mapping = { "ID_DESC": db.FlowRun.id.desc(), "START_TIME_ASC": coalesce( db.FlowRun.start_time, db.FlowRun.expected_start_time ).asc(), ...
from sqlalchemy.sql.functions import coalesce """Return an expression used to sort flow runs""" sort_mapping = { "ID_DESC": db.FlowRun.id.desc(), "START_TIME_ASC": coalesce( db.FlowRun.start_time, db.FlowRun.expected_start_time ).asc(), ...
42
192
313
505
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
5,904
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/sorting.py
104,105
96,115
as_sql_sort
FlowSort
106,115
105,115
class FlowSort(AutoEnum): """Defines flow sorting options.""" CREATED_DESC = AutoEnum.auto() UPDATED_DESC = AutoEnum.auto() NAME_ASC = AutoEnum.auto() NAME_DESC = AutoEnum.auto() def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": FILL_FUNC_BODY
class FlowSort(AutoEnum): """Defines flow sorting options.""" CREATED_DESC = AutoEnum.auto() UPDATED_DESC = AutoEnum.auto() NAME_ASC = AutoEnum.auto() NAME_DESC = AutoEnum.auto() def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": """Return an expression used to sort fl...
sort_mapping = { "CREATED_DESC": db.Flow.created.desc(), "UPDATED_DESC": db.Flow.updated.desc(), "NAME_ASC": db.Flow.name.asc(), "NAME_DESC": db.Flow.name.desc(), } return sort_mapping[self.value]
"""Return an expression used to sort flows""" sort_mapping = { "CREATED_DESC": db.Flow.created.desc(), "UPDATED_DESC": db.Flow.updated.desc(), "NAME_ASC": db.Flow.name.asc(), "NAME_DESC": db.Flow.name.desc(), } return sort_mapping[self.valu...
14
117
99
216
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
5,905
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/sorting.py
87,88
81,96
as_sql_sort
LogSort
89,96
88,96
class LogSort(AutoEnum): """Defines log sorting options.""" TIMESTAMP_ASC = AutoEnum.auto() TIMESTAMP_DESC = AutoEnum.auto() def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": FILL_FUNC_BODY
class LogSort(AutoEnum): """Defines log sorting options.""" TIMESTAMP_ASC = AutoEnum.auto() TIMESTAMP_DESC = AutoEnum.auto() def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": """Return an expression used to sort task runs""" FILL_FUNC_BODY
sort_mapping = { "TIMESTAMP_ASC": db.Log.timestamp.asc(), "TIMESTAMP_DESC": db.Log.timestamp.desc(), } return sort_mapping[self.value]
"""Return an expression used to sort task runs""" sort_mapping = { "TIMESTAMP_ASC": db.Log.timestamp.asc(), "TIMESTAMP_DESC": db.Log.timestamp.desc(), } return sort_mapping[self.value]
10
97
66
163
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
5,906
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/sorting.py
67,68
56,81
as_sql_sort
TaskRunSort
69,81
68,81
class TaskRunSort(AutoEnum): """Defines task run sorting options.""" ID_DESC = AutoEnum.auto() EXPECTED_START_TIME_ASC = AutoEnum.auto() EXPECTED_START_TIME_DESC = AutoEnum.auto() NAME_ASC = AutoEnum.auto() NAME_DESC = AutoEnum.auto() NEXT_SCHEDULED_START_TIME_ASC = AutoEnum.auto() END_...
class TaskRunSort(AutoEnum): """Defines task run sorting options.""" ID_DESC = AutoEnum.auto() EXPECTED_START_TIME_ASC = AutoEnum.auto() EXPECTED_START_TIME_DESC = AutoEnum.auto() NAME_ASC = AutoEnum.auto() NAME_DESC = AutoEnum.auto() NEXT_SCHEDULED_START_TIME_ASC = AutoEnum.auto() END_...
sort_mapping = { "ID_DESC": db.TaskRun.id.desc(), "EXPECTED_START_TIME_ASC": db.TaskRun.expected_start_time.asc(), "EXPECTED_START_TIME_DESC": db.TaskRun.expected_start_time.desc(), "NAME_ASC": db.TaskRun.name.asc(), "NAME_DESC": db.TaskRun.name.desc()...
"""Return an expression used to sort task runs""" sort_mapping = { "ID_DESC": db.TaskRun.id.desc(), "EXPECTED_START_TIME_ASC": db.TaskRun.expected_start_time.asc(), "EXPECTED_START_TIME_DESC": db.TaskRun.expected_start_time.desc(), "NAME_ASC": db.TaskRun.n...
20
176
196
372
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
5,907
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/sorting.py
184,185
176,195
as_sql_sort
VariableSort
186,195
185,195
class VariableSort(AutoEnum): """Defines variables sorting options.""" CREATED_DESC = "CREATED_DESC" UPDATED_DESC = "UPDATED_DESC" NAME_DESC = "NAME_DESC" NAME_ASC = "NAME_ASC" def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": FILL_FUNC_BODY
class VariableSort(AutoEnum): """Defines variables sorting options.""" CREATED_DESC = "CREATED_DESC" UPDATED_DESC = "UPDATED_DESC" NAME_DESC = "NAME_DESC" NAME_ASC = "NAME_ASC" def as_sql_sort(self, db: "PrefectDBInterface") -> "ColumnElement": """Return an expression used to sort vari...
sort_mapping = { "CREATED_DESC": db.Variable.created.desc(), "UPDATED_DESC": db.Variable.updated.desc(), "NAME_DESC": db.Variable.name.desc(), "NAME_ASC": db.Variable.name.asc(), } return sort_mapping[self.value]
"""Return an expression used to sort variables""" sort_mapping = { "CREATED_DESC": db.Variable.created.desc(), "UPDATED_DESC": db.Variable.updated.desc(), "NAME_DESC": db.Variable.name.desc(), "NAME_ASC": db.Variable.name.asc(), } return so...
14
125
99
224
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
""" Schemas for sorting Prefect REST API objects. """ from typing import TYPE_CHECKING import sqlalchemy as sa from prefect.utilities.collections import AutoEnum if TYPE_CHECKING: from sqlalchemy.sql.expression import ColumnElement from prefect.server.database.interface import PrefectDBInterface # TODO: C...
5,908
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/statuses.py
28,29
22,32
in_kebab_case
DeploymentStatus
29,32
29,32
class DeploymentStatus(AutoEnum): """Enumeration of deployment statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() def in_kebab_case(self) -> str: FILL_FUNC_BODY
class DeploymentStatus(AutoEnum): """Enumeration of deployment statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() def in_kebab_case(self) -> str: FILL_FUNC_BODY
return self.value.lower().replace("_", "-")
return self.value.lower().replace("_", "-")
3
71
20
91
from prefect.utilities.collections import AutoEnum class WorkPoolStatus(AutoEnum): """Enumeration of work pool statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() PAUSED = AutoEnum.auto() def in_kebab_case(self) -> str: return self.value.lower().replace("_", "-") class Wor...
from prefect.utilities.collections import AutoEnum class WorkPoolStatus(AutoEnum): """Enumeration of work pool statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() PAUSED = AutoEnum.auto() def in_kebab_case(self) -> str: return self.value.lower().replace("_", "-") class Wor...
5,909
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/statuses.py
11,12
4,15
in_kebab_case
WorkPoolStatus
12,15
12,15
class WorkPoolStatus(AutoEnum): """Enumeration of work pool statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() PAUSED = AutoEnum.auto() def in_kebab_case(self) -> str: FILL_FUNC_BODY
class WorkPoolStatus(AutoEnum): """Enumeration of work pool statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() PAUSED = AutoEnum.auto() def in_kebab_case(self) -> str: FILL_FUNC_BODY
return self.value.lower().replace("_", "-")
return self.value.lower().replace("_", "-")
3
83
20
103
from prefect.utilities.collections import AutoEnum class WorkPoolStatus(AutoEnum): """Enumeration of work pool statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() PAUSED = AutoEnum.auto() def in_kebab_case(self) -> str: FILL_FUNC_BODYclass WorkerStatus(AutoEnum): """Enumeration ...
from prefect.utilities.collections import AutoEnum class WorkPoolStatus(AutoEnum): """Enumeration of work pool statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() PAUSED = AutoEnum.auto() def in_kebab_case(self) -> str: FILL_FUNC_BODYclass WorkerStatus(AutoEnum): """Enumeration ...
5,910
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/schemas/statuses.py
39,40
32,41
in_kebab_case
WorkQueueStatus
40,41
40,41
class WorkQueueStatus(AutoEnum): """Enumeration of work queue statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() PAUSED = AutoEnum.auto() def in_kebab_case(self) -> str: FILL_FUNC_BODY
class WorkQueueStatus(AutoEnum): """Enumeration of work queue statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() PAUSED = AutoEnum.auto() def in_kebab_case(self) -> str: FILL_FUNC_BODY
return self.value.lower().replace("_", "-")
return self.value.lower().replace("_", "-")
3
83
16
99
from prefect.utilities.collections import AutoEnum class WorkPoolStatus(AutoEnum): """Enumeration of work pool statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() PAUSED = AutoEnum.auto() def in_kebab_case(self) -> str: return self.value.lower().replace("_", "-") class Wor...
from prefect.utilities.collections import AutoEnum class WorkPoolStatus(AutoEnum): """Enumeration of work pool statuses.""" READY = AutoEnum.auto() NOT_READY = AutoEnum.auto() PAUSED = AutoEnum.auto() def in_kebab_case(self) -> str: return self.value.lower().replace("_", "-") class Wor...
5,911
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/services/late_runs.py
108,111
26,127
_mark_flow_run_as_late
MarkLateRuns
116,127
111,127
class MarkLateRuns(LoopService): """ A simple loop service responsible for identifying flow runs that are "late". A flow run is defined as "late" if has not scheduled within a certain amount of time after its scheduled start time. The exact amount is configurable in Prefect REST API Settings. "...
class MarkLateRuns(LoopService): """ A simple loop service responsible for identifying flow runs that are "late". A flow run is defined as "late" if has not scheduled within a certain amount of time after its scheduled start time. The exact amount is configurable in Prefect REST API Settings. "...
try: await models.flow_runs.set_flow_run_state( session=session, flow_run_id=flow_run.id, state=states.Late(scheduled_time=flow_run.next_scheduled_start_time), flow_policy=MarkLateRunsPolicy, # type: ignore ) except...
""" Mark a flow run as late. Pass-through method for overrides. """ try: await models.flow_runs.set_flow_run_state( session=session, flow_run_id=flow_run.id, state=states.Late(scheduled_time=flow_run.next_scheduled_star...
21
885
122
1,007
""" The MarkLateRuns service. Responsible for putting flow runs in a Late state if they are not started on time. The threshold for a late run can be configured by changing `PREFECT_API_SERVICES_LATE_RUNS_AFTER_SECONDS`. """ import asyncio import datetime import pendulum import sqlalchemy as sa from sqlalchemy.ext.asy...
""" The MarkLateRuns service. Responsible for putting flow runs in a Late state if they are not started on time. The threshold for a late run can be configured by changing `PREFECT_API_SERVICES_LATE_RUNS_AFTER_SECONDS`. """ import asyncio import datetime import pendulum import sqlalchemy as sa from sqlalchemy.ext.asy...
5,912
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/services/pause_expirations.py
34,36
19,82
run_once
FailExpiredPauses
42,65
36,65
class FailExpiredPauses(LoopService): """ A simple loop service responsible for identifying Paused flow runs that no longer can be resumed. """ def __init__(self, loop_seconds: float = None, **kwargs): super().__init__( loop_seconds=loop_seconds or PREFECT_API_SERVICES_P...
class FailExpiredPauses(LoopService): """ A simple loop service responsible for identifying Paused flow runs that no longer can be resumed. """ def __init__(self, loop_seconds: float = None, **kwargs): super().__init__( loop_seconds=loop_seconds or PREFECT_API_SERVICES_P...
while True: async with db.session_context(begin_transaction=True) as session: query = ( sa.select(db.FlowRun) .where( db.FlowRun.state_type == states.StateType.PAUSED, ) .limit(sel...
""" Mark flow runs as failed by: - Querying for flow runs in a Paused state that have timed out - For any runs past the "expiration" threshold, setting the flow run state to a new `Failed` state """ while True: async with db.session_context(begin_transaction=...
57
400
217
617
""" The FailExpiredPauses service. Responsible for putting Paused flow runs in a Failed state if they are not resumed on time. """ import asyncio import pendulum import sqlalchemy as sa from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.models as models from prefect.server.database.dependencies im...
""" The FailExpiredPauses service. Responsible for putting Paused flow runs in a Failed state if they are not resumed on time. """ import asyncio import pendulum import sqlalchemy as sa from sqlalchemy.ext.asyncio import AsyncSession import prefect.server.models as models from prefect.server.database.dependencies im...
5,913
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/task_queue.py
95,96
87,104
get
MultiQueue
97,104
96,104
class MultiQueue: """A queue that can pull tasks from from any of a number of task queues""" _queues: List[TaskQueue] def __init__(self, task_keys: List[str]): self._queues = [TaskQueue.for_key(task_key) for task_key in task_keys] async def get(self) -> schemas.core.TaskRun: FILL_FUNC_BODY
class MultiQueue: """A queue that can pull tasks from from any of a number of task queues""" _queues: List[TaskQueue] def __init__(self, task_keys: List[str]): self._queues = [TaskQueue.for_key(task_key) for task_key in task_keys] async def get(self) -> schemas.core.TaskRun: """Gets t...
while True: for queue in self._queues: try: return queue.get_nowait() except asyncio.QueueEmpty: continue await asyncio.sleep(0.01)
"""Gets the next task_run from any of the given queues""" while True: for queue in self._queues: try: return queue.get_nowait() except asyncio.QueueEmpty: continue await asyncio.sleep(0.01)
14
130
61
191
""" Implements an in-memory task queue for delivering autonomous task runs to TaskServers. """ import asyncio from typing import Dict, List, Optional, Tuple from typing_extensions import Self import prefect.server.schemas as schemas from prefect.settings import ( PREFECT_TASK_SCHEDULING_MAX_RETRY_QUEUE_SIZE, ...
""" Implements an in-memory task queue for delivering autonomous task runs to TaskServers. """ import asyncio from typing import Dict, List, Optional, Tuple from typing_extensions import Self import prefect.server.schemas as schemas from prefect.settings import ( PREFECT_TASK_SCHEDULING_MAX_RETRY_QUEUE_SIZE, ...
5,914
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/task_queue.py
31,33
17,87
enqueue
TaskQueue
33,35
33,35
class TaskQueue: _task_queues: Dict[str, Self] = {} default_scheduled_max_size: int = ( PREFECT_TASK_SCHEDULING_MAX_SCHEDULED_QUEUE_SIZE.value() ) default_retry_max_size: int = PREFECT_TASK_SCHEDULING_MAX_RETRY_QUEUE_SIZE.value() _queue_size_configs: Dict[str, Tuple[int, int]] = {} ta...
class TaskQueue: _task_queues: Dict[str, Self] = {} default_scheduled_max_size: int = ( PREFECT_TASK_SCHEDULING_MAX_SCHEDULED_QUEUE_SIZE.value() ) default_retry_max_size: int = PREFECT_TASK_SCHEDULING_MAX_RETRY_QUEUE_SIZE.value() _queue_size_configs: Dict[str, Tuple[int, int]] = {} ta...
await cls.for_key(task_run.task_key).put(task_run)
await cls.for_key(task_run.task_key).put(task_run)
2
864
27
891
""" Implements an in-memory task queue for delivering autonomous task runs to TaskServers. """ import asyncio from typing import Dict, List, Optional, Tuple from typing_extensions import Self import prefect.server.schemas as schemas from prefect.settings import ( PREFECT_TASK_SCHEDULING_MAX_RETRY_QUEUE_SIZE, ...
""" Implements an in-memory task queue for delivering autonomous task runs to TaskServers. """ import asyncio from typing import Dict, List, Optional, Tuple from typing_extensions import Self import prefect.server.schemas as schemas from prefect.settings import ( PREFECT_TASK_SCHEDULING_MAX_RETRY_QUEUE_SIZE, ...
5,915
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/http.py
1,2
1,19
should_redact_header
4,19
2,19
def should_redact_header(key: str) -> bool: FILL_FUNC_BODY
def should_redact_header(key: str) -> bool: """Indicates whether an HTTP header is sensitive or noisy and should be redacted from events and templates.""" FILL_FUNC_BODY
key = key.lower() if key in {"authorization", "traceparent", "via"}: return True if key.startswith("x-forwarded"): return True if key.startswith("x-b3"): return True if key.startswith("x-cloud-trace"): return True if key.startswith("x-envoy"): return True ...
"""Indicates whether an HTTP header is sensitive or noisy and should be redacted from events and templates.""" key = key.lower() if key in {"authorization", "traceparent", "via"}: return True if key.startswith("x-forwarded"): return True if key.startswith("x-b3"): return ...
33
53
145
198
def should_redact_header(key: str) -> bool: FILL_FUNC_BODY
def should_redact_header(key: str) -> bool: """Indicates whether an HTTP header is sensitive or noisy and should be redacted from events and templates.""" FILL_FUNC_BODY
5,916
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/messaging/memory.py
207,209
1,214
ephemeral_subscription
209,214
209,214
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
subscription = Topic.by_name(topic).subscribe() try: yield {"topic": topic, "subscription": subscription} finally: Topic.by_name(topic).unsubscribe(subscription)
subscription = Topic.by_name(topic).subscribe() try: yield {"topic": topic, "subscription": subscription} finally: Topic.by_name(topic).unsubscribe(subscription)
11
1,747
59
1,806
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
5,917
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/messaging/memory.py
124,125
115,158
without_duplicates
Cache
125,146
125,146
class Cache(_Cache): _recently_seen_messages: MutableMapping[str, bool] = TTLCache( maxsize=1000, ttl=timedelta(minutes=5).total_seconds(), ) async def clear_recently_seen_messages(self) -> None: self._recently_seen_messages.clear() async def without_duplicates(self, attribute:...
class Cache(_Cache): _recently_seen_messages: MutableMapping[str, bool] = TTLCache( maxsize=1000, ttl=timedelta(minutes=5).total_seconds(), ) async def clear_recently_seen_messages(self) -> None: self._recently_seen_messages.clear() async def without_duplicates(self, attribute:...
messages_with_attribute = [] messages_without_attribute = [] for m in messages: if m.attributes is None or attribute not in m.attributes: logger.warning( "Message is missing deduplication attribute %r", attribute, ...
messages_with_attribute = [] messages_without_attribute = [] for m in messages: if m.attributes is None or attribute not in m.attributes: logger.warning( "Message is missing deduplication attribute %r", attribute, ...
43
249
190
439
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
5,918
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/messaging/memory.py
194,195
186,207
run
Consumer
195,207
195,207
class Consumer(_Consumer): def __init__(self, topic: str, subscription: Optional[Subscription] = None): self.topic = Topic.by_name(topic) if not subscription: subscription = self.topic.subscribe() assert subscription.topic is self.topic self.subscription = subscription ...
class Consumer(_Consumer): def __init__(self, topic: str, subscription: Optional[Subscription] = None): self.topic = Topic.by_name(topic) if not subscription: subscription = self.topic.subscribe() assert subscription.topic is self.topic self.subscription = subscription ...
while True: message = await self.subscription.get() try: await handler(message) except StopConsumer as e: if not e.ack: await self.subscription.retry(message) return except Exception: ...
while True: message = await self.subscription.get() try: await handler(message) except StopConsumer as e: if not e.ack: await self.subscription.retry(message) return except Exception: ...
23
106
92
198
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
5,919
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/messaging/memory.py
170,171
158,186
publish_data
Publisher
171,186
171,186
class Publisher(_Publisher): def __init__(self, topic: str, cache: Cache, deduplicate_by: Optional[str] = None): self.topic = Topic.by_name(topic) self.deduplicate_by = deduplicate_by self._cache = cache async def __aenter__(self) -> Self: return self async def __aexit__(se...
class Publisher(_Publisher): def __init__(self, topic: str, cache: Cache, deduplicate_by: Optional[str] = None): self.topic = Topic.by_name(topic) self.deduplicate_by = deduplicate_by self._cache = cache async def __aenter__(self) -> Self: return self async def __aexit__(se...
to_publish = [MemoryMessage(data, attributes)] if self.deduplicate_by: to_publish = await self._cache.without_duplicates( self.deduplicate_by, to_publish ) try: for message in to_publish: await self.topic.publish(message) ...
to_publish = [MemoryMessage(data, attributes)] if self.deduplicate_by: to_publish = await self._cache.without_duplicates( self.deduplicate_by, to_publish ) try: for message in to_publish: await self.topic.publish(message) ...
28
151
146
297
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
5,920
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/messaging/memory.py
50,51
34,56
get
Subscription
51,56
51,56
class Subscription: topic: "Topic" _queue: asyncio.Queue _retry: asyncio.Queue def __init__(self, topic: "Topic") -> None: self.topic = topic self._queue = asyncio.Queue() self._retry = asyncio.Queue() async def deliver(self, message: MemoryMessage) -> None: await s...
class Subscription: topic: "Topic" _queue: asyncio.Queue _retry: asyncio.Queue def __init__(self, topic: "Topic") -> None: self.topic = topic self._queue = asyncio.Queue() self._retry = asyncio.Queue() async def deliver(self, message: MemoryMessage) -> None: await s...
if self._retry.qsize() > 0: return await self._retry.get() return await self._queue.get()
if self._retry.qsize() > 0: return await self._retry.get() return await self._queue.get()
10
165
42
207
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
5,921
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/messaging/memory.py
75,77
56,99
clear_all
Topic
77,81
77,81
class Topic: _topics: Dict[str, "Topic"] = {} name: str _subscriptions: List[Subscription] def __init__(self, name: str) -> None: self.name = name self._subscriptions = [] @classmethod def by_name(cls, name: str) -> Self: try: return cls._topics[name] ...
class Topic: _topics: Dict[str, "Topic"] = {} name: str _subscriptions: List[Subscription] def __init__(self, name: str) -> None: self.name = name self._subscriptions = [] @classmethod def by_name(cls, name: str) -> Self: try: return cls._topics[name] ...
for topic in cls._topics.values(): topic.clear() cls._topics = {}
for topic in cls._topics.values(): topic.clear() cls._topics = {}
8
308
33
341
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
import asyncio from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import timedelta from typing import ( Any, AsyncGenerator, Dict, List, MutableMapping, Optional, TypeVar, Union, ) from cachetools import TTLCache from typing_extensions import Self...
5,922
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/schemas/fields.py
27,29
1,37
validate
29,37
29,37
import datetime import pendulum from typing_extensions import TypeAlias # Rather than subclassing pendulum.DateTime to add our pydantic-specific validation, # which will lead to a lot of funky typing issues, we'll just monkeypatch the pydantic # validators onto the class. Retaining this type alias means that we can ...
import datetime import pendulum from typing_extensions import TypeAlias # Rather than subclassing pendulum.DateTime to add our pydantic-specific validation, # which will lead to a lot of funky typing issues, we'll just monkeypatch the pydantic # validators onto the class. Retaining this type alias means that we can ...
if isinstance(v, str): parsed = pendulum.parse(v) assert isinstance(parsed, pendulum.DateTime) return parsed elif isinstance(v, datetime.datetime): return pendulum.instance(v) else: raise ValueError("Unrecognized datetime.")
if isinstance(v, str): parsed = pendulum.parse(v) assert isinstance(parsed, pendulum.DateTime) return parsed elif isinstance(v, datetime.datetime): return pendulum.instance(v) else: raise ValueError("Unrecognized datetime.")
20
261
87
348
import datetime import pendulum from typing_extensions import TypeAlias # Rather than subclassing pendulum.DateTime to add our pydantic-specific validation, # which will lead to a lot of funky typing issues, we'll just monkeypatch the pydantic # validators onto the class. Retaining this type alias means that we can ...
import datetime import pendulum from typing_extensions import TypeAlias # Rather than subclassing pendulum.DateTime to add our pydantic-specific validation, # which will lead to a lot of funky typing issues, we'll just monkeypatch the pydantic # validators onto the class. Retaining this type alias means that we can ...
5,923
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/schemas/serializers.py
26,27
1,38
orjson_dumps_extra_compatible
35,38
27,38
from typing import Any, TypeVar import orjson from prefect._internal.pydantic import HAS_PYDANTIC_V2 if HAS_PYDANTIC_V2: from pydantic.v1 import BaseModel else: from pydantic import BaseModel T = TypeVar("T") B = TypeVar("B", bound=BaseModel) def orjson_dumps(v: Any, *, default: Any) -> str: """ ...
from typing import Any, TypeVar import orjson from prefect._internal.pydantic import HAS_PYDANTIC_V2 if HAS_PYDANTIC_V2: from pydantic.v1 import BaseModel else: from pydantic import BaseModel T = TypeVar("T") B = TypeVar("B", bound=BaseModel) def orjson_dumps(v: Any, *, default: Any) -> str: """ ...
return orjson.dumps( v, default=default, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY ).decode()
""" Utility for dumping a value to JSON using orjson, but allows for 1) non-string keys: this is helpful for situations like pandas dataframes, which can result in non-string keys 2) numpy types: for serializing numpy arrays orjson.dumps returns bytes, to match standard json.dumps we need to de...
8
310
54
364
from typing import Any, TypeVar import orjson from prefect._internal.pydantic import HAS_PYDANTIC_V2 if HAS_PYDANTIC_V2: from pydantic.v1 import BaseModel else: from pydantic import BaseModel T = TypeVar("T") B = TypeVar("B", bound=BaseModel) def orjson_dumps(v: Any, *, default: Any) -> str: """ ...
from typing import Any, TypeVar import orjson from prefect._internal.pydantic import HAS_PYDANTIC_V2 if HAS_PYDANTIC_V2: from pydantic.v1 import BaseModel else: from pydantic import BaseModel T = TypeVar("T") B = TypeVar("B", bound=BaseModel) def orjson_dumps(v: Any, *, default: Any) -> str: """ ...
5,924
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/server.py
30,31
1,140
response_scoped_dependency
50,85
31,85
""" Utilities for the Prefect REST API server. """ import functools import inspect from contextlib import AsyncExitStack, asynccontextmanager from typing import Any, Callable, Coroutine, Sequence, Set, get_type_hints from prefect._vendor.fastapi import APIRouter, Request, Response, status from prefect._vendor.fastapi...
""" Utilities for the Prefect REST API server. """ import functools import inspect from contextlib import AsyncExitStack, asynccontextmanager from typing import Any, Callable, Coroutine, Sequence, Set, get_type_hints from prefect._vendor.fastapi import APIRouter, Request, Response, status from prefect._vendor.fastapi...
signature = inspect.signature(dependency) async def wrapper(*args, request: Request, **kwargs): # Replicate FastAPI behavior of auto-creating a context manager if inspect.isasyncgenfunction(dependency): context_manager = asynccontextmanager(dependency) else: cont...
""" Ensure that this dependency closes before the response is returned to the client. By default, FastAPI closes dependencies after sending the response. Uses an async stack that is exited before the response is returned. This is particularly useful for database sessions which must be committed bef...
120
1,086
351
1,437
""" Utilities for the Prefect REST API server. """ import functools import inspect from contextlib import AsyncExitStack, asynccontextmanager from typing import Any, Callable, Coroutine, Sequence, Set, get_type_hints from prefect._vendor.fastapi import APIRouter, Request, Response, status from prefect._vendor.fastapi...
""" Utilities for the Prefect REST API server. """ import functools import inspect from contextlib import AsyncExitStack, asynccontextmanager from typing import Any, Callable, Coroutine, Sequence, Set, get_type_hints from prefect._vendor.fastapi import APIRouter, Request, Response, status from prefect._vendor.fastapi...
5,925
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/server.py
97,98
85,111
get_route_handler
PrefectAPIRoute
98,111
98,111
class PrefectAPIRoute(APIRoute): """ A FastAPIRoute class which attaches an async stack to requests that exits before a response is returned. Requests already have `request.scope['fastapi_astack']` which is an async stack for the full scope of the request. This stack is used for managing contexts o...
class PrefectAPIRoute(APIRoute): """ A FastAPIRoute class which attaches an async stack to requests that exits before a response is returned. Requests already have `request.scope['fastapi_astack']` which is an async stack for the full scope of the request. This stack is used for managing contexts o...
default_handler = super().get_route_handler() async def handle_response_scoped_depends(request: Request) -> Response: # Create a new stack scoped to exit before the response is returned async with AsyncExitStack() as stack: request.state.response_scoped_stack = s...
default_handler = super().get_route_handler() async def handle_response_scoped_depends(request: Request) -> Response: # Create a new stack scoped to exit before the response is returned async with AsyncExitStack() as stack: request.state.response_scoped_stack = s...
38
190
123
313
""" Utilities for the Prefect REST API server. """ import functools import inspect from contextlib import AsyncExitStack, asynccontextmanager from typing import Any, Callable, Coroutine, Sequence, Set, get_type_hints from prefect._vendor.fastapi import APIRouter, Request, Response, status from prefect._vendor.fastapi...
""" Utilities for the Prefect REST API server. """ import functools import inspect from contextlib import AsyncExitStack, asynccontextmanager from typing import Any, Callable, Coroutine, Sequence, Set, get_type_hints from prefect._vendor.fastapi import APIRouter, Request, Response, status from prefect._vendor.fastapi...
5,926
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/server.py
120,123
111,140
add_api_route
PrefectRouter
132,140
123,140
class PrefectRouter(APIRouter): """ A base class for Prefect REST API routers. """ def __init__(self, **kwargs: Any) -> None: kwargs.setdefault("route_class", PrefectAPIRoute) super().__init__(**kwargs) def add_api_route( self, path: str, endpoint: Callable[..., Any], **kwa...
class PrefectRouter(APIRouter): """ A base class for Prefect REST API routers. """ def __init__(self, **kwargs: Any) -> None: kwargs.setdefault("route_class", PrefectAPIRoute) super().__init__(**kwargs) def add_api_route( self, path: str, endpoint: Callable[..., Any], **kwa...
if kwargs.get("status_code") == status.HTTP_204_NO_CONTENT: # any routes that return No-Content status codes must # explicitly set a response_class that will handle status codes # and not return anything in the body kwargs["response_class"] = Response if k...
""" Add an API route. For routes that return content and have not specified a `response_model`, use return type annotation to infer the response model. For routes that return No-Content status codes, explicitly set a `response_class` to ensure nothing is returned in the...
45
203
143
346
""" Utilities for the Prefect REST API server. """ import functools import inspect from contextlib import AsyncExitStack, asynccontextmanager from typing import Any, Callable, Coroutine, Sequence, Set, get_type_hints from prefect._vendor.fastapi import APIRouter, Request, Response, status from prefect._vendor.fastapi...
""" Utilities for the Prefect REST API server. """ import functools import inspect from contextlib import AsyncExitStack, asynccontextmanager from typing import Any, Callable, Coroutine, Sequence, Set, get_type_hints from prefect._vendor.fastapi import APIRouter, Request, Response, status from prefect._vendor.fastapi...
5,927
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/subscriptions.py
16,17
1,43
accept_prefect_socket
17,43
17,43
from typing import Optional from prefect._vendor.fastapi import ( WebSocket, ) from prefect._vendor.starlette.status import ( WS_1002_PROTOCOL_ERROR, WS_1008_POLICY_VIOLATION, ) from prefect._vendor.starlette.websockets import WebSocketDisconnect from websockets.exceptions import ConnectionClosed NORMAL_D...
from typing import Optional from prefect._vendor.fastapi import ( WebSocket, ) from prefect._vendor.starlette.status import ( WS_1002_PROTOCOL_ERROR, WS_1008_POLICY_VIOLATION, ) from prefect._vendor.starlette.websockets import WebSocketDisconnect from websockets.exceptions import ConnectionClosed NORMAL_D...
subprotocols = websocket.headers.get("Sec-WebSocket-Protocol", "").split(",") if "prefect" not in subprotocols: return await websocket.close(WS_1002_PROTOCOL_ERROR) await websocket.accept(subprotocol="prefect") try: # Websocket connections are authenticated via messages. The first ...
subprotocols = websocket.headers.get("Sec-WebSocket-Protocol", "").split(",") if "prefect" not in subprotocols: return await websocket.close(WS_1002_PROTOCOL_ERROR) await websocket.accept(subprotocol="prefect") try: # Websocket connections are authenticated via messages. The first ...
113
167
325
492
from typing import Optional from prefect._vendor.fastapi import ( WebSocket, ) from prefect._vendor.starlette.status import ( WS_1002_PROTOCOL_ERROR, WS_1008_POLICY_VIOLATION, ) from prefect._vendor.starlette.websockets import WebSocketDisconnect from websockets.exceptions import ConnectionClosed NORMAL_D...
from typing import Optional from prefect._vendor.fastapi import ( WebSocket, ) from prefect._vendor.starlette.status import ( WS_1002_PROTOCOL_ERROR, WS_1008_POLICY_VIOLATION, ) from prefect._vendor.starlette.websockets import WebSocketDisconnect from websockets.exceptions import ConnectionClosed NORMAL_D...
5,928
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/server/utilities/user_templates.py
59,60
1,136
_validate_loop_constraints
60,80
60,80
"""Utilities to support safely rendering user-supplied templates""" from typing import Any, Dict, List, Optional, Set import jinja2.sandbox from jinja2 import ChainableUndefined, nodes from jinja2.sandbox import ImmutableSandboxedEnvironment from prefect.logging import get_logger logger = get_logger(__name__) jin...
"""Utilities to support safely rendering user-supplied templates""" from typing import Any, Dict, List, Optional, Set import jinja2.sandbox from jinja2 import ChainableUndefined, nodes from jinja2.sandbox import ImmutableSandboxedEnvironment from prefect.logging import get_logger logger = get_logger(__name__) jin...
for_nodes = [node for node in root_node.find_all(nodes.For)] if not for_nodes: return if len(for_nodes) > MAX_LOOP_COUNT: raise TemplateSecurityError( f"Contains {len(for_nodes)} for loops. Templates can contain no " f"more than {MAX_LOOP_COUNT} for loops." ...
for_nodes = [node for node in root_node.find_all(nodes.For)] if not for_nodes: return if len(for_nodes) > MAX_LOOP_COUNT: raise TemplateSecurityError( f"Contains {len(for_nodes)} for loops. Templates can contain no " f"more than {MAX_LOOP_COUNT} for loops." ...
68
1,055
243
1,298
"""Utilities to support safely rendering user-supplied templates""" from typing import Any, Dict, List, Optional, Set import jinja2.sandbox from jinja2 import ChainableUndefined, nodes from jinja2.sandbox import ImmutableSandboxedEnvironment from prefect.logging import get_logger logger = get_logger(__name__) jin...
"""Utilities to support safely rendering user-supplied templates""" from typing import Any, Dict, List, Optional, Set import jinja2.sandbox from jinja2 import ChainableUndefined, nodes from jinja2.sandbox import ImmutableSandboxedEnvironment from prefect.logging import get_logger logger = get_logger(__name__) jin...
5,929
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/software/base.py
32,35
1,51
remove_duplicate_requirements
39,43
35,43
from typing import Iterable, List, Optional class Requirement: # Implementations are expected to at least contain a name attribute name: str @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, value): if not isinstance(value, cls): ...
from typing import Iterable, List, Optional class Requirement: # Implementations are expected to at least contain a name attribute name: str @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, value): if not isinstance(value, cls): ...
constant_names = {req.name for req in constant} return [req for req in to_deduplicate if req.name not in constant_names]
""" Returns a list of requirements that excludes requirements already specified in the first iterable. """ constant_names = {req.name for req in constant} return [req for req in to_deduplicate if req.name not in constant_names]
18
371
43
414
from typing import Iterable, List, Optional class Requirement: # Implementations are expected to at least contain a name attribute name: str @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, value): if not isinstance(value, cls): ...
from typing import Iterable, List, Optional class Requirement: # Implementations are expected to at least contain a name attribute name: str @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, value): if not isinstance(value, cls): ...
5,930
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/software/base.py
12,14
4,32
validate
Requirement
14,19
14,19
class Requirement: # Implementations are expected to at least contain a name attribute name: str @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, value): FILL_FUNC_BODY def __eq__(self, other: object) -> bool: """ Requiremen...
class Requirement: # Implementations are expected to at least contain a name attribute name: str @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, value): FILL_FUNC_BODY def __eq__(self, other: object) -> bool: """ Requiremen...
if not isinstance(value, cls): # Attempt to parse the string representation of the input type return cls(str(value)) return value
if not isinstance(value, cls): # Attempt to parse the string representation of the input type return cls(str(value)) return value
19
181
46
227
from typing import Iterable, List, Optional class Requirement: # Implementations are expected to at least contain a name attribute name: str @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, value): FILL_FUNC_BODY def __eq__(self, other: o...
from typing import Iterable, List, Optional class Requirement: # Implementations are expected to at least contain a name attribute name: str @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, value): FILL_FUNC_BODY def __eq__(self, other: o...
5,931
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/software/pip.py
53,54
1,123
_is_editable_install
58,70
54,70
import site import warnings from pathlib import Path from typing import Dict, List, Type, Union import packaging.requirements import packaging.version from typing_extensions import Literal, Self from prefect.software.base import Requirement from prefect.utilities.compat import importlib_metadata class PipRequiremen...
import site import warnings from pathlib import Path from typing import Dict, List, Type, Union import packaging.requirements import packaging.version from typing_extensions import Literal, Self from prefect.software.base import Requirement from prefect.utilities.compat import importlib_metadata class PipRequiremen...
site_packages = site.getsitepackages() + [site.getusersitepackages()] dist_location = dist.locate_file("") for site_package_dir in site_packages: if _is_same_path(dist_location, site_package_dir) or _is_child_path( dist_location, site_package_dir ): return False ...
""" Determine if a distribution is an 'editable' install by scanning if it is present in a site-packages directory or not; if not, we presume it is editable. """ site_packages = site.getsitepackages() + [site.getusersitepackages()] dist_location = dist.locate_file("") for site_package_dir i...
24
1,036
116
1,152
import site import warnings from pathlib import Path from typing import Dict, List, Type, Union import packaging.requirements import packaging.version from typing_extensions import Literal, Self from prefect.software.base import Requirement from prefect.utilities.compat import importlib_metadata class PipRequiremen...
import site import warnings from pathlib import Path from typing import Dict, List, Type, Union import packaging.requirements import packaging.version from typing_extensions import Literal, Self from prefect.software.base import Requirement from prefect.utilities.compat import importlib_metadata class PipRequiremen...
5,932
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/software/pip.py
21,25
14,41
from_distribution
PipRequirement
28,41
25,41
class PipRequirement(Requirement, packaging.requirements.Requirement): """ A parsed Python requirement. An extension for `packaging.version.Requirement` with Pydantic support. """ @classmethod def from_distribution( cls: Type[Self], dist: "importlib_metadata.Distribution" ) -> Self...
class PipRequirement(Requirement, packaging.requirements.Requirement): """ A parsed Python requirement. An extension for `packaging.version.Requirement` with Pydantic support. """ @classmethod def from_distribution( cls: Type[Self], dist: "importlib_metadata.Distribution" ) -> Self...
if _is_editable_install(dist): raise ValueError( f"Distribution {dist!r} is an editable installation and cannot be " "used as a requirement." ) return cls.validate( packaging.requirements.Requirement( f"{dist.metadata['...
""" Convert a Python distribution object into a requirement """ if _is_editable_install(dist): raise ValueError( f"Distribution {dist!r} is an editable installation and cannot be " "used as a requirement." ) return cls.vali...
25
118
108
226
import site import warnings from pathlib import Path from typing import Dict, List, Type, Union import packaging.requirements import packaging.version from typing_extensions import Literal, Self from prefect.software.base import Requirement from prefect.utilities.compat import importlib_metadata class PipRequiremen...
import site import warnings from pathlib import Path from typing import Dict, List, Type, Union import packaging.requirements import packaging.version from typing_extensions import Literal, Self from prefect.software.base import Requirement from prefect.utilities.compat import importlib_metadata class PipRequiremen...
5,933
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/task_runners.py
112,113
98,204
duplicate
BaseTaskRunner
116,120
113,120
class BaseTaskRunner(metaclass=abc.ABCMeta): def __init__(self) -> None: self.logger = get_logger(f"task_runner.{self.name}") self._started: bool = False @property @abc.abstractmethod def concurrency_type(self) -> TaskConcurrencyType: pass # noqa @property def name(sel...
class BaseTaskRunner(metaclass=abc.ABCMeta): def __init__(self) -> None: self.logger = get_logger(f"task_runner.{self.name}") self._started: bool = False @property @abc.abstractmethod def concurrency_type(self) -> TaskConcurrencyType: pass # noqa @property def name(sel...
# The base class returns `NotImplemented` to indicate that this is not yet # implemented by a given task runner. return NotImplemented
""" Return a new task runner instance with the same options. """ # The base class returns `NotImplemented` to indicate that this is not yet # implemented by a given task runner. return NotImplemented
22
896
42
938
""" Interface and implementations of various task runners. [Task Runners](/concepts/task-runners/) in Prefect are responsible for managing the execution of Prefect task runs. Generally speaking, users are not expected to interact with task runners outside of configuring and initializing them for a flow. Example: ...
""" Interface and implementations of various task runners. [Task Runners](/concepts/task-runners/) in Prefect are responsible for managing the execution of Prefect task runs. Generally speaking, users are not expected to interact with task runners outside of configuring and initializing them for a flow. Example: ...
5,934
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/task_runners.py
275,280
241,366
submit
ConcurrentTaskRunner
280,297
280,297
class ConcurrentTaskRunner(BaseTaskRunner): """ A concurrent task runner that allows tasks to switch when blocking on IO. Synchronous tasks will be submitted to a thread pool maintained by `anyio`. Example: ``` Using a thread for concurrency: >>> from prefect import flow ...
class ConcurrentTaskRunner(BaseTaskRunner): """ A concurrent task runner that allows tasks to switch when blocking on IO. Synchronous tasks will be submitted to a thread pool maintained by `anyio`. Example: ``` Using a thread for concurrency: >>> from prefect import flow ...
if not self._started: raise RuntimeError( "The task runner must be started before submitting work." ) if not self._task_group: raise RuntimeError( "The concurrent task runner cannot be used to submit work after " "seria...
if not self._started: raise RuntimeError( "The task runner must be started before submitting work." ) if not self._task_group: raise RuntimeError( "The concurrent task runner cannot be used to submit work after " "seria...
56
934
155
1,089
""" Interface and implementations of various task runners. [Task Runners](/concepts/task-runners/) in Prefect are responsible for managing the execution of Prefect task runs. Generally speaking, users are not expected to interact with task runners outside of configuring and initializing them for a flow. Example: ...
""" Interface and implementations of various task runners. [Task Runners](/concepts/task-runners/) in Prefect are responsible for managing the execution of Prefect task runs. Generally speaking, users are not expected to interact with task runners outside of configuring and initializing them for a flow. Example: ...
5,935
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/task_runners.py
224,229
204,241
submit
SequentialTaskRunner
229,237
229,237
class SequentialTaskRunner(BaseTaskRunner): """ A simple task runner that executes calls as they are submitted. If writing synchronous tasks, this runner will always execute tasks sequentially. If writing async tasks, this runner will execute tasks sequentially unless grouped using `anyio.create_ta...
class SequentialTaskRunner(BaseTaskRunner): """ A simple task runner that executes calls as they are submitted. If writing synchronous tasks, this runner will always execute tasks sequentially. If writing async tasks, this runner will execute tasks sequentially unless grouped using `anyio.create_ta...
# Run the function immediately and store the result in memory try: result = await call() except BaseException as exc: result = await exception_to_crashed_state(exc) self._results[key] = result
# Run the function immediately and store the result in memory try: result = await call() except BaseException as exc: result = await exception_to_crashed_state(exc) self._results[key] = result
27
262
68
330
""" Interface and implementations of various task runners. [Task Runners](/concepts/task-runners/) in Prefect are responsible for managing the execution of Prefect task runs. Generally speaking, users are not expected to interact with task runners outside of configuring and initializing them for a flow. Example: ...
""" Interface and implementations of various task runners. [Task Runners](/concepts/task-runners/) in Prefect are responsible for managing the execution of Prefect task runs. Generally speaking, users are not expected to interact with task runners outside of configuring and initializing them for a flow. Example: ...
5,938
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/annotations.py
19,20
10,40
unwrap
BaseAnnotation
20,28
20,28
class BaseAnnotation( namedtuple("BaseAnnotation", field_names="value"), ABC, Generic[T] ): """ Base class for Prefect annotation types. Inherits from `namedtuple` for unpacking support in another tools. """ def unwrap(self) -> T: FILL_FUNC_BODY def rewrap(self, value: T) -> "BaseAnnotation...
class BaseAnnotation( namedtuple("BaseAnnotation", field_names="value"), ABC, Generic[T] ): """ Base class for Prefect annotation types. Inherits from `namedtuple` for unpacking support in another tools. """ def unwrap(self) -> T: FILL_FUNC_BODY def rewrap(self, value: T) -> "BaseAnnotation...
if sys.version_info < (3, 8): # cannot simply return self.value due to recursion error in Python 3.7 # also _asdict does not follow convention; it's not an internal method # https://stackoverflow.com/a/26180604 return self._asdict()["value"] else: ...
if sys.version_info < (3, 8): # cannot simply return self.value due to recursion error in Python 3.7 # also _asdict does not follow convention; it's not an internal method # https://stackoverflow.com/a/26180604 return self._asdict()["value"] else: ...
36
205
104
309
import sys import warnings from abc import ABC from collections import namedtuple from typing import Generic, TypeVar T = TypeVar("T") class BaseAnnotation( namedtuple("BaseAnnotation", field_names="value"), ABC, Generic[T] ): """ Base class for Prefect annotation types. Inherits from `namedtuple` f...
import sys import warnings from abc import ABC from collections import namedtuple from typing import Generic, TypeVar T = TypeVar("T") class BaseAnnotation( namedtuple("BaseAnnotation", field_names="value"), ABC, Generic[T] ): """ Base class for Prefect annotation types. Inherits from `namedtuple` f...
5,939
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/annotations.py
92,93
68,97
unquote
quote
93,97
93,97
class quote(BaseAnnotation[T]): """ Simple wrapper to mark an expression as a different type so it will not be coerced by Prefect. For example, if you want to return a state from a flow without having the flow assume that state. quote will also instruct prefect to ignore introspection of the wrappe...
class quote(BaseAnnotation[T]): """ Simple wrapper to mark an expression as a different type so it will not be coerced by Prefect. For example, if you want to return a state from a flow without having the flow assume that state. quote will also instruct prefect to ignore introspection of the wrappe...
return self.unwrap() # Backwards compatibility stub for `Quote` class
return self.unwrap() # Backwards compatibility stub for `Quote` class
9
224
26
250
import sys import warnings from abc import ABC from collections import namedtuple from typing import Generic, TypeVar T = TypeVar("T") class BaseAnnotation( namedtuple("BaseAnnotation", field_names="value"), ABC, Generic[T] ): """ Base class for Prefect annotation types. Inherits from `namedtuple` f...
import sys import warnings from abc import ABC from collections import namedtuple from typing import Generic, TypeVar T = TypeVar("T") class BaseAnnotation( namedtuple("BaseAnnotation", field_names="value"), ABC, Generic[T] ): """ Base class for Prefect annotation types. Inherits from `namedtuple` f...
5,941
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/asyncutils.py
416,417
399,454
_run_and_store
GatherTaskGroup
417,419
417,419
class GatherTaskGroup(anyio.abc.TaskGroup): """ A task group that gathers results. AnyIO does not include support `gather`. This class extends the `TaskGroup` interface to allow simple gathering. See https://github.com/agronholm/anyio/issues/100 This class should be instantiated with `create_...
class GatherTaskGroup(anyio.abc.TaskGroup): """ A task group that gathers results. AnyIO does not include support `gather`. This class extends the `TaskGroup` interface to allow simple gathering. See https://github.com/agronholm/anyio/issues/100 This class should be instantiated with `create_...
self._results[key] = await fn(*args)
self._results[key] = await fn(*args)
4
523
17
540
""" Utilities for interoperability with async functions and workers from various contexts. """ import asyncio import ctypes import inspect import threading import warnings from concurrent.futures import ThreadPoolExecutor from contextlib import asynccontextmanager from contextvars import copy_context from functools im...
""" Utilities for interoperability with async functions and workers from various contexts. """ import asyncio import ctypes import inspect import threading import warnings from concurrent.futures import ThreadPoolExecutor from contextlib import asynccontextmanager from contextvars import copy_context from functools im...
5,942
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/asyncutils.py
489,490
476,493
_initialize_semaphore
LazySemaphore
490,493
490,493
class LazySemaphore: def __init__(self, initial_value_func): self._semaphore = None self._initial_value_func = initial_value_func async def __aenter__(self): self._initialize_semaphore() await self._semaphore.__aenter__() return self._semaphore async def __aexit__(s...
class LazySemaphore: def __init__(self, initial_value_func): self._semaphore = None self._initial_value_func = initial_value_func async def __aenter__(self): self._initialize_semaphore() await self._semaphore.__aenter__() return self._semaphore async def __aexit__(s...
if self._semaphore is None: initial_value = self._initial_value_func() self._semaphore = asyncio.Semaphore(initial_value)
if self._semaphore is None: initial_value = self._initial_value_func() self._semaphore = asyncio.Semaphore(initial_value)
10
154
47
201
""" Utilities for interoperability with async functions and workers from various contexts. """ import asyncio import ctypes import inspect import threading import warnings from concurrent.futures import ThreadPoolExecutor from contextlib import asynccontextmanager from contextvars import copy_context from functools im...
""" Utilities for interoperability with async functions and workers from various contexts. """ import asyncio import ctypes import inspect import threading import warnings from concurrent.futures import ThreadPoolExecutor from contextlib import asynccontextmanager from contextvars import copy_context from functools im...
5,944
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/dockerutils.py
355,356
196,393
assert_line_before
ImageBuilder
357,380
356,380
class ImageBuilder: """An interface for preparing Docker build contexts and building images""" base_directory: Path context: Optional[Path] platform: Optional[str] dockerfile_lines: List[str] def __init__( self, base_image: str, base_directory: Path = None, plat...
class ImageBuilder: """An interface for preparing Docker build contexts and building images""" base_directory: Path context: Optional[Path] platform: Optional[str] dockerfile_lines: List[str] def __init__( self, base_image: str, base_directory: Path = None, plat...
self.assert_has_line(first) self.assert_has_line(second) first_index = self.dockerfile_lines.index(first) second_index = self.dockerfile_lines.index(second) surrounding_lines = "\n".join( [ f" {i+1:>3}: {line}" for i, line in enumera...
"""Asserts that the first line appears before the second line""" self.assert_has_line(first) self.assert_has_line(second) first_index = self.dockerfile_lines.index(first) second_index = self.dockerfile_lines.index(second) surrounding_lines = "\n".join( [ ...
64
1,738
257
1,995
import hashlib import os import shutil import sys import warnings from contextlib import contextmanager from pathlib import Path, PurePosixPath from tempfile import TemporaryDirectory from types import TracebackType from typing import ( TYPE_CHECKING, Generator, Iterable, List, Optional, TextIO,...
import hashlib import os import shutil import sys import warnings from contextlib import contextmanager from pathlib import Path, PurePosixPath from tempfile import TemporaryDirectory from types import TracebackType from typing import ( TYPE_CHECKING, Generator, Iterable, List, Optional, TextIO,...
5,945
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/filesystem.py
58,60
1,148
tmpchdir
63,77
60,77
""" Utilities for working with file systems """ import os import pathlib import threading from contextlib import contextmanager from pathlib import Path, PureWindowsPath from typing import Union import fsspec import pathspec from fsspec.core import OpenFile from fsspec.implementations.local import LocalFileSystem imp...
""" Utilities for working with file systems """ import os import pathlib import threading from contextlib import contextmanager from pathlib import Path, PureWindowsPath from typing import Union import fsspec import pathspec from fsspec.core import OpenFile from fsspec.implementations.local import LocalFileSystem imp...
path = os.path.abspath(path) if os.path.isfile(path) or (not os.path.exists(path) and not path.endswith("/")): path = os.path.dirname(path) owd = os.getcwd() with chdir_lock: try: os.chdir(path) yield path finally: os.chdir(owd)
""" Change current-working directories for the duration of the context """ path = os.path.abspath(path) if os.path.isfile(path) or (not os.path.exists(path) and not path.endswith("/")): path = os.path.dirname(path) owd = os.getcwd() with chdir_lock: try: os.chdi...
25
1,230
128
1,358
""" Utilities for working with file systems """ import os import pathlib import threading from contextlib import contextmanager from pathlib import Path, PureWindowsPath from typing import Union import fsspec import pathspec from fsspec.core import OpenFile from fsspec.implementations.local import LocalFileSystem imp...
""" Utilities for working with file systems """ import os import pathlib import threading from contextlib import contextmanager from pathlib import Path, PureWindowsPath from typing import Union import fsspec import pathspec from fsspec.core import OpenFile from fsspec.implementations.local import LocalFileSystem imp...
5,946
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/hashing.py
37,38
1,68
file_hash
47,51
38,51
import hashlib import sys from functools import partial from pathlib import Path from typing import Optional, Union import cloudpickle from prefect.serializers import JSONSerializer if sys.version_info[:2] >= (3, 9): _md5 = partial(hashlib.md5, usedforsecurity=False) else: _md5 = hashlib.md5 def stable_has...
import hashlib import sys from functools import partial from pathlib import Path from typing import Optional, Union import cloudpickle from prefect.serializers import JSONSerializer if sys.version_info[:2] >= (3, 9): _md5 = partial(hashlib.md5, usedforsecurity=False) else: _md5 = hashlib.md5 def stable_has...
contents = Path(path).read_bytes() return stable_hash(contents, hash_algo=hash_algo)
"""Given a path to a file, produces a stable hash of the file contents. Args: path (str): the path to a file hash_algo: Hash algorithm from hashlib to use. Returns: str: a hash of the file contents """ contents = Path(path).read_bytes() return stable_hash(contents, hash...
6
544
37
581
import hashlib import sys from functools import partial from pathlib import Path from typing import Optional, Union import cloudpickle from prefect.serializers import JSONSerializer if sys.version_info[:2] >= (3, 9): _md5 = partial(hashlib.md5, usedforsecurity=False) else: _md5 = hashlib.md5 def stable_has...
import hashlib import sys from functools import partial from pathlib import Path from typing import Optional, Union import cloudpickle from prefect.serializers import JSONSerializer if sys.version_info[:2] >= (3, 9): _md5 = partial(hashlib.md5, usedforsecurity=False) else: _md5 = hashlib.md5 def stable_has...
5,947
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/math.py
41,42
1,73
clamped_poisson_interval
48,60
42,60
import math import random def poisson_interval(average_interval, lower=0, upper=1): """ Generates an "inter-arrival time" for a Poisson process. Draws a random variable from an exponential distribution using the inverse-CDF method. Can optionally be passed a lower and upper bound between (0, 1] to cl...
import math import random def poisson_interval(average_interval, lower=0, upper=1): """ Generates an "inter-arrival time" for a Poisson process. Draws a random variable from an exponential distribution using the inverse-CDF method. Can optionally be passed a lower and upper bound between (0, 1] to cl...
if clamping_factor <= 0: raise ValueError("`clamping_factor` must be >= 0.") upper_clamp_multiple = 1 + clamping_factor upper_bound = average_interval * upper_clamp_multiple lower_bound = max(0, average_interval * lower_clamp_multiple(upper_clamp_multiple)) upper_rv = exponential_cdf(upper...
""" Bounds Poisson "inter-arrival times" to a range defined by the clamping factor. The upper bound for this random variate is: average_interval * (1 + clamping_factor). A lower bound is picked so that the average interval remains approximately fixed. """ if clamping_factor <= 0: raise ...
38
684
168
852
import math import random def poisson_interval(average_interval, lower=0, upper=1): """ Generates an "inter-arrival time" for a Poisson process. Draws a random variable from an exponential distribution using the inverse-CDF method. Can optionally be passed a lower and upper bound between (0, 1] to cl...
import math import random def poisson_interval(average_interval, lower=0, upper=1): """ Generates an "inter-arrival time" for a Poisson process. Draws a random variable from an exponential distribution using the inverse-CDF method. Can optionally be passed a lower and upper bound between (0, 1] to cl...
5,948
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/names.py
55,56
1,73
obfuscate_string
67,73
56,73
from typing import Any import coolname OBFUSCATED_PREFIX = "****" IGNORE_LIST = { "sexy", "demonic", "kickass", "heretic", "godlike", "booby", "chubby", "gay", "sloppy", "funky", "juicy", "beaver", "curvy", "fat", "flashy", "flat", "thick", "nip...
from typing import Any import coolname OBFUSCATED_PREFIX = "****" IGNORE_LIST = { "sexy", "demonic", "kickass", "heretic", "godlike", "booby", "chubby", "gay", "sloppy", "funky", "juicy", "beaver", "curvy", "fat", "flashy", "flat", "thick", "nip...
result = OBFUSCATED_PREFIX + "*" * 4 # take up to 4 characters, but only after the 10th character suffix = s[10:][-4:] if suffix and show_tail: result = f"{result[:-len(suffix)]}{suffix}" return result
""" Obfuscates a string by returning a new string of 8 characters. If the input string is longer than 10 characters and show_tail is True, then up to 4 of its final characters will become final characters of the obfuscated string; all other characters are "*". "abc" -> "********" "abcd...
31
538
88
626
from typing import Any import coolname OBFUSCATED_PREFIX = "****" IGNORE_LIST = { "sexy", "demonic", "kickass", "heretic", "godlike", "booby", "chubby", "gay", "sloppy", "funky", "juicy", "beaver", "curvy", "fat", "flashy", "flat", "thick", "nip...
from typing import Any import coolname OBFUSCATED_PREFIX = "****" IGNORE_LIST = { "sexy", "demonic", "kickass", "heretic", "godlike", "booby", "chubby", "gay", "sloppy", "funky", "juicy", "beaver", "curvy", "fat", "flashy", "flat", "thick", "nip...
5,950
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/services.py
17,27
1,153
critical_service_loop
49,153
27,153
import sys from collections import deque from traceback import format_exception from types import TracebackType from typing import Callable, Coroutine, Deque, Tuple import anyio import httpx from prefect.logging.loggers import get_logger from prefect.utilities.collections import distinct from prefect.utilities.math i...
import sys from collections import deque from traceback import format_exception from types import TracebackType from typing import Callable, Coroutine, Deque, Tuple import anyio import httpx from prefect.logging.loggers import get_logger from prefect.utilities.collections import distinct from prefect.utilities.math i...
track_record: Deque[bool] = deque([True] * consecutive, maxlen=consecutive) failures: Deque[Tuple[Exception, TracebackType]] = deque(maxlen=memory) backoff_count = 0 while True: try: workload_display_name = ( workload.__name__ if hasattr(workload, "__name__") else w...
""" Runs the given `workload` function on the specified `interval`, while being forgiving of intermittent issues like temporary HTTP errors. If more than a certain number of `consecutive` errors occur, print a summary of up to `memory` recent exceptions to `printer`, then begin backoff. The lo...
503
509
1,263
1,772
import sys from collections import deque from traceback import format_exception from types import TracebackType from typing import Callable, Coroutine, Deque, Tuple import anyio import httpx from prefect.logging.loggers import get_logger from prefect.utilities.collections import distinct from prefect.utilities.math i...
import sys from collections import deque from traceback import format_exception from types import TracebackType from typing import Callable, Coroutine, Deque, Tuple import anyio import httpx from prefect.logging.loggers import get_logger from prefect.utilities.collections import distinct from prefect.utilities.math i...
5,951
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/text.py
4,5
1,20
truncated_to
5,20
5,20
from typing import Optional def truncated_to(length: int, value: Optional[str]) -> str: FILL_FUNC_BODY
from typing import Optional def truncated_to(length: int, value: Optional[str]) -> str: FILL_FUNC_BODY
if not value: return "" if len(value) <= length: return value half = length // 2 beginning = value[:half] end = value[-half:] omitted = len(value) - (len(beginning) + len(end)) proposed = f"{beginning}...{omitted} additional characters...{end}" return proposed if len...
if not value: return "" if len(value) <= length: return value half = length // 2 beginning = value[:half] end = value[-half:] omitted = len(value) - (len(beginning) + len(end)) proposed = f"{beginning}...{omitted} additional characters...{end}" return proposed if len...
42
38
126
164
from typing import Optional def truncated_to(length: int, value: Optional[str]) -> str: FILL_FUNC_BODY
from typing import Optional def truncated_to(length: int, value: Optional[str]) -> str: FILL_FUNC_BODY
5,952
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/timeout.py
11,13
1,27
timeout_async
13,20
13,20
from asyncio import CancelledError from contextlib import contextmanager from typing import Optional from prefect._internal.concurrency.cancellation import ( cancel_async_after, cancel_sync_after, ) @contextmanager def timeout_async(seconds: Optional[float] = None): FILL_FUNC_BODY@contextmanager def timeout(...
from asyncio import CancelledError from contextlib import contextmanager from typing import Optional from prefect._internal.concurrency.cancellation import ( cancel_async_after, cancel_sync_after, ) @contextmanager def timeout_async(seconds: Optional[float] = None): FILL_FUNC_BODY@contextmanager def timeout(...
try: with cancel_async_after(timeout=seconds): yield except CancelledError: raise TimeoutError(f"Scope timed out after {seconds} second(s).")
try: with cancel_async_after(timeout=seconds): yield except CancelledError: raise TimeoutError(f"Scope timed out after {seconds} second(s).")
13
153
59
212
from asyncio import CancelledError from contextlib import contextmanager from typing import Optional from prefect._internal.concurrency.cancellation import ( cancel_async_after, cancel_sync_after, ) @contextmanager def timeout_async(seconds: Optional[float] = None): FILL_FUNC_BODY@contextmanager def timeout(...
from asyncio import CancelledError from contextlib import contextmanager from typing import Optional from prefect._internal.concurrency.cancellation import ( cancel_async_after, cancel_sync_after, ) @contextmanager def timeout_async(seconds: Optional[float] = None): FILL_FUNC_BODY@contextmanager def timeout(...
5,953
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/visualization.py
36,42
1,202
track_viz_task
43,51
42,51
""" Utilities for working with Flow.visualize() """ from functools import partial from typing import Any, List, Optional import graphviz from prefect._internal.concurrency.api import from_async class FlowVisualizationError(Exception): pass class VisualizationUnsupportedError(Exception): pass class TaskV...
""" Utilities for working with Flow.visualize() """ from functools import partial from typing import Any, List, Optional import graphviz from prefect._internal.concurrency.api import from_async class FlowVisualizationError(Exception): pass class VisualizationUnsupportedError(Exception): pass class TaskV...
if is_async: return from_async.wait_for_call_in_loop_thread( partial(_track_viz_task, task_name, parameters, viz_return_value) ) else: return _track_viz_task(task_name, parameters, viz_return_value)
"""Return a result if sync otherwise return a coroutine that returns the result""" if is_async: return from_async.wait_for_call_in_loop_thread( partial(_track_viz_task, task_name, parameters, viz_return_value) ) else: return _track_viz_task(task_name, parameters, viz_retu...
14
1,894
91
1,985
""" Utilities for working with Flow.visualize() """ from functools import partial from typing import Any, List, Optional import graphviz from prefect._internal.concurrency.api import from_async class FlowVisualizationError(Exception): pass class VisualizationUnsupportedError(Exception): pass class TaskV...
""" Utilities for working with Flow.visualize() """ from functools import partial from typing import Any, List, Optional import graphviz from prefect._internal.concurrency.api import from_async class FlowVisualizationError(Exception): pass class VisualizationUnsupportedError(Exception): pass class TaskV...
5,954
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/utilities/visualization.py
115,118
93,131
link_viz_return_value_to_viz_task
TaskVizTracker
122,131
118,131
class TaskVizTracker: def __init__(self): self.tasks = [] self.dynamic_task_counter = {} self.object_id_to_task = {} def add_task(self, task: VizTask): if task.name not in self.dynamic_task_counter: self.dynamic_task_counter[task.name] = 0 else: s...
class TaskVizTracker: def __init__(self): self.tasks = [] self.dynamic_task_counter = {} self.object_id_to_task = {} def add_task(self, task: VizTask): if task.name not in self.dynamic_task_counter: self.dynamic_task_counter[task.name] = 0 else: s...
from prefect.utilities.engine import UNTRACKABLE_TYPES if (type(viz_return_value) in UNTRACKABLE_TYPES) or ( isinstance(viz_return_value, int) and (-5 <= viz_return_value <= 256) ): return self.object_id_to_task[id(viz_return_value)] = viz_task
""" We cannot track booleans, Ellipsis, None, NotImplemented, or the integers from -5 to 256 because they are singletons. """ from prefect.utilities.engine import UNTRACKABLE_TYPES if (type(viz_return_value) in UNTRACKABLE_TYPES) or ( isinstance(viz_return_va...
23
317
118
435
""" Utilities for working with Flow.visualize() """ from functools import partial from typing import Any, List, Optional import graphviz from prefect._internal.concurrency.api import from_async class FlowVisualizationError(Exception): pass class VisualizationUnsupportedError(Exception): pass class TaskV...
""" Utilities for working with Flow.visualize() """ from functools import partial from typing import Any, List, Optional import graphviz from prefect._internal.concurrency.api import from_async class FlowVisualizationError(Exception): pass class VisualizationUnsupportedError(Exception): pass class TaskV...
5,955
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/variables.py
92,95
1,115
get
113,115
95,115
from typing import List, Optional from prefect._internal.compatibility.deprecated import deprecated_callable from prefect.client.schemas.actions import VariableCreate as VariableRequest from prefect.client.schemas.actions import VariableUpdate as VariableUpdateRequest from prefect.client.utilities import get_or_create...
from typing import List, Optional from prefect._internal.compatibility.deprecated import deprecated_callable from prefect.client.schemas.actions import VariableCreate as VariableRequest from prefect.client.schemas.actions import VariableUpdate as VariableUpdateRequest from prefect.client.utilities import get_or_create...
variable = await Variable.get(name) return variable.value if variable else default
""" Get a variable by name. If doesn't exist return the default. ``` from prefect import variables @flow def my_flow(): var = variables.get("my_var") ``` or ``` from prefect import variables @flow async def my_flow(): var ...
10
1,004
24
1,028
from typing import List, Optional from prefect._internal.compatibility.deprecated import deprecated_callable from prefect.client.schemas.actions import VariableCreate as VariableRequest from prefect.client.schemas.actions import VariableUpdate as VariableUpdateRequest from prefect.client.utilities import get_or_create...
from typing import List, Optional from prefect._internal.compatibility.deprecated import deprecated_callable from prefect.client.schemas.actions import VariableCreate as VariableRequest from prefect.client.schemas.actions import VariableUpdate as VariableUpdateRequest from prefect.client.utilities import get_or_create...
5,956
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/variables.py
21,30
10,92
set
Variable
48,66
30,66
class Variable(VariableRequest): """ Variables are named, mutable string values, much like environment variables. Variables are scoped to a Prefect server instance or a single workspace in Prefect Cloud. https://docs.prefect.io/latest/concepts/variables/ Arguments: name: A string identifying th...
class Variable(VariableRequest): """ Variables are named, mutable string values, much like environment variables. Variables are scoped to a Prefect server instance or a single workspace in Prefect Cloud. https://docs.prefect.io/latest/concepts/variables/ Arguments: name: A string identifying th...
client, _ = get_or_create_client() variable = await client.read_variable_by_name(name) var_dict = {"name": name, "value": value} var_dict["tags"] = tags or [] if variable: if not overwrite: raise ValueError( "You are attempting to s...
""" Sets a new variable. If one exists with the same name, user must pass `overwrite=True` ``` from prefect.variables import Variable @flow def my_flow(): var = Variable.set(name="my_var",value="test_value", tags=["hi", "there"], overwrite=Tru...
81
549
228
777
from typing import List, Optional from prefect._internal.compatibility.deprecated import deprecated_callable from prefect.client.schemas.actions import VariableCreate as VariableRequest from prefect.client.schemas.actions import VariableUpdate as VariableUpdateRequest from prefect.client.utilities import get_or_create...
from typing import List, Optional from prefect._internal.compatibility.deprecated import deprecated_callable from prefect.client.schemas.actions import VariableCreate as VariableRequest from prefect.client.schemas.actions import VariableUpdate as VariableUpdateRequest from prefect.client.utilities import get_or_create...
5,957
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/workers/server.py
15,20
1,52
start_healthcheck_server
27,52
20,52
from typing import Union import uvicorn from prefect._vendor.fastapi import APIRouter, FastAPI, status from prefect._vendor.fastapi.responses import JSONResponse from prefect.settings import ( PREFECT_WORKER_WEBSERVER_HOST, PREFECT_WORKER_WEBSERVER_PORT, ) from prefect.workers.base import BaseWorker from pref...
from typing import Union import uvicorn from prefect._vendor.fastapi import APIRouter, FastAPI, status from prefect._vendor.fastapi.responses import JSONResponse from prefect.settings import ( PREFECT_WORKER_WEBSERVER_HOST, PREFECT_WORKER_WEBSERVER_PORT, ) from prefect.workers.base import BaseWorker from pref...
webserver = FastAPI() router = APIRouter() def perform_health_check(): did_recently_poll = worker.is_worker_still_polling( query_interval_seconds=query_interval_seconds ) if not did_recently_poll: return JSONResponse( status_code=status.HTTP_...
""" Run a healthcheck FastAPI server for a worker. Args: worker (BaseWorker | ProcessWorker): the worker whose health we will check log_level (str): the log level to use for the server """ webserver = FastAPI() router = APIRouter() def perform_health_check(): did_re...
42
239
290
529
from typing import Union import uvicorn from prefect._vendor.fastapi import APIRouter, FastAPI, status from prefect._vendor.fastapi.responses import JSONResponse from prefect.settings import ( PREFECT_WORKER_WEBSERVER_HOST, PREFECT_WORKER_WEBSERVER_PORT, ) from prefect.workers.base import BaseWorker from pref...
from typing import Union import uvicorn from prefect._vendor.fastapi import APIRouter, FastAPI, status from prefect._vendor.fastapi.responses import JSONResponse from prefect.settings import ( PREFECT_WORKER_WEBSERVER_HOST, PREFECT_WORKER_WEBSERVER_PORT, ) from prefect.workers.base import BaseWorker from pref...
5,958
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect
/home/hieuvd/dung_repo/raw/stars_01/PrefectHQ_prefect/prefect/src/prefect/workers/utilities.py
32,35
1,60
get_default_base_job_template_for_infrastructure_type
35,60
35,60
from copy import deepcopy from logging import getLogger from typing import Any, Dict, List, Optional from prefect.client.collections import get_collections_metadata_client from prefect.logging.loggers import get_logger from prefect.settings import PREFECT_DEBUG_MODE from prefect.workers.base import BaseWorker async ...
from copy import deepcopy from logging import getLogger from typing import Any, Dict, List, Optional from prefect.client.collections import get_collections_metadata_client from prefect.logging.loggers import get_logger from prefect.settings import PREFECT_DEBUG_MODE from prefect.workers.base import BaseWorker async ...
# Attempt to get the default base job template for the worker type # from the local type registry first. worker_cls = BaseWorker.get_worker_class_from_type(infra_type) if worker_cls is not None: return deepcopy(worker_cls.get_default_base_job_template()) # If the worker type is not found in...
# Attempt to get the default base job template for the worker type # from the local type registry first. worker_cls = BaseWorker.get_worker_class_from_type(infra_type) if worker_cls is not None: return deepcopy(worker_cls.get_default_base_job_template()) # If the worker type is not found in...
103
348
300
648
from copy import deepcopy from logging import getLogger from typing import Any, Dict, List, Optional from prefect.client.collections import get_collections_metadata_client from prefect.logging.loggers import get_logger from prefect.settings import PREFECT_DEBUG_MODE from prefect.workers.base import BaseWorker async ...
from copy import deepcopy from logging import getLogger from typing import Any, Dict, List, Optional from prefect.client.collections import get_collections_metadata_client from prefect.logging.loggers import get_logger from prefect.settings import PREFECT_DEBUG_MODE from prefect.workers.base import BaseWorker async ...
5,983
/home/hieuvd/dung_repo/raw/stars_01/QwenLM_Qwen/Qwen
/home/hieuvd/dung_repo/raw/stars_01/QwenLM_Qwen/Qwen/examples/auto_comments.py
38,39
21,49
chat
QWenChat
39,49
39,49
class QWenChat(): def __init__(self): self.tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-7B-Chat", trust_remote_code=True) # use bf16 # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, bf16=True).eval() # use fp16 ...
class QWenChat(): def __init__(self): self.tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-7B-Chat", trust_remote_code=True) # use bf16 # model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, bf16=True).eval() # use fp16 ...
# use history # response, history = self.model.chat(self.tokenizer, query, history=self.history) # 默认不使用history response, history = self.model.chat(self.tokenizer, query, history=None) self.history = history return response # 生成注释
# use history # response, history = self.model.chat(self.tokenizer, query, history=self.history) # 默认不使用history response, history = self.model.chat(self.tokenizer, query, history=None) self.history = history return response # 生成注释
25
370
94
464
# 运行方式:python auto_comments.py --path 'path of file or folder' # 脚本功能:使用QWen-7B-Chat为提供的代码文件自动生成注释。(详见auto_comments.md) import argparse import os from transformers import AutoModelForCausalLM, AutoTokenizer from transformers.generation import GenerationConfig MaxLine = 50 # 限制单次处理最大代码行数 SplitKey = ["\ndef "] # 自定义的切...
# 运行方式:python auto_comments.py --path 'path of file or folder' # 脚本功能:使用QWen-7B-Chat为提供的代码文件自动生成注释。(详见auto_comments.md) import argparse import os from transformers import AutoModelForCausalLM, AutoTokenizer from transformers.generation import GenerationConfig MaxLine = 50 # 限制单次处理最大代码行数 SplitKey = ["\ndef "] # 自定义的切...
5,985
/home/hieuvd/dung_repo/raw/stars_01/QwenLM_Qwen/Qwen
/home/hieuvd/dung_repo/raw/stars_01/QwenLM_Qwen/Qwen/utils.py
6,7
1,45
_device_map
7,28
7,28
import torch from transformers import AutoModelForCausalLM from accelerate import dispatch_model def _device_map(num_gpus, num_layers): FILL_FUNC_BODYdef load_model_on_gpus(model_name_or_path, num_gpus: int = 2): num_devices = torch.cuda.device_count() if num_gpus == 1: model = AutoModelForCausalLM.f...
import torch from transformers import AutoModelForCausalLM from accelerate import dispatch_model def _device_map(num_gpus, num_layers): FILL_FUNC_BODYdef load_model_on_gpus(model_name_or_path, num_gpus: int = 2): num_devices = torch.cuda.device_count() if num_gpus == 1: model = AutoModelForCausalLM.f...
per_gpu_layers = (num_layers + 2) / num_gpus device_map = { 'transformer.wte': 0, 'transformer.ln_f': 0, 'lm_head': num_gpus-1 } used = 1 gpu_target = 0 for i in range(num_layers): if used >= per_gpu_layers: gpu_target += 1 used = 0 if gp...
per_gpu_layers = (num_layers + 2) / num_gpus device_map = { 'transformer.wte': 0, 'transformer.ln_f': 0, 'lm_head': num_gpus-1 } used = 1 gpu_target = 0 for i in range(num_layers): if used >= per_gpu_layers: gpu_target += 1 used = 0 if gp...
55
287
202
489
import torch from transformers import AutoModelForCausalLM from accelerate import dispatch_model def _device_map(num_gpus, num_layers): FILL_FUNC_BODYdef load_model_on_gpus(model_name_or_path, num_gpus: int = 2): num_devices = torch.cuda.device_count() if num_gpus == 1: model = AutoModelForCausalLM.f...
import torch from transformers import AutoModelForCausalLM from accelerate import dispatch_model def _device_map(num_gpus, num_layers): FILL_FUNC_BODYdef load_model_on_gpus(model_name_or_path, num_gpus: int = 2): num_devices = torch.cuda.device_count() if num_gpus == 1: model = AutoModelForCausalLM.f...
6,070
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/i18n/i18n.py
6,7
1,28
load_language_list
7,12
7,12
import json import locale import os def load_language_list(language): FILL_FUNC_BODYclass I18nAuto: def __init__(self, language=None): if language in ["Auto", None]: language = locale.getdefaultlocale()[ 0 ] # getlocale can't identify the system's language ((None, ...
import json import locale import os def load_language_list(language): FILL_FUNC_BODYclass I18nAuto: def __init__(self, language=None): if language in ["Auto", None]: language = locale.getdefaultlocale()[ 0 ] # getlocale can't identify the system's language ((None, ...
with open(f"./i18n/locale/{language}.json", "r", encoding="utf-8") as f: language_list = json.load(f) return language_list
with open(f"./i18n/locale/{language}.json", "r", encoding="utf-8") as f: language_list = json.load(f) return language_list
11
201
57
258
import json import locale import os def load_language_list(language): FILL_FUNC_BODYclass I18nAuto: def __init__(self, language=None): if language in ["Auto", None]: language = locale.getdefaultlocale()[ 0 ] # getlocale can't identify the system's language ((None, ...
import json import locale import os def load_language_list(language): FILL_FUNC_BODYclass I18nAuto: def __init__(self, language=None): if language in ["Auto", None]: language = locale.getdefaultlocale()[ 0 ] # getlocale can't identify the system's language ((None, ...
6,071
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/i18n/scan_i18n.py
7,8
1,76
extract_i18n_strings
8,29
8,29
import ast import glob import json from collections import OrderedDict def extract_i18n_strings(node): FILL_FUNC_BODYstrings = [] for filename in glob.iglob("**/*.py", recursive=True): with open(filename, "r") as f: code = f.read() if "I18nAuto" in code: tree = ast.parse(code) ...
import ast import glob import json from collections import OrderedDict def extract_i18n_strings(node): FILL_FUNC_BODYstrings = [] for filename in glob.iglob("**/*.py", recursive=True): with open(filename, "r") as f: code = f.read() if "I18nAuto" in code: tree = ast.parse(code) ...
i18n_strings = [] if ( isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "i18n" ): for arg in node.args: if isinstance(arg, ast.Str): i18n_strings.append(arg.s) for child_node in ast.iter_child_nodes(node): ...
i18n_strings = [] if ( isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "i18n" ): for arg in node.args: if isinstance(arg, ast.Str): i18n_strings.append(arg.s) for child_node in ast.iter_child_nodes(node): ...
57
539
214
753
import ast import glob import json from collections import OrderedDict def extract_i18n_strings(node): FILL_FUNC_BODYstrings = [] for filename in glob.iglob("**/*.py", recursive=True): with open(filename, "r") as f: code = f.read() if "I18nAuto" in code: tree = ast.parse(code) ...
import ast import glob import json from collections import OrderedDict def extract_i18n_strings(node): FILL_FUNC_BODYstrings = [] for filename in glob.iglob("**/*.py", recursive=True): with open(filename, "r") as f: code = f.read() if "I18nAuto" in code: tree = ast.parse(code) ...
6,072
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/audio.py
30,31
1,51
load_audio
31,47
31,47
import platform import ffmpeg import numpy as np import av def wav2(i, o, format): inp = av.open(i, "r") if format == "m4a": format = "mp4" out = av.open(o, "w", format=format) if format == "ogg": format = "libvorbis" if format == "mp4": format = "aac" ostream = out.ad...
import platform import ffmpeg import numpy as np import av def wav2(i, o, format): inp = av.open(i, "r") if format == "m4a": format = "mp4" out = av.open(o, "w", format=format) if format == "ogg": format = "libvorbis" if format == "mp4": format = "aac" ostream = out.ad...
try: # https://github.com/openai/whisper/blob/main/whisper/audio.py#L26 # This launches a subprocess to decode audio while down-mixing and resampling as necessary. # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed. file = clean_path(file) # 防止小白拷路径头尾带了空格和"和回车 ...
try: # https://github.com/openai/whisper/blob/main/whisper/audio.py#L26 # This launches a subprocess to decode audio while down-mixing and resampling as necessary. # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed. file = clean_path(file) # 防止小白拷路径头尾带了空格和"和回车 ...
62
287
268
555
import platform import ffmpeg import numpy as np import av def wav2(i, o, format): inp = av.open(i, "r") if format == "m4a": format = "mp4" out = av.open(o, "w", format=format) if format == "ogg": format = "libvorbis" if format == "mp4": format = "aac" ostream = out.ad...
import platform import ffmpeg import numpy as np import av def wav2(i, o, format): inp = av.open(i, "r") if format == "m4a": format = "mp4" out = av.open(o, "w", format=format) if format == "ogg": format = "libvorbis" if format == "mp4": format = "aac" ostream = out.ad...
6,073
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/attentions.py
140,141
80,166
forward
Decoder
145,166
141,166
class Decoder(nn.Module): def __init__( self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0.0, proximal_bias=False, proximal_init=True, **kwargs ): super(Decoder, self).__init__() se...
class Decoder(nn.Module): def __init__( self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0.0, proximal_bias=False, proximal_init=True, **kwargs ): super(Decoder, self).__init__() se...
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to( device=x.device, dtype=x.dtype ) encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) x = x * x_mask for i in range(self.n_layers): y = self.self_attn_layers[i](x, x, self_attn_mask) ...
""" x: decoder input h: encoder output """ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to( device=x.device, dtype=x.dtype ) encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) x = x * x_mask for i in range(self.n_...
65
661
296
957
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
6,074
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/attentions.py
62,63
14,80
forward
Encoder
63,80
63,80
class Encoder(nn.Module): def __init__( self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0.0, window_size=10, **kwargs ): super(Encoder, self).__init__() self.hidden_channels = hidden_chann...
class Encoder(nn.Module): def __init__( self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0.0, window_size=10, **kwargs ): super(Encoder, self).__init__() self.hidden_channels = hidden_chann...
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) x = x * x_mask zippep = zip( self.attn_layers, self.norm_layers_1, self.ffn_layers, self.norm_layers_2 ) for attn_layers, norm_layers_1, ffn_layers, norm_layers_2 in zippep: y = attn_layers(x, x, attn_...
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) x = x * x_mask zippep = zip( self.attn_layers, self.norm_layers_1, self.ffn_layers, self.norm_layers_2 ) for attn_layers, norm_layers_1, ffn_layers, norm_layers_2 in zippep: y = attn_layers(x, x, attn_...
57
468
224
692
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
6,075
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/attentions.py
435,436
388,460
_causal_padding
FFN
436,448
436,448
class FFN(nn.Module): def __init__( self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0.0, activation: str = None, causal=False, ): super(FFN, self).__init__() self.in_channels = in_channels self.out_c...
class FFN(nn.Module): def __init__( self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0.0, activation: str = None, causal=False, ): super(FFN, self).__init__() self.in_channels = in_channels self.out_c...
if self.kernel_size == 1: return x pad_l: int = self.kernel_size - 1 pad_r: int = 0 # padding = [[0, 0], [0, 0], [pad_l, pad_r]] x = F.pad( x, # commons.convert_pad_shape(padding) [pad_l, pad_r, 0, 0, 0, 0], ) retu...
if self.kernel_size == 1: return x pad_l: int = self.kernel_size - 1 pad_r: int = 0 # padding = [[0, 0], [0, 0], [pad_l, pad_r]] x = F.pad( x, # commons.convert_pad_shape(padding) [pad_l, pad_r, 0, 0, 0, 0], ) retu...
40
697
136
833
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
6,077
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/attentions_onnx.py
140,141
80,166
forward
Decoder
145,166
141,166
class Decoder(nn.Module): def __init__( self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0.0, proximal_bias=False, proximal_init=True, **kwargs ): super(Decoder, self).__init__() se...
class Decoder(nn.Module): def __init__( self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0.0, proximal_bias=False, proximal_init=True, **kwargs ): super(Decoder, self).__init__() se...
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to( device=x.device, dtype=x.dtype ) encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) x = x * x_mask for i in range(self.n_layers): y = self.self_attn_layers[i](x, x, self_attn_mask) ...
""" x: decoder input h: encoder output """ self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to( device=x.device, dtype=x.dtype ) encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) x = x * x_mask for i in range(self.n_...
65
661
296
957
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
6,078
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/attentions_onnx.py
62,63
14,80
forward
Encoder
63,80
63,80
class Encoder(nn.Module): def __init__( self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0.0, window_size=10, **kwargs ): super(Encoder, self).__init__() self.hidden_channels = hidden_chann...
class Encoder(nn.Module): def __init__( self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0.0, window_size=10, **kwargs ): super(Encoder, self).__init__() self.hidden_channels = hidden_chann...
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) x = x * x_mask zippep = zip( self.attn_layers, self.norm_layers_1, self.ffn_layers, self.norm_layers_2 ) for attn_layers, norm_layers_1, ffn_layers, norm_layers_2 in zippep: y = attn_layers(x, x, attn_...
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) x = x * x_mask zippep = zip( self.attn_layers, self.norm_layers_1, self.ffn_layers, self.norm_layers_2 ) for attn_layers, norm_layers_1, ffn_layers, norm_layers_2 in zippep: y = attn_layers(x, x, attn_...
57
468
224
692
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
6,079
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/attentions_onnx.py
424,425
388,460
forward
FFN
425,435
425,435
class FFN(nn.Module): def __init__( self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0.0, activation: str = None, causal=False, ): super(FFN, self).__init__() self.in_channels = in_channels self.out_c...
class FFN(nn.Module): def __init__( self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0.0, activation: str = None, causal=False, ): super(FFN, self).__init__() self.in_channels = in_channels self.out_c...
x = self.conv_1(self.padding(x, x_mask)) if self.is_activation: x = x * torch.sigmoid(1.702 * x) else: x = torch.relu(x) x = self.drop(x) x = self.conv_2(self.padding(x, x_mask)) return x * x_mask
x = self.conv_1(self.padding(x, x_mask)) if self.is_activation: x = x * torch.sigmoid(1.702 * x) else: x = torch.relu(x) x = self.drop(x) x = self.conv_2(self.padding(x, x_mask)) return x * x_mask
28
714
117
831
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
import copy import math from typing import Optional import numpy as np import torch from torch import nn from torch.nn import functional as F from infer.lib.infer_pack import commons, modules from infer.lib.infer_pack.modules import LayerNorm class Encoder(nn.Module): def __init__( self, hidden_...
6,082
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models.py
1218,1219
1161,1243
forward
DiscriminatorP
1219,1243
1219,1243
class DiscriminatorP(torch.nn.Module): def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): super(DiscriminatorP, self).__init__() self.period = period self.use_spectral_norm = use_spectral_norm norm_f = weight_norm if use_spectral_norm == False else spectral...
class DiscriminatorP(torch.nn.Module): def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): super(DiscriminatorP, self).__init__() self.period = period self.use_spectral_norm = use_spectral_norm norm_f = weight_norm if use_spectral_norm == False else spectral...
fmap = [] # 1d to 2d b, c, t = x.shape if t % self.period != 0: # pad first n_pad = self.period - (t % self.period) if has_xpu and x.dtype == torch.bfloat16: x = F.pad(x.to(dtype=torch.float16), (0, n_pad), "reflect").to( dtyp...
fmap = [] # 1d to 2d b, c, t = x.shape if t % self.period != 0: # pad first n_pad = self.period - (t % self.period) if has_xpu and x.dtype == torch.bfloat16: x = F.pad(x.to(dtype=torch.float16), (0, n_pad), "reflect").to( dtyp...
86
530
312
842
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,083
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models.py
1147,1148
1131,1161
forward
DiscriminatorS
1148,1161
1148,1161
class DiscriminatorS(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(DiscriminatorS, self).__init__() norm_f = weight_norm if use_spectral_norm == False else spectral_norm self.convs = nn.ModuleList( [ norm_f(Conv1d(1, 16, 15, 1, padding=7)), ...
class DiscriminatorS(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(DiscriminatorS, self).__init__() norm_f = weight_norm if use_spectral_norm == False else spectral_norm self.convs = nn.ModuleList( [ norm_f(Conv1d(1, 16, 15, 1, padding=7)), ...
fmap = [] for l in self.convs: x = l(x) x = F.leaky_relu(x, modules.LRELU_SLOPE) fmap.append(x) x = self.conv_post(x) fmap.append(x) x = torch.flatten(x, 1, -1) return x, fmap
fmap = [] for l in self.convs: x = l(x) x = F.leaky_relu(x, modules.LRELU_SLOPE) fmap.append(x) x = self.conv_post(x) fmap.append(x) x = torch.flatten(x, 1, -1) return x, fmap
27
355
121
476
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,084
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models.py
252,258
204,312
forward
Generator
258,283
258,283
class Generator(torch.nn.Module): def __init__( self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0, ): super(Generator, se...
class Generator(torch.nn.Module): def __init__( self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels=0, ): super(Generator, se...
if n_res is not None: assert isinstance(n_res, torch.Tensor) n = int(n_res.item()) if n != x.shape[-1]: x = F.interpolate(x, size=n, mode="linear") x = self.conv_pre(x) if g is not None: x = x + self.cond(g) for i in range(...
if n_res is not None: assert isinstance(n_res, torch.Tensor) n = int(n_res.item()) if n != x.shape[-1]: x = F.interpolate(x, size=n, mode="linear") x = self.conv_pre(x) if g is not None: x = x + self.cond(g) for i in range(...
86
948
315
1,263
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,085
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models.py
541,548
467,614
forward
GeneratorNSF
548,586
548,586
class GeneratorNSF(torch.nn.Module): def __init__( self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels, sr, is_half=False...
class GeneratorNSF(torch.nn.Module): def __init__( self, initial_channel, resblock, resblock_kernel_sizes, resblock_dilation_sizes, upsample_rates, upsample_initial_channel, upsample_kernel_sizes, gin_channels, sr, is_half=False...
har_source, noi_source, uv = self.m_source(f0, self.upp) har_source = har_source.transpose(1, 2) if n_res is not None: assert isinstance(n_res, torch.Tensor) n = int(n_res.item()) if n * self.upp != har_source.shape[-1]: har_source = F.interpol...
har_source, noi_source, uv = self.m_source(f0, self.upp) har_source = har_source.transpose(1, 2) if n_res is not None: assert isinstance(n_res, torch.Tensor) n = int(n_res.item()) if n * self.upp != har_source.shape[-1]: har_source = F.interpol...
168
1,252
564
1,816
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
6,086
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI
/home/hieuvd/dung_repo/raw/stars_01/RVC-Project_Retrieval-based-Voice-Conversion-WebUI/Retrieval-based-Voice-Conversion-WebUI/infer/lib/infer_pack/models.py
1083,1084
1071,1101
forward
MultiPeriodDiscriminator
1084,1101
1084,1101
class MultiPeriodDiscriminator(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(MultiPeriodDiscriminator, self).__init__() periods = [2, 3, 5, 7, 11, 17] # periods = [3, 5, 7, 11, 17, 23, 37] discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] d...
class MultiPeriodDiscriminator(torch.nn.Module): def __init__(self, use_spectral_norm=False): super(MultiPeriodDiscriminator, self).__init__() periods = [2, 3, 5, 7, 11, 17] # periods = [3, 5, 7, 11, 17, 23, 37] discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] d...
y_d_rs = [] # y_d_gs = [] fmap_rs = [] fmap_gs = [] for i, d in enumerate(self.discriminators): y_d_r, fmap_r = d(y) y_d_g, fmap_g = d(y_hat) # for j in range(len(fmap_r)): # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g...
y_d_rs = [] # y_d_gs = [] fmap_rs = [] fmap_gs = [] for i, d in enumerate(self.discriminators): y_d_r, fmap_r = d(y) y_d_g, fmap_g = d(y_hat) # for j in range(len(fmap_r)): # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g...
42
213
247
460
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...
import math import logging from typing import Optional logger = logging.getLogger(__name__) import numpy as np import torch from torch import nn from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn import functional as F from torch.nn.utils import remove_weight_norm, spectral_norm, weight_nor...