id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
154,638
from chromadb.api import ServerAPI from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System from chromadb.db.system import SysDB from chromadb.quota import QuotaEnforcer, Resource from chromadb.rate_limiting import rate_limit from chromadb.segment import SegmentManager, MetadataReader, VectorReader from chromadb.telemetry.opentelemetry import ( add_attributes_to_current_span, OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) from chromadb.telemetry.product import ProductTelemetryClient from chromadb.ingest import Producer from chromadb.api.models.Collection import Collection from chromadb import __version__ from chromadb.errors import InvalidDimensionException, InvalidCollectionException import chromadb.utils.embedding_functions as ef from chromadb.api.types import ( URI, CollectionMetadata, Embeddable, Document, EmbeddingFunction, DataLoader, IDs, Embeddings, Embedding, Loadable, Metadatas, Documents, URIs, Where, WhereDocument, Include, GetResult, QueryResult, validate_metadata, validate_update_metadata, validate_where, validate_where_document, validate_batch, ) from chromadb.telemetry.product.events import ( CollectionAddEvent, CollectionDeleteEvent, CollectionGetEvent, CollectionUpdateEvent, CollectionQueryEvent, ClientCreateCollectionEvent, ) import chromadb.types as t from typing import Any, Optional, Sequence, Generator, List, cast, Set, Dict from overrides import override from uuid import UUID, uuid4 import time import logging import re The provided code snippet includes necessary dependencies for implementing the `_uri` function. Write a Python function `def _uri(metadata: Optional[t.Metadata]) -> Optional[str]` to solve the following problem: Retrieve the uri (if any) from a Metadata map Here is the function: def _uri(metadata: Optional[t.Metadata]) -> Optional[str]: """Retrieve the uri (if any) from a Metadata map""" if metadata and "chroma:uri" in metadata: return str(metadata["chroma:uri"]) return None
Retrieve the uri (if any) from a Metadata map
154,639
from chromadb.api import ServerAPI from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System from chromadb.db.system import SysDB from chromadb.quota import QuotaEnforcer, Resource from chromadb.rate_limiting import rate_limit from chromadb.segment import SegmentManager, MetadataReader, VectorReader from chromadb.telemetry.opentelemetry import ( add_attributes_to_current_span, OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) from chromadb.telemetry.product import ProductTelemetryClient from chromadb.ingest import Producer from chromadb.api.models.Collection import Collection from chromadb import __version__ from chromadb.errors import InvalidDimensionException, InvalidCollectionException import chromadb.utils.embedding_functions as ef from chromadb.api.types import ( URI, CollectionMetadata, Embeddable, Document, EmbeddingFunction, DataLoader, IDs, Embeddings, Embedding, Loadable, Metadatas, Documents, URIs, Where, WhereDocument, Include, GetResult, QueryResult, validate_metadata, validate_update_metadata, validate_where, validate_where_document, validate_batch, ) from chromadb.telemetry.product.events import ( CollectionAddEvent, CollectionDeleteEvent, CollectionGetEvent, CollectionUpdateEvent, CollectionQueryEvent, ClientCreateCollectionEvent, ) import chromadb.types as t from typing import Any, Optional, Sequence, Generator, List, cast, Set, Dict from overrides import override from uuid import UUID, uuid4 import time import logging import re def _clean_metadata(metadata: Optional[t.Metadata]) -> Optional[t.Metadata]: """Remove any chroma-specific metadata keys that the client shouldn't see from a metadata map.""" if not metadata: return None result = {} for k, v in metadata.items(): if not k.startswith("chroma:"): result[k] = v if len(result) == 0: return None return result The provided code snippet includes necessary dependencies for implementing the `_clean_metadatas` function. Write a Python function `def _clean_metadatas( metadata: List[Optional[t.Metadata]], ) -> List[Optional[t.Metadata]]` to solve the following problem: Remove any chroma-specific metadata keys that the client shouldn't see from a list of metadata maps. Here is the function: def _clean_metadatas( metadata: List[Optional[t.Metadata]], ) -> List[Optional[t.Metadata]]: """Remove any chroma-specific metadata keys that the client shouldn't see from a list of metadata maps.""" return [_clean_metadata(m) for m in metadata]
Remove any chroma-specific metadata keys that the client shouldn't see from a list of metadata maps.
154,640
from typing import Optional, Sequence, Any, Tuple, cast, Generator, Union, Dict, List from chromadb.segment import MetadataReader from chromadb.ingest import Consumer from chromadb.config import System from chromadb.types import Segment, InclusionExclusionOperator from chromadb.db.impl.sqlite import SqliteDB from overrides import override from chromadb.db.base import ( Cursor, ParameterValue, get_sql, ) from chromadb.telemetry.opentelemetry import ( OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) from chromadb.types import ( Where, WhereDocument, MetadataEmbeddingRecord, EmbeddingRecord, SeqId, Operation, UpdateMetadata, LiteralValue, WhereOperator, ) from uuid import UUID from pypika import Table, Tables from pypika.queries import QueryBuilder import pypika.functions as fn from pypika.terms import Criterion from itertools import groupby from functools import reduce import sqlite3 import logging SeqId = int The provided code snippet includes necessary dependencies for implementing the `_encode_seq_id` function. Write a Python function `def _encode_seq_id(seq_id: SeqId) -> bytes` to solve the following problem: Encode a SeqID into a byte array Here is the function: def _encode_seq_id(seq_id: SeqId) -> bytes: """Encode a SeqID into a byte array""" if seq_id.bit_length() <= 64: return int.to_bytes(seq_id, 8, "big") elif seq_id.bit_length() <= 192: return int.to_bytes(seq_id, 24, "big") else: raise ValueError(f"Unsupported SeqID: {seq_id}")
Encode a SeqID into a byte array
154,641
from typing import Optional, Sequence, Any, Tuple, cast, Generator, Union, Dict, List from chromadb.segment import MetadataReader from chromadb.ingest import Consumer from chromadb.config import System from chromadb.types import Segment, InclusionExclusionOperator from chromadb.db.impl.sqlite import SqliteDB from overrides import override from chromadb.db.base import ( Cursor, ParameterValue, get_sql, ) from chromadb.telemetry.opentelemetry import ( OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) from chromadb.types import ( Where, WhereDocument, MetadataEmbeddingRecord, EmbeddingRecord, SeqId, Operation, UpdateMetadata, LiteralValue, WhereOperator, ) from uuid import UUID from pypika import Table, Tables from pypika.queries import QueryBuilder import pypika.functions as fn from pypika.terms import Criterion from itertools import groupby from functools import reduce import sqlite3 import logging SeqId = int The provided code snippet includes necessary dependencies for implementing the `_decode_seq_id` function. Write a Python function `def _decode_seq_id(seq_id_bytes: bytes) -> SeqId` to solve the following problem: Decode a byte array into a SeqID Here is the function: def _decode_seq_id(seq_id_bytes: bytes) -> SeqId: """Decode a byte array into a SeqID""" if len(seq_id_bytes) == 8: return int.from_bytes(seq_id_bytes, "big") elif len(seq_id_bytes) == 24: return int.from_bytes(seq_id_bytes, "big") else: raise ValueError(f"Unknown SeqID type with length {len(seq_id_bytes)}")
Decode a byte array into a SeqID
154,642
from typing import Optional, Sequence, Any, Tuple, cast, Generator, Union, Dict, List from chromadb.segment import MetadataReader from chromadb.ingest import Consumer from chromadb.config import System from chromadb.types import Segment, InclusionExclusionOperator from chromadb.db.impl.sqlite import SqliteDB from overrides import override from chromadb.db.base import ( Cursor, ParameterValue, get_sql, ) from chromadb.telemetry.opentelemetry import ( OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) from chromadb.types import ( Where, WhereDocument, MetadataEmbeddingRecord, EmbeddingRecord, SeqId, Operation, UpdateMetadata, LiteralValue, WhereOperator, ) from uuid import UUID from pypika import Table, Tables from pypika.queries import QueryBuilder import pypika.functions as fn from pypika.terms import Criterion from itertools import groupby from functools import reduce import sqlite3 import logging def _value_criterion( value: Union[LiteralValue, List[LiteralValue]], op: Union[WhereOperator, InclusionExclusionOperator], table: Table, ) -> Criterion: """Return a criterion to compare a value with the appropriate columns given its type and the operation type.""" if isinstance(value, str): cols = [table.string_value] # isinstance(True, int) evaluates to True, so we need to check for bools separately elif isinstance(value, bool) and op in ("$eq", "$ne"): cols = [table.bool_value] elif isinstance(value, int) and op in ("$eq", "$ne"): cols = [table.int_value] elif isinstance(value, float) and op in ("$eq", "$ne"): cols = [table.float_value] elif isinstance(value, list) and op in ("$in", "$nin"): _v = value if len(_v) == 0: raise ValueError(f"Empty list for {op} operator") if isinstance(value[0], str): col_exprs = [ table.string_value.isin(ParameterValue(_v)) if op == "$in" else table.string_value.notin(ParameterValue(_v)) ] elif isinstance(value[0], bool): col_exprs = [ table.bool_value.isin(ParameterValue(_v)) if op == "$in" else table.bool_value.notin(ParameterValue(_v)) ] elif isinstance(value[0], int): col_exprs = [ table.int_value.isin(ParameterValue(_v)) if op == "$in" else table.int_value.notin(ParameterValue(_v)) ] elif isinstance(value[0], float): col_exprs = [ table.float_value.isin(ParameterValue(_v)) if op == "$in" else table.float_value.notin(ParameterValue(_v)) ] elif isinstance(value, list) and op in ("$in", "$nin"): col_exprs = [ table.int_value.isin(ParameterValue(value)) if op == "$in" else table.int_value.notin(ParameterValue(value)), table.float_value.isin(ParameterValue(value)) if op == "$in" else table.float_value.notin(ParameterValue(value)), ] else: cols = [table.int_value, table.float_value] if op == "$eq": col_exprs = [col == ParameterValue(value) for col in cols] elif op == "$ne": col_exprs = [col != ParameterValue(value) for col in cols] elif op == "$gt": col_exprs = [col > ParameterValue(value) for col in cols] elif op == "$gte": col_exprs = [col >= ParameterValue(value) for col in cols] elif op == "$lt": col_exprs = [col < ParameterValue(value) for col in cols] elif op == "$lte": col_exprs = [col <= ParameterValue(value) for col in cols] if op == "$ne": return reduce(lambda x, y: x & y, col_exprs) else: return reduce(lambda x, y: x | y, col_exprs) LiteralValue = Union[str, int, float, bool] WhereOperator = Union[ Literal["$gt"], Literal["$gte"], Literal["$lt"], Literal["$lte"], Literal["$ne"], Literal["$eq"], ] InclusionExclusionOperator = Union[Literal["$in"], Literal["$nin"]] The provided code snippet includes necessary dependencies for implementing the `_where_clause` function. Write a Python function `def _where_clause( expr: Union[ LiteralValue, Dict[WhereOperator, LiteralValue], Dict[InclusionExclusionOperator, List[LiteralValue]], ], table: Table, ) -> Criterion` to solve the following problem: Given a field name, an expression, and a table, construct a Pypika Criterion Here is the function: def _where_clause( expr: Union[ LiteralValue, Dict[WhereOperator, LiteralValue], Dict[InclusionExclusionOperator, List[LiteralValue]], ], table: Table, ) -> Criterion: """Given a field name, an expression, and a table, construct a Pypika Criterion""" # Literal value case if isinstance(expr, (str, int, float, bool)): return _where_clause({cast(WhereOperator, "$eq"): expr}, table) # Operator dict case operator, value = next(iter(expr.items())) return _value_criterion(value, operator, table)
Given a field name, an expression, and a table, construct a Pypika Criterion
154,643
from threading import Lock from chromadb.segment import ( SegmentImplementation, SegmentManager, MetadataReader, SegmentType, VectorReader, S, ) import logging from chromadb.segment.impl.manager.cache.cache import SegmentLRUCache, BasicCache,SegmentCache import os from chromadb.config import System, get_class from chromadb.db.system import SysDB from overrides import override from chromadb.segment.impl.vector.local_persistent_hnsw import ( PersistentLocalHnswSegment, ) from chromadb.telemetry.opentelemetry import ( OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) from chromadb.types import Collection, Operation, Segment, SegmentScope, Metadata from typing import Dict, Type, Sequence, Optional, cast from uuid import UUID, uuid4 import platform from chromadb.utils.lru_cache import LRUCache from chromadb.utils.directory import get_directory_size SEGMENT_TYPE_IMPLS = { SegmentType.SQLITE: "chromadb.segment.impl.metadata.sqlite.SqliteMetadataSegment", SegmentType.HNSW_LOCAL_MEMORY: "chromadb.segment.impl.vector.local_hnsw.LocalHnswSegment", SegmentType.HNSW_LOCAL_PERSISTED: "chromadb.segment.impl.vector.local_persistent_hnsw.PersistentLocalHnswSegment", } class SegmentType(Enum): SQLITE = "urn:chroma:segment/metadata/sqlite" HNSW_LOCAL_MEMORY = "urn:chroma:segment/vector/hnsw-local-memory" HNSW_LOCAL_PERSISTED = "urn:chroma:segment/vector/hnsw-local-persisted" HNSW_DISTRIBUTED = "urn:chroma:segment/vector/hnsw-distributed" class SegmentImplementation(Component): def __init__(self, sytstem: System, segment: Segment): pass def count(self) -> int: """Get the number of embeddings in this segment""" pass def max_seqid(self) -> SeqId: """Get the maximum SeqID currently indexed by this segment""" pass def propagate_collection_metadata(metadata: Metadata) -> Optional[Metadata]: """Given an arbitrary metadata map (e.g, from a collection), validate it and return metadata (if any) that is applicable and should be applied to the segment. Validation errors will be reported to the user.""" return None def delete(self) -> None: """Delete the segment and all its data""" ... def get_class(fqn: str, type: Type[C]) -> Type[C]: """Given a fully qualifed class name, import the module and return the class""" module_name, class_name = fqn.rsplit(".", 1) module = importlib.import_module(module_name) cls = getattr(module, class_name) return cast(Type[C], cls) Metadata = Mapping[str, Union[str, int, float, bool]] class SegmentScope(Enum): VECTOR = "VECTOR" METADATA = "METADATA" class Collection(TypedDict): id: UUID name: str topic: str metadata: Optional[Metadata] dimension: Optional[int] tenant: str database: str class Segment(TypedDict): id: UUID type: NamespacedName scope: SegmentScope # If a segment has a topic, it implies that this segment is a consumer of the topic # and indexes the contents of the topic. topic: Optional[str] # If a segment has a collection, it implies that this segment implements the full # collection and can be used to service queries (for it's given scope.) collection: Optional[UUID] metadata: Optional[Metadata] The provided code snippet includes necessary dependencies for implementing the `_segment` function. Write a Python function `def _segment(type: SegmentType, scope: SegmentScope, collection: Collection) -> Segment` to solve the following problem: Create a metadata dict, propagating metadata correctly for the given segment type. Here is the function: def _segment(type: SegmentType, scope: SegmentScope, collection: Collection) -> Segment: """Create a metadata dict, propagating metadata correctly for the given segment type.""" cls = get_class(SEGMENT_TYPE_IMPLS[type], SegmentImplementation) collection_metadata = collection.get("metadata", None) metadata: Optional[Metadata] = None if collection_metadata: metadata = cls.propagate_collection_metadata(collection_metadata) return Segment( id=uuid4(), type=type.value, scope=scope, topic=collection["topic"], collection=collection["id"], metadata=metadata )
Create a metadata dict, propagating metadata correctly for the given segment type.
154,644
from threading import Lock from chromadb.segment import ( SegmentImplementation, SegmentManager, MetadataReader, SegmentType, VectorReader, S, ) from chromadb.config import System, get_class from chromadb.db.system import SysDB from overrides import override from chromadb.segment.distributed import SegmentDirectory from chromadb.telemetry.opentelemetry import ( OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) from chromadb.types import Collection, Operation, Segment, SegmentScope, Metadata from typing import Dict, Type, Sequence, Optional, cast from uuid import UUID, uuid4 from collections import defaultdict SEGMENT_TYPE_IMPLS = { SegmentType.SQLITE: "chromadb.segment.impl.metadata.sqlite.SqliteMetadataSegment", SegmentType.HNSW_DISTRIBUTED: "chromadb.segment.impl.vector.grpc_segment.GrpcVectorSegment", } class SegmentType(Enum): SQLITE = "urn:chroma:segment/metadata/sqlite" HNSW_LOCAL_MEMORY = "urn:chroma:segment/vector/hnsw-local-memory" HNSW_LOCAL_PERSISTED = "urn:chroma:segment/vector/hnsw-local-persisted" HNSW_DISTRIBUTED = "urn:chroma:segment/vector/hnsw-distributed" class SegmentImplementation(Component): def __init__(self, sytstem: System, segment: Segment): pass def count(self) -> int: """Get the number of embeddings in this segment""" pass def max_seqid(self) -> SeqId: """Get the maximum SeqID currently indexed by this segment""" pass def propagate_collection_metadata(metadata: Metadata) -> Optional[Metadata]: """Given an arbitrary metadata map (e.g, from a collection), validate it and return metadata (if any) that is applicable and should be applied to the segment. Validation errors will be reported to the user.""" return None def delete(self) -> None: """Delete the segment and all its data""" ... def get_class(fqn: str, type: Type[C]) -> Type[C]: """Given a fully qualifed class name, import the module and return the class""" module_name, class_name = fqn.rsplit(".", 1) module = importlib.import_module(module_name) cls = getattr(module, class_name) return cast(Type[C], cls) Metadata = Mapping[str, Union[str, int, float, bool]] class SegmentScope(Enum): VECTOR = "VECTOR" METADATA = "METADATA" class Collection(TypedDict): id: UUID name: str topic: str metadata: Optional[Metadata] dimension: Optional[int] tenant: str database: str class Segment(TypedDict): id: UUID type: NamespacedName scope: SegmentScope # If a segment has a topic, it implies that this segment is a consumer of the topic # and indexes the contents of the topic. topic: Optional[str] # If a segment has a collection, it implies that this segment implements the full # collection and can be used to service queries (for it's given scope.) collection: Optional[UUID] metadata: Optional[Metadata] The provided code snippet includes necessary dependencies for implementing the `_segment` function. Write a Python function `def _segment(type: SegmentType, scope: SegmentScope, collection: Collection) -> Segment` to solve the following problem: Create a metadata dict, propagating metadata correctly for the given segment type. Here is the function: def _segment(type: SegmentType, scope: SegmentScope, collection: Collection) -> Segment: """Create a metadata dict, propagating metadata correctly for the given segment type.""" cls = get_class(SEGMENT_TYPE_IMPLS[type], SegmentImplementation) collection_metadata = collection.get("metadata", None) metadata: Optional[Metadata] = None if collection_metadata: metadata = cls.propagate_collection_metadata(collection_metadata) return Segment( id=uuid4(), type=type.value, scope=scope, topic=collection["topic"], collection=collection["id"], metadata=metadata, )
Create a metadata dict, propagating metadata correctly for the given segment type.
154,645
import array from uuid import UUID from typing import Dict, Optional, Tuple, Union, cast from chromadb.api.types import Embedding import chromadb.proto.chroma_pb2 as proto from chromadb.utils.messageid import bytes_to_int, int_to_bytes from chromadb.types import ( Collection, EmbeddingRecord, Metadata, Operation, ScalarEncoding, Segment, SegmentScope, SeqId, SubmitEmbeddingRecord, UpdateMetadata, Vector, VectorEmbeddingRecord, VectorQueryResult, ) def from_proto_vector(vector: proto.Vector) -> Tuple[Embedding, ScalarEncoding]: encoding = vector.encoding as_array: Union[array.array[float], array.array[int]] if encoding == proto.ScalarEncoding.FLOAT32: as_array = array.array("f") out_encoding = ScalarEncoding.FLOAT32 elif encoding == proto.ScalarEncoding.INT32: as_array = array.array("i") out_encoding = ScalarEncoding.INT32 else: raise ValueError( f"Unknown encoding {encoding}, expected one of \ {proto.ScalarEncoding.FLOAT32} or {proto.ScalarEncoding.INT32}" ) as_array.frombytes(vector.vector) return (as_array.tolist(), out_encoding) def from_proto_operation(operation: proto.Operation) -> Operation: if operation == proto.Operation.ADD: return Operation.ADD elif operation == proto.Operation.UPDATE: return Operation.UPDATE elif operation == proto.Operation.UPSERT: return Operation.UPSERT elif operation == proto.Operation.DELETE: return Operation.DELETE else: # TODO: full error raise RuntimeError(f"Unknown operation {operation}") def from_proto_update_metadata( metadata: proto.UpdateMetadata, ) -> Optional[UpdateMetadata]: return cast( Optional[UpdateMetadata], _from_proto_metadata_handle_none(metadata, True) ) SeqId = int class EmbeddingRecord(TypedDict): id: str seq_id: SeqId embedding: Optional[Vector] encoding: Optional[ScalarEncoding] metadata: Optional[UpdateMetadata] operation: Operation # The collection the operation is being performed on # This is optional because in the single node version, # topics are 1:1 with collections. So consumers of the ingest queue # implicitly know this mapping. However, in the multi-node version, # topics are shared between collections, so we need to explicitly # specify the collection. # For backwards compatability reasons, we can't make this a required field on # single node, since data written with older versions of the code won't be able to # populate it. collection_id: Optional[UUID] class SubmitEmbeddingRecord(TypedDict): id: str embedding: Optional[Vector] encoding: Optional[ScalarEncoding] metadata: Optional[UpdateMetadata] operation: Operation collection_id: UUID # The collection the operation is being performed on def from_proto_submit( submit_embedding_record: proto.SubmitEmbeddingRecord, seq_id: SeqId ) -> EmbeddingRecord: embedding, encoding = from_proto_vector(submit_embedding_record.vector) record = EmbeddingRecord( id=submit_embedding_record.id, seq_id=seq_id, embedding=embedding, encoding=encoding, metadata=from_proto_update_metadata(submit_embedding_record.metadata), operation=from_proto_operation(submit_embedding_record.operation), collection_id=UUID(hex=submit_embedding_record.collection_id), ) return record
null
154,646
import array from uuid import UUID from typing import Dict, Optional, Tuple, Union, cast from chromadb.api.types import Embedding import chromadb.proto.chroma_pb2 as proto from chromadb.utils.messageid import bytes_to_int, int_to_bytes from chromadb.types import ( Collection, EmbeddingRecord, Metadata, Operation, ScalarEncoding, Segment, SegmentScope, SeqId, SubmitEmbeddingRecord, UpdateMetadata, Vector, VectorEmbeddingRecord, VectorQueryResult, ) def from_proto_metadata(metadata: proto.UpdateMetadata) -> Optional[Metadata]: return cast(Optional[Metadata], _from_proto_metadata_handle_none(metadata, False)) def from_proto_segment_scope(segment_scope: proto.SegmentScope) -> SegmentScope: if segment_scope == proto.SegmentScope.VECTOR: return SegmentScope.VECTOR elif segment_scope == proto.SegmentScope.METADATA: return SegmentScope.METADATA else: raise RuntimeError(f"Unknown segment scope {segment_scope}") class Segment(TypedDict): id: UUID type: NamespacedName scope: SegmentScope # If a segment has a topic, it implies that this segment is a consumer of the topic # and indexes the contents of the topic. topic: Optional[str] # If a segment has a collection, it implies that this segment implements the full # collection and can be used to service queries (for it's given scope.) collection: Optional[UUID] metadata: Optional[Metadata] def from_proto_segment(segment: proto.Segment) -> Segment: return Segment( id=UUID(hex=segment.id), type=segment.type, scope=from_proto_segment_scope(segment.scope), topic=segment.topic if segment.HasField("topic") else None, collection=None if not segment.HasField("collection") else UUID(hex=segment.collection), metadata=from_proto_metadata(segment.metadata) if segment.HasField("metadata") else None, )
null
154,647
import array from uuid import UUID from typing import Dict, Optional, Tuple, Union, cast from chromadb.api.types import Embedding import chromadb.proto.chroma_pb2 as proto from chromadb.utils.messageid import bytes_to_int, int_to_bytes from chromadb.types import ( Collection, EmbeddingRecord, Metadata, Operation, ScalarEncoding, Segment, SegmentScope, SeqId, SubmitEmbeddingRecord, UpdateMetadata, Vector, VectorEmbeddingRecord, VectorQueryResult, ) def to_proto_update_metadata(metadata: UpdateMetadata) -> proto.UpdateMetadata: return proto.UpdateMetadata( metadata={k: to_proto_metadata_update_value(v) for k, v in metadata.items()} ) def to_proto_segment_scope(segment_scope: SegmentScope) -> proto.SegmentScope: if segment_scope == SegmentScope.VECTOR: return proto.SegmentScope.VECTOR elif segment_scope == SegmentScope.METADATA: return proto.SegmentScope.METADATA else: raise RuntimeError(f"Unknown segment scope {segment_scope}") class Segment(TypedDict): id: UUID type: NamespacedName scope: SegmentScope # If a segment has a topic, it implies that this segment is a consumer of the topic # and indexes the contents of the topic. topic: Optional[str] # If a segment has a collection, it implies that this segment implements the full # collection and can be used to service queries (for it's given scope.) collection: Optional[UUID] metadata: Optional[Metadata] def to_proto_segment(segment: Segment) -> proto.Segment: return proto.Segment( id=segment["id"].hex, type=segment["type"], scope=to_proto_segment_scope(segment["scope"]), topic=segment["topic"], collection=None if segment["collection"] is None else segment["collection"].hex, metadata=None if segment["metadata"] is None else to_proto_update_metadata(segment["metadata"]), )
null
154,648
import array from uuid import UUID from typing import Dict, Optional, Tuple, Union, cast from chromadb.api.types import Embedding import chromadb.proto.chroma_pb2 as proto from chromadb.utils.messageid import bytes_to_int, int_to_bytes from chromadb.types import ( Collection, EmbeddingRecord, Metadata, Operation, ScalarEncoding, Segment, SegmentScope, SeqId, SubmitEmbeddingRecord, UpdateMetadata, Vector, VectorEmbeddingRecord, VectorQueryResult, ) def from_proto_metadata(metadata: proto.UpdateMetadata) -> Optional[Metadata]: class Collection(TypedDict): def from_proto_collection(collection: proto.Collection) -> Collection: return Collection( id=UUID(hex=collection.id), name=collection.name, topic=collection.topic, metadata=from_proto_metadata(collection.metadata) if collection.HasField("metadata") else None, dimension=collection.dimension if collection.HasField("dimension") and collection.dimension else None, database=collection.database, tenant=collection.tenant, )
null
154,649
import array from uuid import UUID from typing import Dict, Optional, Tuple, Union, cast from chromadb.api.types import Embedding import chromadb.proto.chroma_pb2 as proto from chromadb.utils.messageid import bytes_to_int, int_to_bytes from chromadb.types import ( Collection, EmbeddingRecord, Metadata, Operation, ScalarEncoding, Segment, SegmentScope, SeqId, SubmitEmbeddingRecord, UpdateMetadata, Vector, VectorEmbeddingRecord, VectorQueryResult, ) def to_proto_update_metadata(metadata: UpdateMetadata) -> proto.UpdateMetadata: class Collection(TypedDict): def to_proto_collection(collection: Collection) -> proto.Collection: return proto.Collection( id=collection["id"].hex, name=collection["name"], topic=collection["topic"], metadata=None if collection["metadata"] is None else to_proto_update_metadata(collection["metadata"]), dimension=collection["dimension"], tenant=collection["tenant"], database=collection["database"], )
null
154,650
import array from uuid import UUID from typing import Dict, Optional, Tuple, Union, cast from chromadb.api.types import Embedding import chromadb.proto.chroma_pb2 as proto from chromadb.utils.messageid import bytes_to_int, int_to_bytes from chromadb.types import ( Collection, EmbeddingRecord, Metadata, Operation, ScalarEncoding, Segment, SegmentScope, SeqId, SubmitEmbeddingRecord, UpdateMetadata, Vector, VectorEmbeddingRecord, VectorQueryResult, ) def to_proto_vector(vector: Vector, encoding: ScalarEncoding) -> proto.Vector: if encoding == ScalarEncoding.FLOAT32: as_bytes = array.array("f", vector).tobytes() proto_encoding = proto.ScalarEncoding.FLOAT32 elif encoding == ScalarEncoding.INT32: as_bytes = array.array("i", vector).tobytes() proto_encoding = proto.ScalarEncoding.INT32 else: raise ValueError( f"Unknown encoding {encoding}, expected one of {ScalarEncoding.FLOAT32} \ or {ScalarEncoding.INT32}" ) return proto.Vector(dimension=len(vector), vector=as_bytes, encoding=proto_encoding) def to_proto_update_metadata(metadata: UpdateMetadata) -> proto.UpdateMetadata: return proto.UpdateMetadata( metadata={k: to_proto_metadata_update_value(v) for k, v in metadata.items()} ) def to_proto_operation(operation: Operation) -> proto.Operation: if operation == Operation.ADD: return proto.Operation.ADD elif operation == Operation.UPDATE: return proto.Operation.UPDATE elif operation == Operation.UPSERT: return proto.Operation.UPSERT elif operation == Operation.DELETE: return proto.Operation.DELETE else: raise ValueError( f"Unknown operation {operation}, expected one of {Operation.ADD}, \ {Operation.UPDATE}, {Operation.UPDATE}, or {Operation.DELETE}" ) class SubmitEmbeddingRecord(TypedDict): id: str embedding: Optional[Vector] encoding: Optional[ScalarEncoding] metadata: Optional[UpdateMetadata] operation: Operation collection_id: UUID # The collection the operation is being performed on def to_proto_submit( submit_record: SubmitEmbeddingRecord, ) -> proto.SubmitEmbeddingRecord: vector = None if submit_record["embedding"] is not None and submit_record["encoding"] is not None: vector = to_proto_vector(submit_record["embedding"], submit_record["encoding"]) metadata = None if submit_record["metadata"] is not None: metadata = to_proto_update_metadata(submit_record["metadata"]) return proto.SubmitEmbeddingRecord( id=submit_record["id"], vector=vector, metadata=metadata, operation=to_proto_operation(submit_record["operation"]), collection_id=submit_record["collection_id"].hex, )
null
154,651
import array from uuid import UUID from typing import Dict, Optional, Tuple, Union, cast from chromadb.api.types import Embedding import chromadb.proto.chroma_pb2 as proto from chromadb.utils.messageid import bytes_to_int, int_to_bytes from chromadb.types import ( Collection, EmbeddingRecord, Metadata, Operation, ScalarEncoding, Segment, SegmentScope, SeqId, SubmitEmbeddingRecord, UpdateMetadata, Vector, VectorEmbeddingRecord, VectorQueryResult, ) def from_proto_vector(vector: proto.Vector) -> Tuple[Embedding, ScalarEncoding]: encoding = vector.encoding as_array: Union[array.array[float], array.array[int]] if encoding == proto.ScalarEncoding.FLOAT32: as_array = array.array("f") out_encoding = ScalarEncoding.FLOAT32 elif encoding == proto.ScalarEncoding.INT32: as_array = array.array("i") out_encoding = ScalarEncoding.INT32 else: raise ValueError( f"Unknown encoding {encoding}, expected one of \ {proto.ScalarEncoding.FLOAT32} or {proto.ScalarEncoding.INT32}" ) as_array.frombytes(vector.vector) return (as_array.tolist(), out_encoding) def from_proto_seq_id(seq_id: bytes) -> SeqId: return bytes_to_int(seq_id) class VectorEmbeddingRecord(TypedDict): id: str seq_id: SeqId embedding: Vector def from_proto_vector_embedding_record( embedding_record: proto.VectorEmbeddingRecord, ) -> VectorEmbeddingRecord: return VectorEmbeddingRecord( id=embedding_record.id, seq_id=from_proto_seq_id(embedding_record.seq_id), embedding=from_proto_vector(embedding_record.vector)[0], )
null
154,652
import array from uuid import UUID from typing import Dict, Optional, Tuple, Union, cast from chromadb.api.types import Embedding import chromadb.proto.chroma_pb2 as proto from chromadb.utils.messageid import bytes_to_int, int_to_bytes from chromadb.types import ( Collection, EmbeddingRecord, Metadata, Operation, ScalarEncoding, Segment, SegmentScope, SeqId, SubmitEmbeddingRecord, UpdateMetadata, Vector, VectorEmbeddingRecord, VectorQueryResult, ) def to_proto_vector(vector: Vector, encoding: ScalarEncoding) -> proto.Vector: if encoding == ScalarEncoding.FLOAT32: as_bytes = array.array("f", vector).tobytes() proto_encoding = proto.ScalarEncoding.FLOAT32 elif encoding == ScalarEncoding.INT32: as_bytes = array.array("i", vector).tobytes() proto_encoding = proto.ScalarEncoding.INT32 else: raise ValueError( f"Unknown encoding {encoding}, expected one of {ScalarEncoding.FLOAT32} \ or {ScalarEncoding.INT32}" ) return proto.Vector(dimension=len(vector), vector=as_bytes, encoding=proto_encoding) def to_proto_seq_id(seq_id: SeqId) -> bytes: return int_to_bytes(seq_id) class ScalarEncoding(Enum): FLOAT32 = "FLOAT32" INT32 = "INT32" class VectorEmbeddingRecord(TypedDict): id: str seq_id: SeqId embedding: Vector def to_proto_vector_embedding_record( embedding_record: VectorEmbeddingRecord, encoding: ScalarEncoding, ) -> proto.VectorEmbeddingRecord: return proto.VectorEmbeddingRecord( id=embedding_record["id"], seq_id=to_proto_seq_id(embedding_record["seq_id"]), vector=to_proto_vector(embedding_record["embedding"], encoding), )
null
154,653
import array from uuid import UUID from typing import Dict, Optional, Tuple, Union, cast from chromadb.api.types import Embedding import chromadb.proto.chroma_pb2 as proto from chromadb.utils.messageid import bytes_to_int, int_to_bytes from chromadb.types import ( Collection, EmbeddingRecord, Metadata, Operation, ScalarEncoding, Segment, SegmentScope, SeqId, SubmitEmbeddingRecord, UpdateMetadata, Vector, VectorEmbeddingRecord, VectorQueryResult, ) def from_proto_vector(vector: proto.Vector) -> Tuple[Embedding, ScalarEncoding]: encoding = vector.encoding as_array: Union[array.array[float], array.array[int]] if encoding == proto.ScalarEncoding.FLOAT32: as_array = array.array("f") out_encoding = ScalarEncoding.FLOAT32 elif encoding == proto.ScalarEncoding.INT32: as_array = array.array("i") out_encoding = ScalarEncoding.INT32 else: raise ValueError( f"Unknown encoding {encoding}, expected one of \ {proto.ScalarEncoding.FLOAT32} or {proto.ScalarEncoding.INT32}" ) as_array.frombytes(vector.vector) return (as_array.tolist(), out_encoding) def from_proto_seq_id(seq_id: bytes) -> SeqId: return bytes_to_int(seq_id) class VectorQueryResult(TypedDict): """A KNN/ANN query result""" id: str seq_id: SeqId distance: float embedding: Optional[Vector] def from_proto_vector_query_result( vector_query_result: proto.VectorQueryResult, ) -> VectorQueryResult: return VectorQueryResult( id=vector_query_result.id, seq_id=from_proto_seq_id(vector_query_result.seq_id), distance=vector_query_result.distance, embedding=from_proto_vector(vector_query_result.vector)[0], )
null
154,654
import grpc from chromadb.proto import chroma_pb2 as chromadb_dot_proto_dot_chroma__pb2 def add_VectorReaderServicer_to_server(servicer, server): rpc_method_handlers = { 'GetVectors': grpc.unary_unary_rpc_method_handler( servicer.GetVectors, request_deserializer=chromadb_dot_proto_dot_chroma__pb2.GetVectorsRequest.FromString, response_serializer=chromadb_dot_proto_dot_chroma__pb2.GetVectorsResponse.SerializeToString, ), 'QueryVectors': grpc.unary_unary_rpc_method_handler( servicer.QueryVectors, request_deserializer=chromadb_dot_proto_dot_chroma__pb2.QueryVectorsRequest.FromString, response_serializer=chromadb_dot_proto_dot_chroma__pb2.QueryVectorsResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'chroma.VectorReader', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
null
154,655
import grpc from chromadb.proto import coordinator_pb2 as chromadb_dot_proto_dot_coordinator__pb2 from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 def add_SysDBServicer_to_server(servicer, server): rpc_method_handlers = { 'CreateDatabase': grpc.unary_unary_rpc_method_handler( servicer.CreateDatabase, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.CreateDatabaseRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.CreateDatabaseResponse.SerializeToString, ), 'GetDatabase': grpc.unary_unary_rpc_method_handler( servicer.GetDatabase, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.GetDatabaseRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.GetDatabaseResponse.SerializeToString, ), 'CreateTenant': grpc.unary_unary_rpc_method_handler( servicer.CreateTenant, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.CreateTenantRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.CreateTenantResponse.SerializeToString, ), 'GetTenant': grpc.unary_unary_rpc_method_handler( servicer.GetTenant, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.GetTenantRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.GetTenantResponse.SerializeToString, ), 'CreateSegment': grpc.unary_unary_rpc_method_handler( servicer.CreateSegment, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.CreateSegmentRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.CreateSegmentResponse.SerializeToString, ), 'DeleteSegment': grpc.unary_unary_rpc_method_handler( servicer.DeleteSegment, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.DeleteSegmentRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.DeleteSegmentResponse.SerializeToString, ), 'GetSegments': grpc.unary_unary_rpc_method_handler( servicer.GetSegments, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.GetSegmentsRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.GetSegmentsResponse.SerializeToString, ), 'UpdateSegment': grpc.unary_unary_rpc_method_handler( servicer.UpdateSegment, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.UpdateSegmentRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.UpdateSegmentResponse.SerializeToString, ), 'CreateCollection': grpc.unary_unary_rpc_method_handler( servicer.CreateCollection, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.CreateCollectionRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.CreateCollectionResponse.SerializeToString, ), 'DeleteCollection': grpc.unary_unary_rpc_method_handler( servicer.DeleteCollection, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.DeleteCollectionRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.DeleteCollectionResponse.SerializeToString, ), 'GetCollections': grpc.unary_unary_rpc_method_handler( servicer.GetCollections, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.GetCollectionsRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.GetCollectionsResponse.SerializeToString, ), 'UpdateCollection': grpc.unary_unary_rpc_method_handler( servicer.UpdateCollection, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.UpdateCollectionRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.UpdateCollectionResponse.SerializeToString, ), 'ResetState': grpc.unary_unary_rpc_method_handler( servicer.ResetState, request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.ResetStateResponse.SerializeToString, ), 'GetLastCompactionTimeForTenant': grpc.unary_unary_rpc_method_handler( servicer.GetLastCompactionTimeForTenant, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.GetLastCompactionTimeForTenantRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.GetLastCompactionTimeForTenantResponse.SerializeToString, ), 'SetLastCompactionTimeForTenant': grpc.unary_unary_rpc_method_handler( servicer.SetLastCompactionTimeForTenant, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.SetLastCompactionTimeForTenantRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'FlushCollectionCompaction': grpc.unary_unary_rpc_method_handler( servicer.FlushCollectionCompaction, request_deserializer=chromadb_dot_proto_dot_coordinator__pb2.FlushCollectionCompactionRequest.FromString, response_serializer=chromadb_dot_proto_dot_coordinator__pb2.FlushCollectionCompactionResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'chroma.SysDB', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
null
154,656
import grpc from chromadb.proto import logservice_pb2 as chromadb_dot_proto_dot_logservice__pb2 def add_LogServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'PushLogs': grpc.unary_unary_rpc_method_handler( servicer.PushLogs, request_deserializer=chromadb_dot_proto_dot_logservice__pb2.PushLogsRequest.FromString, response_serializer=chromadb_dot_proto_dot_logservice__pb2.PushLogsResponse.SerializeToString, ), 'PullLogs': grpc.unary_unary_rpc_method_handler( servicer.PullLogs, request_deserializer=chromadb_dot_proto_dot_logservice__pb2.PullLogsRequest.FromString, response_serializer=chromadb_dot_proto_dot_logservice__pb2.PullLogsResponse.SerializeToString, ), 'GetAllCollectionInfoToCompact': grpc.unary_unary_rpc_method_handler( servicer.GetAllCollectionInfoToCompact, request_deserializer=chromadb_dot_proto_dot_logservice__pb2.GetAllCollectionInfoToCompactRequest.FromString, response_serializer=chromadb_dot_proto_dot_logservice__pb2.GetAllCollectionInfoToCompactResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'chroma.LogService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
null
154,657
from functools import partial from typing import Any, Callable, Dict, Optional, Sequence, cast from chromadb.utils.fastapi import string_to_uuid from chromadb.api import ServerAPI from chromadb.auth import AuthzResourceTypes def find_key_with_value_of_type( type: AuthzResourceTypes, **kwargs: Any ) -> Dict[str, Any]: from chromadb.server.fastapi.types import ( CreateCollection, CreateDatabase, CreateTenant, ) for key, value in kwargs.items(): if type == AuthzResourceTypes.DB and isinstance(value, CreateDatabase): return dict(value) elif type == AuthzResourceTypes.COLLECTION and isinstance( value, CreateCollection ): return dict(value) elif type == AuthzResourceTypes.TENANT and isinstance(value, CreateTenant): return dict(value) return {} class AuthzResourceTypes(str, Enum): DB = "db" COLLECTION = "collection" TENANT = "tenant" def attr_from_resource_object( type: AuthzResourceTypes, additional_attrs: Optional[Sequence[str]] = None, **kwargs: Any, ) -> Callable[..., Dict[str, Any]]: def _wrap(**wkwargs: Any) -> Dict[str, Any]: obj = find_key_with_value_of_type(type, **wkwargs) if additional_attrs: obj.update({k: wkwargs["function_kwargs"][k] for k in additional_attrs}) return obj return partial(_wrap, **kwargs)
null
154,658
from functools import partial from typing import Any, Callable, Dict, Optional, Sequence, cast from chromadb.utils.fastapi import string_to_uuid from chromadb.api import ServerAPI from chromadb.auth import AuthzResourceTypes def string_to_uuid(uuid_str: str) -> UUID: class ServerAPI(BaseAPI, AdminAPI, Component): def list_collections( self, limit: Optional[int] = None, offset: Optional[int] = None, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> Sequence[Collection]: def count_collections( self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE ) -> int: def create_collection( self, name: str, metadata: Optional[CollectionMetadata] = None, embedding_function: Optional[ EmbeddingFunction[Embeddable] ] = ef.DefaultEmbeddingFunction(), # type: ignore data_loader: Optional[DataLoader[Loadable]] = None, get_or_create: bool = False, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> Collection: def get_collection( self, name: str, id: Optional[UUID] = None, embedding_function: Optional[ EmbeddingFunction[Embeddable] ] = ef.DefaultEmbeddingFunction(), # type: ignore data_loader: Optional[DataLoader[Loadable]] = None, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> Collection: def get_or_create_collection( self, name: str, metadata: Optional[CollectionMetadata] = None, embedding_function: Optional[ EmbeddingFunction[Embeddable] ] = ef.DefaultEmbeddingFunction(), # type: ignore data_loader: Optional[DataLoader[Loadable]] = None, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> Collection: def delete_collection( self, name: str, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> None: def attr_from_collection_lookup( collection_id_arg: str, **kwargs: Any ) -> Callable[..., Dict[str, Any]]: def _wrap(**kwargs: Any) -> Dict[str, Any]: _api = cast(ServerAPI, kwargs["api"]) col = _api.get_collection( id=string_to_uuid(kwargs["function_kwargs"][collection_id_arg])) return {"tenant": col.tenant, "database": col.database} return partial(_wrap, **kwargs)
null
154,659
import importlib import logging import pkgutil from typing import Union, Dict, Type, Callable from chromadb.auth import ( ClientAuthConfigurationProvider, ClientAuthCredentialsProvider, ClientAuthProtocolAdapter, ServerAuthProvider, ServerAuthConfigurationProvider, ServerAuthCredentialsProvider, ClientAuthProvider, ServerAuthorizationConfigurationProvider, ServerAuthorizationProvider, ) from chromadb.utils import get_class logger = logging.getLogger(__name__) ProviderTypes = Union[ "ClientAuthProvider", "ClientAuthConfigurationProvider", "ClientAuthCredentialsProvider", "ServerAuthProvider", "ServerAuthConfigurationProvider", "ServerAuthCredentialsProvider", "ClientAuthProtocolAdapter", "ServerAuthorizationProvider", "ServerAuthorizationConfigurationProvider", ] _provider_registry = { "client_auth_providers": {}, "client_auth_config_providers": {}, "client_auth_credentials_providers": {}, "client_auth_protocol_adapters": {}, "server_auth_providers": {}, "server_auth_config_providers": {}, "server_auth_credentials_providers": {}, "server_authz_providers": {}, "server_authz_config_providers": {}, } class ClientAuthProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def authenticate(self) -> ClientAuthResponse: pass class ClientAuthConfigurationProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def get_configuration(self) -> Optional[T]: pass class ClientAuthCredentialsProvider(Component, Generic[T]): def __init__(self, system: System) -> None: super().__init__(system) def get_credentials(self) -> T: pass class ClientAuthProtocolAdapter(Component, Generic[T]): def __init__(self, system: System) -> None: super().__init__(system) def inject_credentials(self, injection_context: T) -> None: pass class ServerAuthProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def authenticate( self, request: ServerAuthenticationRequest[T] ) -> ServerAuthenticationResponse: pass class ServerAuthConfigurationProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def get_configuration(self) -> Optional[T]: pass class ServerAuthCredentialsProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def validate_credentials(self, credentials: AbstractCredentials[T]) -> bool: ... def get_user_identity( self, credentials: AbstractCredentials[T] ) -> Optional[UserIdentity]: ... class ServerAuthorizationProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def authorize(self, context: AuthorizationContext) -> bool: pass class ServerAuthorizationConfigurationProvider(Component, Generic[T]): def __init__(self, system: System) -> None: super().__init__(system) def get_configuration(self) -> T: pass def register_provider( short_hand: str, ) -> Callable[[Type[ProviderTypes]], Type[ProviderTypes]]: def decorator(cls: Type[ProviderTypes]) -> Type[ProviderTypes]: logger.debug("Registering provider: %s", short_hand) global _provider_registry if issubclass(cls, ClientAuthProvider): _provider_registry["client_auth_providers"][short_hand] = cls elif issubclass(cls, ClientAuthConfigurationProvider): _provider_registry["client_auth_config_providers"][short_hand] = cls elif issubclass(cls, ClientAuthCredentialsProvider): _provider_registry["client_auth_credentials_providers"][short_hand] = cls elif issubclass(cls, ClientAuthProtocolAdapter): _provider_registry["client_auth_protocol_adapters"][short_hand] = cls elif issubclass(cls, ServerAuthProvider): _provider_registry["server_auth_providers"][short_hand] = cls elif issubclass(cls, ServerAuthConfigurationProvider): _provider_registry["server_auth_config_providers"][short_hand] = cls elif issubclass(cls, ServerAuthCredentialsProvider): _provider_registry["server_auth_credentials_providers"][short_hand] = cls elif issubclass(cls, ServerAuthorizationProvider): _provider_registry["server_authz_providers"][short_hand] = cls elif issubclass(cls, ServerAuthorizationConfigurationProvider): _provider_registry["server_authz_config_providers"][short_hand] = cls else: raise ValueError( "Only ClientAuthProvider, ClientAuthConfigurationProvider, " "ClientAuthCredentialsProvider, ServerAuthProvider, " "ServerAuthConfigurationProvider, and ServerAuthCredentialsProvider, " "ClientAuthProtocolAdapter, ServerAuthorizationProvider, " "ServerAuthorizationConfigurationProvider can be registered." ) return cls return decorator
null
154,660
import importlib import logging import pkgutil from typing import Union, Dict, Type, Callable from chromadb.auth import ( ClientAuthConfigurationProvider, ClientAuthCredentialsProvider, ClientAuthProtocolAdapter, ServerAuthProvider, ServerAuthConfigurationProvider, ServerAuthCredentialsProvider, ClientAuthProvider, ServerAuthorizationConfigurationProvider, ServerAuthorizationProvider, ) from chromadb.utils import get_class ProviderTypes = Union[ "ClientAuthProvider", "ClientAuthConfigurationProvider", "ClientAuthCredentialsProvider", "ServerAuthProvider", "ServerAuthConfigurationProvider", "ServerAuthCredentialsProvider", "ClientAuthProtocolAdapter", "ServerAuthorizationProvider", "ServerAuthorizationConfigurationProvider", ] _provider_registry = { "client_auth_providers": {}, "client_auth_config_providers": {}, "client_auth_credentials_providers": {}, "client_auth_protocol_adapters": {}, "server_auth_providers": {}, "server_auth_config_providers": {}, "server_auth_credentials_providers": {}, "server_authz_providers": {}, "server_authz_config_providers": {}, } def register_classes_from_package(package_name: str) -> None: package = importlib.import_module(package_name) for _, module_name, _ in pkgutil.iter_modules(package.__path__): full_module_name = f"{package_name}.{module_name}" _ = importlib.import_module(full_module_name) class ClientAuthProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def authenticate(self) -> ClientAuthResponse: pass class ClientAuthConfigurationProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def get_configuration(self) -> Optional[T]: pass class ClientAuthCredentialsProvider(Component, Generic[T]): def __init__(self, system: System) -> None: super().__init__(system) def get_credentials(self) -> T: pass class ClientAuthProtocolAdapter(Component, Generic[T]): def __init__(self, system: System) -> None: super().__init__(system) def inject_credentials(self, injection_context: T) -> None: pass class ServerAuthProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def authenticate( self, request: ServerAuthenticationRequest[T] ) -> ServerAuthenticationResponse: pass class ServerAuthConfigurationProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def get_configuration(self) -> Optional[T]: pass class ServerAuthCredentialsProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def validate_credentials(self, credentials: AbstractCredentials[T]) -> bool: ... def get_user_identity( self, credentials: AbstractCredentials[T] ) -> Optional[UserIdentity]: ... class ServerAuthorizationProvider(Component): def __init__(self, system: System) -> None: super().__init__(system) def authorize(self, context: AuthorizationContext) -> bool: pass class ServerAuthorizationConfigurationProvider(Component, Generic[T]): def __init__(self, system: System) -> None: super().__init__(system) def get_configuration(self) -> T: pass def get_class(fqn: str, type: Type[C]) -> Type[C]: """Given a fully qualifed class name, import the module and return the class""" module_name, class_name = fqn.rsplit(".", 1) module = importlib.import_module(module_name) cls = getattr(module, class_name) return cast(Type[C], cls) def resolve_provider( class_or_name: str, cls: Type[ProviderTypes] ) -> Type[ProviderTypes]: register_classes_from_package("chromadb.auth") global _provider_registry if issubclass(cls, ClientAuthProvider): _key = "client_auth_providers" elif issubclass(cls, ClientAuthConfigurationProvider): _key = "client_auth_config_providers" elif issubclass(cls, ClientAuthCredentialsProvider): _key = "client_auth_credentials_providers" elif issubclass(cls, ClientAuthProtocolAdapter): _key = "client_auth_protocol_adapters" elif issubclass(cls, ServerAuthProvider): _key = "server_auth_providers" elif issubclass(cls, ServerAuthConfigurationProvider): _key = "server_auth_config_providers" elif issubclass(cls, ServerAuthCredentialsProvider): _key = "server_auth_credentials_providers" elif issubclass(cls, ServerAuthorizationProvider): _key = "server_authz_providers" elif issubclass(cls, ServerAuthorizationConfigurationProvider): _key = "server_authz_config_providers" else: raise ValueError( "Only ClientAuthProvider, ClientAuthConfigurationProvider, " "ClientAuthCredentialsProvider, ServerAuthProvider, " "ServerAuthConfigurationProvider, and ServerAuthCredentialsProvider, " "ClientAuthProtocolAdapter, ServerAuthorizationProvider," "ServerAuthorizationConfigurationProvider, can be registered." ) if class_or_name in _provider_registry[_key]: return _provider_registry[_key][class_or_name] else: return get_class(class_or_name, cls) # type: ignore
null
154,661
from contextvars import ContextVar from functools import wraps import logging from typing import Callable, Optional, Dict, List, Union, cast, Any from overrides import override from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint from starlette.requests import Request from starlette.responses import Response from starlette.types import ASGIApp import chromadb from chromadb.config import DEFAULT_TENANT, System from chromadb.auth import ( AuthorizationContext, AuthorizationRequestContext, AuthzAction, AuthzResource, AuthzResourceActions, AuthzUser, DynamicAuthzResource, ServerAuthenticationRequest, AuthInfoType, ServerAuthenticationResponse, ServerAuthProvider, ChromaAuthMiddleware, ChromaAuthzMiddleware, ServerAuthorizationProvider, ) from chromadb.auth.registry import resolve_provider from chromadb.errors import AuthorizationError from chromadb.utils.fastapi import fastapi_json_response from chromadb.telemetry.opentelemetry import ( OpenTelemetryGranularity, trace_method, ) overwrite_singleton_tenant_database_access_from_auth: bool = False def set_overwrite_singleton_tenant_database_access_from_auth( overwrite: bool = False, ) -> None: global overwrite_singleton_tenant_database_access_from_auth overwrite_singleton_tenant_database_access_from_auth = overwrite
null
154,662
from contextvars import ContextVar from functools import wraps import logging from typing import Callable, Optional, Dict, List, Union, cast, Any from overrides import override from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint from starlette.requests import Request from starlette.responses import Response from starlette.types import ASGIApp import chromadb from chromadb.config import DEFAULT_TENANT, System from chromadb.auth import ( AuthorizationContext, AuthorizationRequestContext, AuthzAction, AuthzResource, AuthzResourceActions, AuthzUser, DynamicAuthzResource, ServerAuthenticationRequest, AuthInfoType, ServerAuthenticationResponse, ServerAuthProvider, ChromaAuthMiddleware, ChromaAuthzMiddleware, ServerAuthorizationProvider, ) from chromadb.auth.registry import resolve_provider from chromadb.errors import AuthorizationError from chromadb.utils.fastapi import fastapi_json_response from chromadb.telemetry.opentelemetry import ( OpenTelemetryGranularity, trace_method, ) request_var: ContextVar[Optional[Request]] = ContextVar("request_var", default=None) authz_provider: ContextVar[Optional[ServerAuthorizationProvider]] = ContextVar( "authz_provider", default=None ) overwrite_singleton_tenant_database_access_from_auth: bool = False DEFAULT_TENANT = "default_tenant" class AuthzResourceActions(str, Enum): CREATE_DATABASE = "create_database" GET_DATABASE = "get_database" CREATE_TENANT = "create_tenant" GET_TENANT = "get_tenant" LIST_COLLECTIONS = "list_collections" COUNT_COLLECTIONS = "count_collections" GET_COLLECTION = "get_collection" CREATE_COLLECTION = "create_collection" GET_OR_CREATE_COLLECTION = "get_or_create_collection" DELETE_COLLECTION = "delete_collection" UPDATE_COLLECTION = "update_collection" ADD = "add" DELETE = "delete" GET = "get" QUERY = "query" COUNT = "count" UPDATE = "update" UPSERT = "upsert" RESET = "reset" class AuthzUser: id: Optional[str] tenant: Optional[str] = DEFAULT_TENANT attributes: Optional[Dict[str, Any]] = None claims: Optional[Dict[str, Any]] = None class AuthzResource: id: Optional[str] type: Optional[str] attributes: Optional[Dict[str, Any]] = None class DynamicAuthzResource: id: Optional[Union[str, Callable[..., str]]] type: Optional[Union[str, Callable[..., str]]] attributes: Optional[Union[Dict[str, Any], Callable[..., Dict[str, Any]]]] def __init__( self, id: Optional[Union[str, Callable[..., str]]] = None, attributes: Optional[ Union[Dict[str, Any], Callable[..., Dict[str, Any]]] ] = lambda **kwargs: {}, type: Optional[Union[str, Callable[..., str]]] = DEFAULT_DATABASE, ) -> None: self.id = id self.attributes = attributes self.type = type def to_authz_resource(self, **kwargs: Any) -> AuthzResource: return AuthzResource( id=self.id(**kwargs) if callable(self.id) else self.id, type=self.type(**kwargs) if callable(self.type) else self.type, attributes=self.attributes(**kwargs) if callable(self.attributes) else self.attributes, ) class AuthzAction: id: str attributes: Optional[Dict[str, Any]] = None class AuthorizationContext: user: AuthzUser resource: AuthzResource action: AuthzAction class AuthorizationError(ChromaError): def code(self) -> int: return 401 def name(cls) -> str: return "AuthorizationError" def authz_context( action: Union[str, AuthzResourceActions, List[str], List[AuthzResourceActions]], resource: Union[AuthzResource, DynamicAuthzResource], ) -> Callable[[Callable[..., Any]], Callable[..., Any]]: def decorator(f: Callable[..., Any]) -> Callable[..., Any]: @wraps(f) def wrapped(*args: Any, **kwargs: Dict[Any, Any]) -> Any: _dynamic_kwargs = { "api": args[0]._api, "function": f, "function_args": args, "function_kwargs": kwargs, } request = request_var.get() if request: _provider = authz_provider.get() a_list: List[Union[str, AuthzAction]] = [] if not isinstance(action, list): a_list = [action] else: a_list = cast(List[Union[str, AuthzAction]], action) a_authz_responses = [] for a in a_list: _action = a if isinstance(a, AuthzAction) else AuthzAction(id=a) _resource = ( resource if isinstance(resource, AuthzResource) else resource.to_authz_resource(**_dynamic_kwargs) ) _context = AuthorizationContext( user=AuthzUser( id=request.state.user_identity.get_user_id() if hasattr(request.state, "user_identity") else "Anonymous", tenant=request.state.user_identity.get_user_tenant() if hasattr(request.state, "user_identity") else DEFAULT_TENANT, attributes=request.state.user_identity.get_user_attributes() if hasattr(request.state, "user_identity") else {}, ), resource=_resource, action=_action, ) if _provider: a_authz_responses.append(_provider.authorize(_context)) if not any(a_authz_responses): raise AuthorizationError("Unauthorized") # In a multi-tenant environment, we may want to allow users to send # requests without configuring a tenant and DB. If so, they can set # the request tenant and DB however they like and we simply overwrite it. if overwrite_singleton_tenant_database_access_from_auth: desired_tenant = request.state.user_identity.get_user_tenant() if desired_tenant and "tenant" in kwargs: if isinstance(kwargs["tenant"], str): kwargs["tenant"] = desired_tenant elif isinstance( kwargs["tenant"], chromadb.server.fastapi.types.CreateTenant ): kwargs["tenant"].name = desired_tenant databases = request.state.user_identity.get_user_databases() if databases and len(databases) == 1 and "database" in kwargs: desired_database = databases[0] if isinstance(kwargs["database"], str): kwargs["database"] = desired_database elif isinstance( kwargs["database"], chromadb.server.fastapi.types.CreateDatabase, ): kwargs["database"].name = desired_database return f(*args, **kwargs) return wrapped return decorator
null
154,663
import importlib import inspect import logging import os from abc import ABC from graphlib import TopologicalSorter from typing import Optional, List, Any, Dict, Set, Iterable, Union from typing import Type, TypeVar, cast from overrides import EnforceOverrides from overrides import override from typing_extensions import Literal import platform The provided code snippet includes necessary dependencies for implementing the `get_fqn` function. Write a Python function `def get_fqn(cls: Type[object]) -> str` to solve the following problem: Given a class, return its fully qualified name Here is the function: def get_fqn(cls: Type[object]) -> str: """Given a class, return its fully qualified name""" return f"{cls.__module__}.{cls.__name__}"
Given a class, return its fully qualified name
154,664
import logging from typing import Optional import yaml from typing_extensions import Annotated import typer import uvicorn import os import webbrowser from chromadb.cli.utils import set_log_file_path _logo = """ \033[38;5;069m((((((((( \033[38;5;203m(((((\033[38;5;220m#### \033[38;5;069m(((((((((((((\033[38;5;203m(((((((((\033[38;5;220m######### \033[38;5;069m(((((((((((((\033[38;5;203m(((((((((((\033[38;5;220m########### \033[38;5;069m((((((((((((((\033[38;5;203m((((((((((((\033[38;5;220m############ \033[38;5;069m(((((((((((((\033[38;5;203m((((((((((((((\033[38;5;220m############# \033[38;5;069m(((((((((((((\033[38;5;203m((((((((((((((\033[38;5;220m############# \033[38;5;069m((((((((((((\033[38;5;203m(((((((((((((\033[38;5;220m############## \033[38;5;069m((((((((((((\033[38;5;203m((((((((((((\033[38;5;220m############## \033[38;5;069m((((((((((\033[38;5;203m(((((((((((\033[38;5;220m############# \033[38;5;069m((((((((\033[38;5;203m((((((((\033[38;5;220m############## \033[38;5;069m(((((\033[38;5;203m(((( \033[38;5;220m#########\033[0m """ def help() -> None: """Opens help url in your browser""" webbrowser.open("https://discord.gg/MMeYNTmh3x") def set_log_file_path( log_config_path: str, new_filename: str = "chroma.log" ) -> Dict[str, Any]: """This works with the standard log_config.yml file. It will not work with custom log configs that may use different handlers""" with open(f"{log_config_path}", "r") as file: log_config = yaml.safe_load(file) for handler in log_config["handlers"].values(): if handler.get("class") == "logging.handlers.RotatingFileHandler": handler["filename"] = new_filename return log_config The provided code snippet includes necessary dependencies for implementing the `run` function. Write a Python function `def run( path: str = typer.Option( "./chroma_data", help="The path to the file or directory." ), host: Annotated[ Optional[str], typer.Option(help="The host to listen to. Default: localhost") ] = "localhost", log_path: Annotated[ Optional[str], typer.Option(help="The path to the log file.") ] = "chroma.log", port: int = typer.Option(8000, help="The port to run the server on."), test: bool = typer.Option(False, help="Test mode.", show_envvar=False, hidden=True), ) -> None` to solve the following problem: Run a chroma server Here is the function: def run( path: str = typer.Option( "./chroma_data", help="The path to the file or directory." ), host: Annotated[ Optional[str], typer.Option(help="The host to listen to. Default: localhost") ] = "localhost", log_path: Annotated[ Optional[str], typer.Option(help="The path to the log file.") ] = "chroma.log", port: int = typer.Option(8000, help="The port to run the server on."), test: bool = typer.Option(False, help="Test mode.", show_envvar=False, hidden=True), ) -> None: """Run a chroma server""" print("\033[1m") # Bold logo print(_logo) print("\033[1m") # Bold print("Running Chroma") print("\033[0m") # Reset typer.echo(f"\033[1mSaving data to\033[0m: \033[32m{path}\033[0m") typer.echo( f"\033[1mConnect to chroma at\033[0m: \033[32mhttp://{host}:{port}\033[0m" ) typer.echo( "\033[1mGetting started guide\033[0m: https://docs.trychroma.com/getting-started\n\n" ) # set ENV variable for PERSIST_DIRECTORY to path os.environ["IS_PERSISTENT"] = "True" os.environ["PERSIST_DIRECTORY"] = path os.environ["CHROMA_SERVER_NOFILE"] = "65535" # get the path where chromadb is installed chromadb_path = os.path.dirname(os.path.realpath(__file__)) # this is the path of the CLI, we want to move up one directory chromadb_path = os.path.dirname(chromadb_path) log_config = set_log_file_path(f"{chromadb_path}/log_config.yml", f"{log_path}") config = { "app": "chromadb.app:app", "host": host, "port": port, "workers": 1, "log_config": log_config, # Pass the modified log_config dictionary "timeout_keep_alive": 30, } if test: return uvicorn.run(**config)
Run a chroma server
154,665
import logging from typing import Optional import yaml from typing_extensions import Annotated import typer import uvicorn import os import webbrowser from chromadb.cli.utils import set_log_file_path The provided code snippet includes necessary dependencies for implementing the `docs` function. Write a Python function `def docs() -> None` to solve the following problem: Opens docs url in your browser Here is the function: def docs() -> None: """Opens docs url in your browser""" webbrowser.open("https://docs.trychroma.com")
Opens docs url in your browser
154,666
import re from typing import Tuple topic_regex = r"persistent:\/\/(?P<tenant>.+)\/(?P<namespace>.+)\/(?P<topic>.+)" The provided code snippet includes necessary dependencies for implementing the `parse_topic_name` function. Write a Python function `def parse_topic_name(topic_name: str) -> Tuple[str, str, str]` to solve the following problem: Parse the topic name into the tenant, namespace and topic name Here is the function: def parse_topic_name(topic_name: str) -> Tuple[str, str, str]: """Parse the topic name into the tenant, namespace and topic name""" match = re.match(topic_regex, topic_name) if not match: raise ValueError(f"Invalid topic name: {topic_name}") return match.group("tenant"), match.group("namespace"), match.group("topic")
Parse the topic name into the tenant, namespace and topic name
154,667
import re from typing import Tuple def create_pulsar_connection_str(host: str, port: str) -> str: return f"pulsar://{host}:{port}"
null
154,668
import re from typing import Tuple def create_topic_name(tenant: str, namespace: str, topic: str) -> str: return f"persistent://{tenant}/{namespace}/{topic}"
null
154,669
import sys from typing import Sequence from typing_extensions import TypedDict, NotRequired from importlib_resources.abc import Traversable import re import hashlib from chromadb.db.base import SqlDB, Cursor from abc import abstractmethod from chromadb.config import System, Settings from chromadb.telemetry.opentelemetry import ( OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) class Migration(MigrationFile): hash: str sql: str class InconsistentVersionError(Exception): def __init__(self, dir: str, db_version: int, source_version: int): super().__init__( f"Inconsistent migration versions in {dir}:" + f"db version was {db_version}, source version was {source_version}." + " Has the migration sequence been modified since being applied to the DB?" ) class InconsistentHashError(Exception): def __init__(self, path: str, db_hash: str, source_hash: str): super().__init__( f"Inconsistent hashes in {path}:" + f"db hash was {db_hash}, source has was {source_hash}." + " Was the migration file modified after being applied to the DB?" ) The provided code snippet includes necessary dependencies for implementing the `verify_migration_sequence` function. Write a Python function `def verify_migration_sequence( db_migrations: Sequence[Migration], source_migrations: Sequence[Migration], ) -> Sequence[Migration]` to solve the following problem: Given a list of migrations already applied to a database, and a list of migrations from the source code, validate that the applied migrations are correct and match the expected migrations. Throws an exception if any migrations are missing, out of order, or if the source hash does not match. Returns a list of all unapplied migrations, or an empty list if all migrations are applied and the database is up to date. Here is the function: def verify_migration_sequence( db_migrations: Sequence[Migration], source_migrations: Sequence[Migration], ) -> Sequence[Migration]: """Given a list of migrations already applied to a database, and a list of migrations from the source code, validate that the applied migrations are correct and match the expected migrations. Throws an exception if any migrations are missing, out of order, or if the source hash does not match. Returns a list of all unapplied migrations, or an empty list if all migrations are applied and the database is up to date.""" for db_migration, source_migration in zip(db_migrations, source_migrations): if db_migration["version"] != source_migration["version"]: raise InconsistentVersionError( dir=db_migration["dir"], db_version=db_migration["version"], source_version=source_migration["version"], ) if db_migration["hash"] != source_migration["hash"]: raise InconsistentHashError( path=db_migration["dir"] + "/" + db_migration["filename"], db_hash=db_migration["hash"], source_hash=source_migration["hash"], ) return source_migrations[len(db_migrations) :]
Given a list of migrations already applied to a database, and a list of migrations from the source code, validate that the applied migrations are correct and match the expected migrations. Throws an exception if any migrations are missing, out of order, or if the source hash does not match. Returns a list of all unapplied migrations, or an empty list if all migrations are applied and the database is up to date.
154,670
import sys from typing import Sequence from typing_extensions import TypedDict, NotRequired from importlib_resources.abc import Traversable import re import hashlib from chromadb.db.base import SqlDB, Cursor from abc import abstractmethod from chromadb.config import System, Settings from chromadb.telemetry.opentelemetry import ( OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) class Migration(MigrationFile): hash: str sql: str def _parse_migration_filename( dir: str, filename: str, path: Traversable ) -> MigrationFile: """Parse a migration filename into a MigrationFile object""" match = filename_regex.match(filename) if match is None: raise InvalidMigrationFilename("Invalid migration filename: " + filename) version, _, scope = match.groups() return { "path": path, "dir": dir, "filename": filename, "version": int(version), "scope": scope, } def _read_migration_file(file: MigrationFile, hash_alg: str) -> Migration: """Read a migration file""" if "path" not in file or not file["path"].is_file(): raise FileNotFoundError( f"No migration file found for dir {file['dir']} with filename {file['filename']} and scope {file['scope']} at version {file['version']}" ) sql = file["path"].read_text() if hash_alg == "md5": hash = hashlib.md5(sql.encode("utf-8"), usedforsecurity=False).hexdigest() if sys.version_info >= (3, 9) else hashlib.md5(sql.encode("utf-8")).hexdigest() elif hash_alg == "sha256": hash = hashlib.sha256(sql.encode("utf-8")).hexdigest() else: raise InvalidHashError(alg=hash_alg) return { "hash": hash, "sql": sql, "dir": file["dir"], "filename": file["filename"], "version": file["version"], "scope": file["scope"], } The provided code snippet includes necessary dependencies for implementing the `find_migrations` function. Write a Python function `def find_migrations(dir: Traversable, scope: str, hash_alg: str = "md5") -> Sequence[Migration]` to solve the following problem: Return a list of all migration present in the given directory, in ascending order. Filter by scope. Here is the function: def find_migrations(dir: Traversable, scope: str, hash_alg: str = "md5") -> Sequence[Migration]: """Return a list of all migration present in the given directory, in ascending order. Filter by scope.""" files = [ _parse_migration_filename(dir.name, t.name, t) for t in dir.iterdir() if t.name.endswith(".sql") ] files = list(filter(lambda f: f["scope"] == scope, files)) files = sorted(files, key=lambda f: f["version"]) return [_read_migration_file(f, hash_alg) for f in files]
Return a list of all migration present in the given directory, in ascending order. Filter by scope.
154,671
from typing import Any, Optional, Sequence, Tuple, Type from types import TracebackType from typing_extensions import Protocol, Self, Literal from abc import ABC, abstractmethod from threading import local from overrides import override, EnforceOverrides import pypika import pypika.queries from chromadb.config import System, Component from uuid import UUID from itertools import islice, count _context = local() The provided code snippet includes necessary dependencies for implementing the `get_sql` function. Write a Python function `def get_sql( query: pypika.queries.QueryBuilder, formatstr: str = "?" ) -> Tuple[str, Tuple[Any, ...]]` to solve the following problem: Wrapper for pypika's get_sql method that allows the values for Parameters to be expressed inline while building a query, and that returns a tuple of the SQL string and parameters. This makes it easier to construct complex queries programmatically and automatically matches up the generated SQL with the required parameter vector. Doing so requires using the ParameterValue class defined in this module instead of the base pypika.Parameter class. Usage Example: q = ( pypika.Query().from_("table") .select("col1") .where("col2"==ParameterValue("foo")) .where("col3"==ParameterValue("bar")) ) sql, params = get_sql(q) cursor.execute(sql, params) Note how it is not necessary to construct the parameter vector manually... it will always be generated with the parameter values in the same order as emitted SQL string. The format string should match the parameter format for the database being used. It will be called with str.format(i) where i is the numeric index of the parameter. For example, Postgres requires parameters like `:1`, `:2`, etc. so the format string should be `":{}"`. See https://pypika.readthedocs.io/en/latest/2_tutorial.html#parametrized-queries for more information on parameterized queries in PyPika. Here is the function: def get_sql( query: pypika.queries.QueryBuilder, formatstr: str = "?" ) -> Tuple[str, Tuple[Any, ...]]: """ Wrapper for pypika's get_sql method that allows the values for Parameters to be expressed inline while building a query, and that returns a tuple of the SQL string and parameters. This makes it easier to construct complex queries programmatically and automatically matches up the generated SQL with the required parameter vector. Doing so requires using the ParameterValue class defined in this module instead of the base pypika.Parameter class. Usage Example: q = ( pypika.Query().from_("table") .select("col1") .where("col2"==ParameterValue("foo")) .where("col3"==ParameterValue("bar")) ) sql, params = get_sql(q) cursor.execute(sql, params) Note how it is not necessary to construct the parameter vector manually... it will always be generated with the parameter values in the same order as emitted SQL string. The format string should match the parameter format for the database being used. It will be called with str.format(i) where i is the numeric index of the parameter. For example, Postgres requires parameters like `:1`, `:2`, etc. so the format string should be `":{}"`. See https://pypika.readthedocs.io/en/latest/2_tutorial.html#parametrized-queries for more information on parameterized queries in PyPika. """ _context.values = [] _context.generator = count(1) _context.formatstr = formatstr sql = query.get_sql() params = tuple(_context.values) return sql, params
Wrapper for pypika's get_sql method that allows the values for Parameters to be expressed inline while building a query, and that returns a tuple of the SQL string and parameters. This makes it easier to construct complex queries programmatically and automatically matches up the generated SQL with the required parameter vector. Doing so requires using the ParameterValue class defined in this module instead of the base pypika.Parameter class. Usage Example: q = ( pypika.Query().from_("table") .select("col1") .where("col2"==ParameterValue("foo")) .where("col3"==ParameterValue("bar")) ) sql, params = get_sql(q) cursor.execute(sql, params) Note how it is not necessary to construct the parameter vector manually... it will always be generated with the parameter values in the same order as emitted SQL string. The format string should match the parameter format for the database being used. It will be called with str.format(i) where i is the numeric index of the parameter. For example, Postgres requires parameters like `:1`, `:2`, etc. so the format string should be `":{}"`. See https://pypika.readthedocs.io/en/latest/2_tutorial.html#parametrized-queries for more information on parameterized queries in PyPika.
154,672
import hashlib import logging from functools import cached_property from tenacity import stop_after_attempt, wait_random, retry, retry_if_exception from chromadb.api.types import ( Document, Documents, Embedding, Image, Images, EmbeddingFunction, Embeddings, is_image, is_document, ) from pathlib import Path import os import tarfile import requests from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Union, cast import numpy as np import numpy.typing as npt import importlib import inspect import json import sys def _verify_sha256(fname: str, expected_sha256: str) -> bool: sha256_hash = hashlib.sha256() with open(fname, "rb") as f: # Read and update hash in chunks to avoid using too much memory for byte_block in iter(lambda: f.read(4096), b""): sha256_hash.update(byte_block) return sha256_hash.hexdigest() == expected_sha256
null
154,673
import hashlib import logging from functools import cached_property from tenacity import stop_after_attempt, wait_random, retry, retry_if_exception from chromadb.api.types import ( Document, Documents, Embedding, Image, Images, EmbeddingFunction, Embeddings, is_image, is_document, ) from pathlib import Path import os import tarfile import requests from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Union, cast import numpy as np import numpy.typing as npt import importlib import inspect import json import sys class ONNXMiniLM_L6_V2(EmbeddingFunction[Documents]): MODEL_NAME = "all-MiniLM-L6-v2" DOWNLOAD_PATH = Path.home() / ".cache" / "chroma" / "onnx_models" / MODEL_NAME EXTRACTED_FOLDER_NAME = "onnx" ARCHIVE_FILENAME = "onnx.tar.gz" MODEL_DOWNLOAD_URL = ( "https://chroma-onnx-models.s3.amazonaws.com/all-MiniLM-L6-v2/onnx.tar.gz" ) _MODEL_SHA256 = "913d7300ceae3b2dbc2c50d1de4baacab4be7b9380491c27fab7418616a16ec3" # https://github.com/python/mypy/issues/7291 mypy makes you type the constructor if # no args def __init__(self, preferred_providers: Optional[List[str]] = None) -> None: # Import dependencies on demand to mirror other embedding functions. This # breaks typechecking, thus the ignores. # convert the list to set for unique values if preferred_providers and not all( [isinstance(i, str) for i in preferred_providers] ): raise ValueError("Preferred providers must be a list of strings") # check for duplicate providers if preferred_providers and len(preferred_providers) != len( set(preferred_providers) ): raise ValueError("Preferred providers must be unique") self._preferred_providers = preferred_providers try: # Equivalent to import onnxruntime self.ort = importlib.import_module("onnxruntime") except ImportError: raise ValueError( "The onnxruntime python package is not installed. Please install it with `pip install onnxruntime`" ) try: # Equivalent to from tokenizers import Tokenizer self.Tokenizer = importlib.import_module("tokenizers").Tokenizer except ImportError: raise ValueError( "The tokenizers python package is not installed. Please install it with `pip install tokenizers`" ) try: # Equivalent to from tqdm import tqdm self.tqdm = importlib.import_module("tqdm").tqdm except ImportError: raise ValueError( "The tqdm python package is not installed. Please install it with `pip install tqdm`" ) # Borrowed from https://gist.github.com/yanqd0/c13ed29e29432e3cf3e7c38467f42f51 # Download with tqdm to preserve the sentence-transformers experience reraise=True, stop=stop_after_attempt(3), wait=wait_random(min=1, max=3), retry=retry_if_exception(lambda e: "does not match expected SHA256" in str(e)), ) def _download(self, url: str, fname: str, chunk_size: int = 1024) -> None: resp = requests.get(url, stream=True) total = int(resp.headers.get("content-length", 0)) with open(fname, "wb") as file, self.tqdm( desc=str(fname), total=total, unit="iB", unit_scale=True, unit_divisor=1024, ) as bar: for data in resp.iter_content(chunk_size=chunk_size): size = file.write(data) bar.update(size) if not _verify_sha256(fname, self._MODEL_SHA256): # if the integrity of the file is not verified, remove it os.remove(fname) raise ValueError( f"Downloaded file {fname} does not match expected SHA256 hash. Corrupted download or malicious file." ) # Use pytorches default epsilon for division by zero # https://pytorch.org/docs/stable/generated/torch.nn.functional.normalize.html def _normalize(self, v: npt.NDArray) -> npt.NDArray: norm = np.linalg.norm(v, axis=1) norm[norm == 0] = 1e-12 return cast(npt.NDArray, v / norm[:, np.newaxis]) def _forward(self, documents: List[str], batch_size: int = 32) -> npt.NDArray: # We need to cast to the correct type because the type checker doesn't know that init_model_and_tokenizer will set the values self.tokenizer = cast(self.Tokenizer, self.tokenizer) self.model = cast(self.ort.InferenceSession, self.model) all_embeddings = [] for i in range(0, len(documents), batch_size): batch = documents[i : i + batch_size] encoded = [self.tokenizer.encode(d) for d in batch] input_ids = np.array([e.ids for e in encoded]) attention_mask = np.array([e.attention_mask for e in encoded]) onnx_input = { "input_ids": np.array(input_ids, dtype=np.int64), "attention_mask": np.array(attention_mask, dtype=np.int64), "token_type_ids": np.array( [np.zeros(len(e), dtype=np.int64) for e in input_ids], dtype=np.int64, ), } model_output = self.model.run(None, onnx_input) last_hidden_state = model_output[0] # Perform mean pooling with attention weighting input_mask_expanded = np.broadcast_to( np.expand_dims(attention_mask, -1), last_hidden_state.shape ) embeddings = np.sum(last_hidden_state * input_mask_expanded, 1) / np.clip( input_mask_expanded.sum(1), a_min=1e-9, a_max=None ) embeddings = self._normalize(embeddings).astype(np.float32) all_embeddings.append(embeddings) return np.concatenate(all_embeddings) def tokenizer(self) -> "Tokenizer": tokenizer = self.Tokenizer.from_file( os.path.join( self.DOWNLOAD_PATH, self.EXTRACTED_FOLDER_NAME, "tokenizer.json" ) ) # max_seq_length = 256, for some reason sentence-transformers uses 256 even though the HF config has a max length of 128 # https://github.com/UKPLab/sentence-transformers/blob/3e1929fddef16df94f8bc6e3b10598a98f46e62d/docs/_static/html/models_en_sentence_embeddings.html#LL480 tokenizer.enable_truncation(max_length=256) tokenizer.enable_padding(pad_id=0, pad_token="[PAD]", length=256) return tokenizer def model(self) -> "InferenceSession": if self._preferred_providers is None or len(self._preferred_providers) == 0: if len(self.ort.get_available_providers()) > 0: logger.debug( f"WARNING: No ONNX providers provided, defaulting to available providers: " f"{self.ort.get_available_providers()}" ) self._preferred_providers = self.ort.get_available_providers() elif not set(self._preferred_providers).issubset( set(self.ort.get_available_providers()) ): raise ValueError( f"Preferred providers must be subset of available providers: {self.ort.get_available_providers()}" ) # Suppress onnxruntime warnings. This produces logspew, mainly when onnx tries to use CoreML, which doesn't fit this model. so = self.ort.SessionOptions() so.log_severity_level = 3 return self.ort.InferenceSession( os.path.join(self.DOWNLOAD_PATH, self.EXTRACTED_FOLDER_NAME, "model.onnx"), # Since 1.9 onnyx runtime requires providers to be specified when there are multiple available - https://onnxruntime.ai/docs/api/python/api_summary.html # This is probably not ideal but will improve DX as no exceptions will be raised in multi-provider envs providers=self._preferred_providers, sess_options=so, ) def __call__(self, input: Documents) -> Embeddings: # Only download the model when it is actually used self._download_model_if_not_exists() return cast(Embeddings, self._forward(input).tolist()) def _download_model_if_not_exists(self) -> None: onnx_files = [ "config.json", "model.onnx", "special_tokens_map.json", "tokenizer_config.json", "tokenizer.json", "vocab.txt", ] extracted_folder = os.path.join(self.DOWNLOAD_PATH, self.EXTRACTED_FOLDER_NAME) onnx_files_exist = True for f in onnx_files: if not os.path.exists(os.path.join(extracted_folder, f)): onnx_files_exist = False break # Model is not downloaded yet if not onnx_files_exist: os.makedirs(self.DOWNLOAD_PATH, exist_ok=True) if not os.path.exists( os.path.join(self.DOWNLOAD_PATH, self.ARCHIVE_FILENAME) ) or not _verify_sha256( os.path.join(self.DOWNLOAD_PATH, self.ARCHIVE_FILENAME), self._MODEL_SHA256, ): self._download( url=self.MODEL_DOWNLOAD_URL, fname=os.path.join(self.DOWNLOAD_PATH, self.ARCHIVE_FILENAME), ) with tarfile.open( name=os.path.join(self.DOWNLOAD_PATH, self.ARCHIVE_FILENAME), mode="r:gz", ) as tar: tar.extractall(path=self.DOWNLOAD_PATH) Documents = List[Document] class EmbeddingFunction(Protocol[D]): def __call__(self, input: D) -> Embeddings: ... def __init_subclass__(cls) -> None: super().__init_subclass__() # Raise an exception if __call__ is not defined since it is expected to be defined call = getattr(cls, "__call__") def __call__(self: EmbeddingFunction[D], input: D) -> Embeddings: result = call(self, input) return validate_embeddings(maybe_cast_one_to_many_embedding(result)) setattr(cls, "__call__", __call__) def embed_with_retries(self, input: D, **retry_kwargs: Dict) -> Embeddings: return retry(**retry_kwargs)(self.__call__)(input) def DefaultEmbeddingFunction() -> Optional[EmbeddingFunction[Documents]]: if is_thin_client: return None else: return ONNXMiniLM_L6_V2()
null
154,674
import hashlib import logging from functools import cached_property from tenacity import stop_after_attempt, wait_random, retry, retry_if_exception from chromadb.api.types import ( Document, Documents, Embedding, Image, Images, EmbeddingFunction, Embeddings, is_image, is_document, ) from pathlib import Path import os import tarfile import requests from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Union, cast import numpy as np import numpy.typing as npt import importlib import inspect import json import sys _classes = [ name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass) if obj.__module__ == __name__ ] def get_builtins() -> List[str]: return _classes
null
154,675
from typing import Optional, Tuple, List from chromadb.api import BaseAPI from chromadb.api.types import ( Documents, Embeddings, IDs, Metadatas, ) class BaseAPI(ABC): def heartbeat(self) -> int: def list_collections( self, limit: Optional[int] = None, offset: Optional[int] = None, ) -> Sequence[Collection]: def count_collections(self) -> int: def create_collection( self, name: str, metadata: Optional[CollectionMetadata] = None, embedding_function: Optional[ EmbeddingFunction[Embeddable] ] = ef.DefaultEmbeddingFunction(), # type: ignore data_loader: Optional[DataLoader[Loadable]] = None, get_or_create: bool = False, ) -> Collection: def get_collection( self, name: str, id: Optional[UUID] = None, embedding_function: Optional[ EmbeddingFunction[Embeddable] ] = ef.DefaultEmbeddingFunction(), # type: ignore data_loader: Optional[DataLoader[Loadable]] = None, ) -> Collection: def get_or_create_collection( self, name: str, metadata: Optional[CollectionMetadata] = None, embedding_function: Optional[ EmbeddingFunction[Embeddable] ] = ef.DefaultEmbeddingFunction(), # type: ignore data_loader: Optional[DataLoader[Loadable]] = None, ) -> Collection: def _modify( self, id: UUID, new_name: Optional[str] = None, new_metadata: Optional[CollectionMetadata] = None, ) -> None: def delete_collection( self, name: str, ) -> None: def _add( self, ids: IDs, collection_id: UUID, embeddings: Embeddings, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, uris: Optional[URIs] = None, ) -> bool: def _update( self, collection_id: UUID, ids: IDs, embeddings: Optional[Embeddings] = None, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, uris: Optional[URIs] = None, ) -> bool: def _upsert( self, collection_id: UUID, ids: IDs, embeddings: Embeddings, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, uris: Optional[URIs] = None, ) -> bool: def _count(self, collection_id: UUID) -> int: def _peek(self, collection_id: UUID, n: int = 10) -> GetResult: def _get( self, collection_id: UUID, ids: Optional[IDs] = None, where: Optional[Where] = {}, sort: Optional[str] = None, limit: Optional[int] = None, offset: Optional[int] = None, page: Optional[int] = None, page_size: Optional[int] = None, where_document: Optional[WhereDocument] = {}, include: Include = ["embeddings", "metadatas", "documents"], ) -> GetResult: def _delete( self, collection_id: UUID, ids: Optional[IDs], where: Optional[Where] = {}, where_document: Optional[WhereDocument] = {}, ) -> IDs: def _query( self, collection_id: UUID, query_embeddings: Embeddings, n_results: int = 10, where: Where = {}, where_document: WhereDocument = {}, include: Include = ["embeddings", "metadatas", "documents", "distances"], ) -> QueryResult: def reset(self) -> bool: def get_version(self) -> str: def get_settings(self) -> Settings: def max_batch_size(self) -> int: IDs = List[ID] Embeddings = List[Embedding] Metadatas = List[Metadata] Documents = List[Document] def create_batches( api: BaseAPI, ids: IDs, embeddings: Optional[Embeddings] = None, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, ) -> List[Tuple[IDs, Embeddings, Optional[Metadatas], Optional[Documents]]]: _batches: List[ Tuple[IDs, Embeddings, Optional[Metadatas], Optional[Documents]] ] = [] if len(ids) > api.max_batch_size: # create split batches for i in range(0, len(ids), api.max_batch_size): _batches.append( ( # type: ignore ids[i : i + api.max_batch_size], embeddings[i : i + api.max_batch_size] if embeddings else None, metadatas[i : i + api.max_batch_size] if metadatas else None, documents[i : i + api.max_batch_size] if documents else None, ) ) else: _batches.append((ids, embeddings, metadatas, documents)) # type: ignore return _batches
null
154,676
import os The provided code snippet includes necessary dependencies for implementing the `get_directory_size` function. Write a Python function `def get_directory_size(directory: str) -> int` to solve the following problem: Calculate the total size of the directory by walking through each file. Parameters: directory (str): The path of the directory for which to calculate the size. Returns: total_size (int): The total size of the directory in bytes. Here is the function: def get_directory_size(directory: str) -> int: """ Calculate the total size of the directory by walking through each file. Parameters: directory (str): The path of the directory for which to calculate the size. Returns: total_size (int): The total size of the directory in bytes. """ total_size = 0 for dirpath, _, filenames in os.walk(directory): for f in filenames: fp = os.path.join(dirpath, f) # skip if it is symbolic link if not os.path.islink(fp): total_size += os.path.getsize(fp) return total_size
Calculate the total size of the directory by walking through each file. Parameters: directory (str): The path of the directory for which to calculate the size. Returns: total_size (int): The total size of the directory in bytes.
154,677
import os import random import gc import time def delete_file(name: str) -> None: try: os.remove(name) except Exception: pass chars = list("abcdefghijklmn") random.shuffle(chars) newname = name + "-n-" + "".join(chars) count = 0 while os.path.exists(name): count += 1 try: os.rename(name, newname) except Exception: if count > 30: n = list("abcdefghijklmnopqrstuvwxyz") random.shuffle(n) final_name = "".join(n) try: os.rename( name, "chroma-to-clean" + final_name + ".deletememanually" ) except Exception: pass break time.sleep(0.1) gc.collect()
null
154,678
from typing import Callable, List, cast import mmh3 Hasher = Callable[[str, str], int] Member = str Members = List[str] Key = str The provided code snippet includes necessary dependencies for implementing the `assign` function. Write a Python function `def assign(key: Key, members: Members, hasher: Hasher) -> Member` to solve the following problem: Assigns a key to a member using the rendezvous hashing algorithm Here is the function: def assign(key: Key, members: Members, hasher: Hasher) -> Member: """Assigns a key to a member using the rendezvous hashing algorithm""" if len(members) == 0: raise ValueError("Cannot assign key to empty memberlist") if len(members) == 1: return members[0] if key == "": raise ValueError("Cannot assign empty key") max_score = -1 max_member = None for member in members: score = hasher(member, key) if score > max_score: max_score = score max_member = member max_member = cast(Member, max_member) return max_member
Assigns a key to a member using the rendezvous hashing algorithm
154,679
from typing import Callable, List, cast import mmh3 Member = str Key = str def merge_hashes(x: int, y: int) -> int: """murmurhash3 mix 64-bit""" acc = x ^ y acc ^= acc >> 33 acc = ( acc * 0xFF51AFD7ED558CCD ) % 2**64 # We need to mod here to prevent python from using arbitrary size int acc ^= acc >> 33 acc = (acc * 0xC4CEB9FE1A85EC53) % 2**64 acc ^= acc >> 33 return acc The provided code snippet includes necessary dependencies for implementing the `murmur3hasher` function. Write a Python function `def murmur3hasher(member: Member, key: Key) -> int` to solve the following problem: Hashes the key and member using the murmur3 hashing algorithm Here is the function: def murmur3hasher(member: Member, key: Key) -> int: """Hashes the key and member using the murmur3 hashing algorithm""" member_hash = mmh3.hash64(member, signed=False)[0] key_hash = mmh3.hash64(key, signed=False)[0] return merge_hashes(member_hash, key_hash)
Hashes the key and member using the murmur3 hashing algorithm
154,680
import pulsar def pulsar_to_int(message_id: pulsar.MessageId) -> int: ledger_id: int = message_id.ledger_id() entry_id: int = message_id.entry_id() batch_index: int = message_id.batch_index() partition: int = message_id.partition() # Convert to offset binary encoding to preserve ordering semantics when encoded # see https://en.wikipedia.org/wiki/Offset_binary ledger_id = ledger_id + 2**63 entry_id = entry_id + 2**63 batch_index = batch_index + 2**31 partition = partition + 2**31 return ledger_id << 128 | entry_id << 64 | batch_index << 32 | partition
null
154,681
import pulsar def int_to_pulsar(message_id: int) -> pulsar.MessageId: partition = message_id & 0xFFFFFFFF batch_index = message_id >> 32 & 0xFFFFFFFF entry_id = message_id >> 64 & 0xFFFFFFFFFFFFFFFF ledger_id = message_id >> 128 & 0xFFFFFFFFFFFFFFFF partition = partition - 2**31 batch_index = batch_index - 2**31 entry_id = entry_id - 2**63 ledger_id = ledger_id - 2**63 return pulsar.MessageId(partition, ledger_id, entry_id, batch_index)
null
154,682
import pulsar base85 = ( "!#$%&()*+-0123456789;<=>?@ABCDEFGHIJKLMNOP" + "QRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~" ) def str_to_int(s: str) -> int: return sum(base85.index(c) * 85**i for i, c in enumerate(s[::-1]))
null
154,683
import pulsar def int_to_str(n: int) -> str: return _int_to_str(n).rjust(36, "!") # left pad with '!' to 36 chars def _benchmark() -> None: import random import time t0 = time.time() for i in range(1000000): x = random.randint(0, 2**192 - 1) s = int_to_str(x) if s == "!": # prevent compiler from optimizing out print("oops") t1 = time.time() print(t1 - t0)
null
154,684
from uuid import UUID from starlette.responses import JSONResponse from chromadb.errors import ChromaError, InvalidUUIDError class ChromaError(Exception, EnforceOverrides): def code(self) -> int: def message(self) -> str: def name(cls) -> str: def fastapi_json_response(error: ChromaError) -> JSONResponse: return JSONResponse( content={"error": error.name(), "message": error.message()}, status_code=error.code(), )
null
154,685
import numpy as np from numpy.typing import ArrayLike def l2(x: ArrayLike, y: ArrayLike) -> float: return np.linalg.norm(x - y) ** 2
null
154,686
import numpy as np from numpy.typing import ArrayLike def cosine(x: ArrayLike, y: ArrayLike) -> float: # This epsilon is used to prevent division by zero, and the value is the same # https://github.com/nmslib/hnswlib/blob/359b2ba87358224963986f709e593d799064ace6/python_bindings/bindings.cpp#L238 NORM_EPS = 1e-30 return 1 - np.dot(x, y) / ( (np.linalg.norm(x) + NORM_EPS) * (np.linalg.norm(y) + NORM_EPS) )
null
154,687
import numpy as np from numpy.typing import ArrayLike def ip(x: ArrayLike, y: ArrayLike) -> float: return 1 - np.dot(x, y)
null
154,688
import binascii import collections import grpc from opentelemetry.trace import StatusCode, SpanKind from chromadb.telemetry.opentelemetry import tracer def _encode_span_id(span_id: int) -> str: return binascii.hexlify(span_id.to_bytes(8, 'big')).decode()
null
154,689
import binascii import collections import grpc from opentelemetry.trace import StatusCode, SpanKind from chromadb.telemetry.opentelemetry import tracer def _encode_trace_id(trace_id: int) -> str: return binascii.hexlify(trace_id.to_bytes(16, 'big')).decode()
null
154,690
from typing import List, Optional from fastapi import FastAPI from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor class FastAPI(ServerAPI): _settings: Settings _max_batch_size: int = -1 def _validate_host(host: str) -> None: parsed = urlparse(host) if "/" in host and parsed.scheme not in {"http", "https"}: raise ValueError( "Invalid URL. " f"Unrecognized protocol - {parsed.scheme}." ) if "/" in host and (not host.startswith("http")): raise ValueError( "Invalid URL. " "Seems that you are trying to pass URL as a host but without \ specifying the protocol. " "Please add http:// or https:// to the host." ) def resolve_url( chroma_server_host: str, chroma_server_ssl_enabled: Optional[bool] = False, default_api_path: Optional[str] = "", chroma_server_http_port: Optional[int] = 8000, ) -> str: _skip_port = False _chroma_server_host = chroma_server_host FastAPI._validate_host(_chroma_server_host) if _chroma_server_host.startswith("http"): logger.debug("Skipping port as the user is passing a full URL") _skip_port = True parsed = urlparse(_chroma_server_host) scheme = "https" if chroma_server_ssl_enabled else parsed.scheme or "http" net_loc = parsed.netloc or parsed.hostname or chroma_server_host port = ( ":" + str(parsed.port or chroma_server_http_port) if not _skip_port else "" ) path = parsed.path or default_api_path if not path or path == net_loc: path = default_api_path if default_api_path else "" if not path.endswith(default_api_path or ""): path = path + default_api_path if default_api_path else "" full_url = urlunparse( (scheme, f"{net_loc}{port}", quote(path.replace("//", "/")), "", "", "") ) return full_url def __init__(self, system: System): super().__init__(system) system.settings.require("chroma_server_host") system.settings.require("chroma_server_http_port") self._opentelemetry_client = self.require(OpenTelemetryClient) self._product_telemetry_client = self.require(ProductTelemetryClient) self._settings = system.settings self._api_url = FastAPI.resolve_url( chroma_server_host=str(system.settings.chroma_server_host), chroma_server_http_port=system.settings.chroma_server_http_port, chroma_server_ssl_enabled=system.settings.chroma_server_ssl_enabled, default_api_path=system.settings.chroma_server_api_default_path, ) self._header = system.settings.chroma_server_headers if ( system.settings.chroma_client_auth_provider and system.settings.chroma_client_auth_protocol_adapter ): self._auth_provider = self.require( resolve_provider( system.settings.chroma_client_auth_provider, ClientAuthProvider ) ) self._adapter = cast( RequestsClientAuthProtocolAdapter, system.require( resolve_provider( system.settings.chroma_client_auth_protocol_adapter, RequestsClientAuthProtocolAdapter, ) ), ) self._session = self._adapter.session else: self._session = requests.Session() if self._header is not None: self._session.headers.update(self._header) if self._settings.chroma_server_ssl_verify is not None: self._session.verify = self._settings.chroma_server_ssl_verify def heartbeat(self) -> int: """Returns the current server time in nanoseconds to check if the server is alive""" resp = self._session.get(self._api_url) raise_chroma_error(resp) return int(json.loads(resp.text)["nanosecond heartbeat"]) def create_database( self, name: str, tenant: str = DEFAULT_TENANT, ) -> None: """Creates a database""" resp = self._session.post( self._api_url + "/databases", data=json.dumps({"name": name}), params={"tenant": tenant}, ) raise_chroma_error(resp) def get_database( self, name: str, tenant: str = DEFAULT_TENANT, ) -> Database: """Returns a database""" resp = self._session.get( self._api_url + "/databases/" + name, params={"tenant": tenant}, ) raise_chroma_error(resp) resp_json = json.loads(resp.text) return Database( id=resp_json["id"], name=resp_json["name"], tenant=resp_json["tenant"] ) def create_tenant(self, name: str) -> None: resp = self._session.post( self._api_url + "/tenants", data=json.dumps({"name": name}), ) raise_chroma_error(resp) def get_tenant(self, name: str) -> Tenant: resp = self._session.get( self._api_url + "/tenants/" + name, ) raise_chroma_error(resp) resp_json = json.loads(resp.text) return Tenant(name=resp_json["name"]) def list_collections( self, limit: Optional[int] = None, offset: Optional[int] = None, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> Sequence[Collection]: """Returns a list of all collections""" resp = self._session.get( self._api_url + "/collections", params={ "tenant": tenant, "database": database, "limit": limit, "offset": offset, }, ) raise_chroma_error(resp) json_collections = json.loads(resp.text) collections = [] for json_collection in json_collections: collections.append(Collection(self, **json_collection)) return collections def count_collections( self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE ) -> int: """Returns a count of collections""" resp = self._session.get( self._api_url + "/count_collections", params={"tenant": tenant, "database": database}, ) raise_chroma_error(resp) return cast(int, json.loads(resp.text)) def create_collection( self, name: str, metadata: Optional[CollectionMetadata] = None, embedding_function: Optional[ EmbeddingFunction[Embeddable] ] = ef.DefaultEmbeddingFunction(), # type: ignore data_loader: Optional[DataLoader[Loadable]] = None, get_or_create: bool = False, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> Collection: """Creates a collection""" resp = self._session.post( self._api_url + "/collections", data=json.dumps( { "name": name, "metadata": metadata, "get_or_create": get_or_create, } ), params={"tenant": tenant, "database": database}, ) raise_chroma_error(resp) resp_json = json.loads(resp.text) return Collection( client=self, id=resp_json["id"], name=resp_json["name"], embedding_function=embedding_function, data_loader=data_loader, metadata=resp_json["metadata"], ) def get_collection( self, name: str, id: Optional[UUID] = None, embedding_function: Optional[ EmbeddingFunction[Embeddable] ] = ef.DefaultEmbeddingFunction(), # type: ignore data_loader: Optional[DataLoader[Loadable]] = None, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> Collection: """Returns a collection""" if (name is None and id is None) or (name is not None and id is not None): raise ValueError("Name or id must be specified, but not both") _params = {"tenant": tenant, "database": database} if id is not None: _params["type"] = str(id) resp = self._session.get( self._api_url + "/collections/" + name if name else str(id), params=_params ) raise_chroma_error(resp) resp_json = json.loads(resp.text) return Collection( client=self, name=resp_json["name"], id=resp_json["id"], embedding_function=embedding_function, data_loader=data_loader, metadata=resp_json["metadata"], ) "FastAPI.get_or_create_collection", OpenTelemetryGranularity.OPERATION ) def get_or_create_collection( self, name: str, metadata: Optional[CollectionMetadata] = None, embedding_function: Optional[ EmbeddingFunction[Embeddable] ] = ef.DefaultEmbeddingFunction(), # type: ignore data_loader: Optional[DataLoader[Loadable]] = None, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> Collection: return cast( Collection, self.create_collection( name=name, metadata=metadata, embedding_function=embedding_function, data_loader=data_loader, get_or_create=True, tenant=tenant, database=database, ), ) def _modify( self, id: UUID, new_name: Optional[str] = None, new_metadata: Optional[CollectionMetadata] = None, ) -> None: """Updates a collection""" resp = self._session.put( self._api_url + "/collections/" + str(id), data=json.dumps({"new_metadata": new_metadata, "new_name": new_name}), ) raise_chroma_error(resp) def delete_collection( self, name: str, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> None: """Deletes a collection""" resp = self._session.delete( self._api_url + "/collections/" + name, params={"tenant": tenant, "database": database}, ) raise_chroma_error(resp) def _count( self, collection_id: UUID, ) -> int: """Returns the number of embeddings in the database""" resp = self._session.get( self._api_url + "/collections/" + str(collection_id) + "/count" ) raise_chroma_error(resp) return cast(int, json.loads(resp.text)) def _peek( self, collection_id: UUID, n: int = 10, ) -> GetResult: return cast( GetResult, self._get( collection_id, limit=n, include=["embeddings", "documents", "metadatas"], ), ) def _get( self, collection_id: UUID, ids: Optional[IDs] = None, where: Optional[Where] = {}, sort: Optional[str] = None, limit: Optional[int] = None, offset: Optional[int] = None, page: Optional[int] = None, page_size: Optional[int] = None, where_document: Optional[WhereDocument] = {}, include: Include = ["metadatas", "documents"], ) -> GetResult: if page and page_size: offset = (page - 1) * page_size limit = page_size resp = self._session.post( self._api_url + "/collections/" + str(collection_id) + "/get", data=json.dumps( { "ids": ids, "where": where, "sort": sort, "limit": limit, "offset": offset, "where_document": where_document, "include": include, } ), ) raise_chroma_error(resp) body = json.loads(resp.text) return GetResult( ids=body["ids"], embeddings=body.get("embeddings", None), metadatas=body.get("metadatas", None), documents=body.get("documents", None), data=None, uris=body.get("uris", None), ) def _delete( self, collection_id: UUID, ids: Optional[IDs] = None, where: Optional[Where] = {}, where_document: Optional[WhereDocument] = {}, ) -> IDs: """Deletes embeddings from the database""" resp = self._session.post( self._api_url + "/collections/" + str(collection_id) + "/delete", data=json.dumps( {"where": where, "ids": ids, "where_document": where_document} ), ) raise_chroma_error(resp) return cast(IDs, json.loads(resp.text)) def _submit_batch( self, batch: Tuple[ IDs, Optional[Embeddings], Optional[Metadatas], Optional[Documents], Optional[URIs], ], url: str, ) -> requests.Response: """ Submits a batch of embeddings to the database """ resp = self._session.post( self._api_url + url, data=json.dumps( { "ids": batch[0], "embeddings": batch[1], "metadatas": batch[2], "documents": batch[3], "uris": batch[4], } ), ) return resp def _add( self, ids: IDs, collection_id: UUID, embeddings: Embeddings, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, uris: Optional[URIs] = None, ) -> bool: """ Adds a batch of embeddings to the database - pass in column oriented data lists """ batch = (ids, embeddings, metadatas, documents, uris) validate_batch(batch, {"max_batch_size": self.max_batch_size}) resp = self._submit_batch(batch, "/collections/" + str(collection_id) + "/add") raise_chroma_error(resp) return True def _update( self, collection_id: UUID, ids: IDs, embeddings: Optional[Embeddings] = None, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, uris: Optional[URIs] = None, ) -> bool: """ Updates a batch of embeddings in the database - pass in column oriented data lists """ batch = (ids, embeddings, metadatas, documents, uris) validate_batch(batch, {"max_batch_size": self.max_batch_size}) resp = self._submit_batch( batch, "/collections/" + str(collection_id) + "/update" ) raise_chroma_error(resp) return True def _upsert( self, collection_id: UUID, ids: IDs, embeddings: Embeddings, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, uris: Optional[URIs] = None, ) -> bool: """ Upserts a batch of embeddings in the database - pass in column oriented data lists """ batch = (ids, embeddings, metadatas, documents, uris) validate_batch(batch, {"max_batch_size": self.max_batch_size}) resp = self._submit_batch( batch, "/collections/" + str(collection_id) + "/upsert" ) raise_chroma_error(resp) return True def _query( self, collection_id: UUID, query_embeddings: Embeddings, n_results: int = 10, where: Optional[Where] = {}, where_document: Optional[WhereDocument] = {}, include: Include = ["metadatas", "documents", "distances"], ) -> QueryResult: """Gets the nearest neighbors of a single embedding""" resp = self._session.post( self._api_url + "/collections/" + str(collection_id) + "/query", data=json.dumps( { "query_embeddings": query_embeddings, "n_results": n_results, "where": where, "where_document": where_document, "include": include, } ), ) raise_chroma_error(resp) body = json.loads(resp.text) return QueryResult( ids=body["ids"], distances=body.get("distances", None), embeddings=body.get("embeddings", None), metadatas=body.get("metadatas", None), documents=body.get("documents", None), uris=body.get("uris", None), data=None, ) def reset(self) -> bool: """Resets the database""" resp = self._session.post(self._api_url + "/reset") raise_chroma_error(resp) return cast(bool, json.loads(resp.text)) def get_version(self) -> str: """Returns the version of the server""" resp = self._session.get(self._api_url + "/version") raise_chroma_error(resp) return cast(str, json.loads(resp.text)) def get_settings(self) -> Settings: """Returns the settings of the client""" return self._settings def max_batch_size(self) -> int: if self._max_batch_size == -1: resp = self._session.get(self._api_url + "/pre-flight-checks") raise_chroma_error(resp) self._max_batch_size = cast(int, json.loads(resp.text)["max_batch_size"]) return self._max_batch_size The provided code snippet includes necessary dependencies for implementing the `instrument_fastapi` function. Write a Python function `def instrument_fastapi(app: FastAPI, excluded_urls: Optional[List[str]] = None) -> None` to solve the following problem: Instrument FastAPI to emit OpenTelemetry spans. Here is the function: def instrument_fastapi(app: FastAPI, excluded_urls: Optional[List[str]] = None) -> None: """Instrument FastAPI to emit OpenTelemetry spans.""" FastAPIInstrumentor.instrument_app( app, excluded_urls=",".join(excluded_urls) if excluded_urls else None )
Instrument FastAPI to emit OpenTelemetry spans.
154,691
import boto3 import json import subprocess import os import re The provided code snippet includes necessary dependencies for implementing the `b64text` function. Write a Python function `def b64text(txt)` to solve the following problem: Generate Base 64 encoded CF json for a multiline string, subbing in values where appropriate Here is the function: def b64text(txt): """Generate Base 64 encoded CF json for a multiline string, subbing in values where appropriate""" lines = [] for line in txt.splitlines(True): if "${" in line: lines.append({"Fn::Sub": line}) else: lines.append(line) return {"Fn::Base64": {"Fn::Join": ["", lines]}}
Generate Base 64 encoded CF json for a multiline string, subbing in values where appropriate
154,692
import abc import contextlib import io import logging import os import socket import subprocess import sys import threading import time import typing import packaging.version from ._proto import PROGRAM_NAME def get_binary_by_name(name: str) -> str: pyfilepath = os.path.abspath(__file__) abspath = os.path.join(os.path.dirname(pyfilepath), "binaries", sys.platform, name) if not os.path.isfile(abspath): raise RuntimeError("Binary file {} not exist".format(name)) return abspath
null
154,693
import abc import contextlib import io import logging import os import socket import subprocess import sys import threading import time import typing import packaging.version from ._proto import PROGRAM_NAME def get_current_ip() -> str: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable s.connect(('10.255.255.255', 1)) ip = s.getsockname()[0] except Exception: ip = '127.0.0.1' finally: s.close() return ip
null
154,694
import abc import contextlib import io import logging import os import socket import subprocess import sys import threading import time import typing import packaging.version from ._proto import PROGRAM_NAME The provided code snippet includes necessary dependencies for implementing the `pathjoin` function. Write a Python function `def pathjoin(path: str, *paths) -> str` to solve the following problem: join path with unix file sep: / Here is the function: def pathjoin(path: str, *paths) -> str: """ join path with unix file sep: / """ parts = [path.rstrip("/\\")] for p in paths: parts.append(p.strip("/\\")) return '/'.join(parts)
join path with unix file sep: /
154,695
import abc import contextlib import io import logging import os import socket import subprocess import sys import threading import time import typing import packaging.version from ._proto import PROGRAM_NAME The provided code snippet includes necessary dependencies for implementing the `exec_command` function. Write a Python function `def exec_command(cmds: typing.List[str], logfile)` to solve the following problem: Args: cmds: list of program and args logfile: output command output to this file Here is the function: def exec_command(cmds: typing.List[str], logfile): """ Args: cmds: list of program and args logfile: output command output to this file """ with open(logfile, 'ab') as fout: p = subprocess.Popen(cmds, stdout=fout, stderr=subprocess.STDOUT) try: yield p finally: p.terminate() try: p.wait(3) except subprocess.TimeoutExpired: p.kill()
Args: cmds: list of program and args logfile: output command output to this file
154,696
import abc import contextlib import io import logging import os import socket import subprocess import sys import threading import time import typing import packaging.version from ._proto import PROGRAM_NAME The provided code snippet includes necessary dependencies for implementing the `set_socket_timeout` function. Write a Python function `def set_socket_timeout(conn: typing.Union[typing.Callable[..., socket.socket], socket.socket], value: float)` to solve the following problem: Set conn.timeout to value Save previous value, yield, and then restore the previous value If 'value' is None, do nothing Here is the function: def set_socket_timeout(conn: typing.Union[typing.Callable[..., socket.socket], socket.socket], value: float): """Set conn.timeout to value Save previous value, yield, and then restore the previous value If 'value' is None, do nothing """ def get_conn() -> socket.socket: return conn() if callable(conn) else conn old_value = get_conn().timeout get_conn().settimeout(value) try: yield finally: try: get_conn().settimeout(old_value) except: pass
Set conn.timeout to value Save previous value, yield, and then restore the previous value If 'value' is None, do nothing
154,697
import abc import contextlib import io import logging import os import socket import subprocess import sys import threading import time import typing import packaging.version from ._proto import PROGRAM_NAME The provided code snippet includes necessary dependencies for implementing the `semver_compare` function. Write a Python function `def semver_compare(ver1: str, ver2: str) -> int` to solve the following problem: Compare two semver strings Args: ver1: "1.2.3" ver2: "1.2.3" Returns: 1 if ver1 > ver2 0 if ver1 == ver2 -1 if ver1 < ver2 Here is the function: def semver_compare(ver1: str, ver2: str) -> int: """Compare two semver strings Args: ver1: "1.2.3" ver2: "1.2.3" Returns: 1 if ver1 > ver2 0 if ver1 == ver2 -1 if ver1 < ver2 """ v1 = packaging.version.Version(ver1) v2 = packaging.version.Version(ver2) if v1 == v2: return 0 return 1 if v1 > v2 else -1
Compare two semver strings Args: ver1: "1.2.3" ver2: "1.2.3" Returns: 1 if ver1 > ver2 0 if ver1 == ver2 -1 if ver1 < ver2
154,698
import logging import os import plistlib import socket import ssl import struct import threading import typing import weakref from typing import Any, Union from ._proto import UsbmuxMessageType, LOG from ._utils import set_socket_timeout from .exceptions import * logger = logging.getLogger(LOG.socket) _n = [0] _nlock = threading.Lock() _id_numbers = [] def acquire_uid() -> int: _id = None with _nlock: _n[0] += 1 _id_numbers.append(_n[0]) _id = _n[0] logger.debug("Opening socket: id=%d", _id) return _id
null
154,699
import logging import os import plistlib import socket import ssl import struct import threading import typing import weakref from typing import Any, Union from ._proto import UsbmuxMessageType, LOG from ._utils import set_socket_timeout from .exceptions import * logger = logging.getLogger(LOG.socket) _id_numbers = [] def release_uid(id: int): try: _id_numbers.remove(id) except ValueError: pass logger.debug("Closing socket, id=%d", id)
null
154,700
import os import shutil import tempfile import time import typing import zipfile from typing import List import retry import requests from ._safe_socket import PlistSocketProxy from ._utils import get_app_dir, logger from .exceptions import DeveloperImageError, MuxError, MuxServiceError, DownloadError def cache_developer_image(version: str) -> str: """ download developer image from github to local return image_zip_path """ _alias = { "12.5": "12.4", "15.8": "15.5", # "16.5": "17.0", } if version in _alias: version = _alias[version] logger.info("Use alternative developer image %s", version) # Default download image from https://github.com/JinjunHan/iOSDeviceSupport image_urls = _get_developer_image_url_list(version) # $HOME/.tidevice/device-support/12.2.zip local_device_support = get_app_dir("device-support") image_zip_path = os.path.join(local_device_support, version+".zip") if not zipfile.is_zipfile(image_zip_path): err = None for url in image_urls: try: _urlretrieve(url, image_zip_path) if zipfile.is_zipfile(image_zip_path): err = None break err = Exception("image file not zip") except requests.HTTPError as e: err = e if e.response.status_code == 404: break except requests.RequestException as e: err = e if err: raise err return image_zip_path def get_app_dir(*paths) -> str: home = os.path.expanduser("~") appdir = os.path.join(home, "." + PROGRAM_NAME) if paths: appdir = os.path.join(appdir, *paths) os.makedirs(appdir, exist_ok=True) return appdir class DeveloperImageError(BaseError): """ Developer image error """ The provided code snippet includes necessary dependencies for implementing the `get_developer_image_path` function. Write a Python function `def get_developer_image_path(version: str) -> str` to solve the following problem: return developer image path Raises: - DeveloperImageError - DownloadError Here is the function: def get_developer_image_path(version: str) -> str: """ return developer image path Raises: - DeveloperImageError - DownloadError """ if version.startswith("17."): raise DeveloperImageError("iOS 17.x is not supported yet") image_zip_path = cache_developer_image(version) image_path = get_app_dir("device-support/"+version) if os.path.isfile(os.path.join(image_path, "DeveloperDiskImage.dmg")): return image_path # 解压下载的zip文件 with tempfile.TemporaryDirectory() as tmpdir: zf = zipfile.ZipFile(image_zip_path) zf.extractall(tmpdir) rootfiles = os.listdir(tmpdir) rootdirs = [] for fname in rootfiles: if fname.startswith("_") or fname.startswith("."): continue if os.path.isdir(os.path.join(tmpdir, fname)): rootdirs.append(fname) dmg_path = tmpdir if len(rootfiles) == 0: # empty zip raise DeveloperImageError("deviceSupport zip file is empty") elif version in rootdirs: # contains directory: {version} dmg_path = os.path.join(tmpdir, version) elif len(rootdirs) == 1: # only contain one directory dmg_path = os.path.join(tmpdir, rootdirs[0]) if not os.path.isfile(os.path.join(dmg_path, "DeveloperDiskImage.dmg")): raise DeveloperImageError("deviceSupport zip file is invalid") os.makedirs(image_path, exist_ok=True) for filename in ("DeveloperDiskImage.dmg", "DeveloperDiskImage.dmg.signature"): shutil.copyfile(os.path.join(dmg_path, filename), os.path.join(image_path, filename)) return image_path
return developer image path Raises: - DeveloperImageError - DownloadError
154,701
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError um: Usbmux = None def _print_json(value): def _bytes_hook(obj): if isinstance(obj, bytes): return base64.b64encode(obj).decode() else: return str(obj) print(json.dumps(value, indent=4, ensure_ascii=False, default=_bytes_hook)) Device = BaseDevice MODELS = { # iPhone "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5", "iPhone5,3": "iPhone 5c", "iPhone5,4": "iPhone 5c", "iPhone6,1": "iPhone 5s", "iPhone6,2": "iPhone 5s", "iPhone7,1": "iPhone 6 Plus", "iPhone7,2": "iPhone 6", "iPhone8,1": "iPhone 6s", "iPhone8,2": "iPhone 6s Plus", "iPhone8,4": "iPhone SE (1st generation)", "iPhone9,1": "iPhone 7", # Global "iPhone9,2": "iPhone 7 Plus", # Global "iPhone9,3": "iPhone 7", # GSM "iPhone9,4": "iPhone 7 Plus", # GSM "iPhone10,1": "iPhone 8", # Global "iPhone10,2": "iPhone 8 Plus", # Global "iPhone10,3": "iPhone X", # Global "iPhone10,4": "iPhone 8", # GSM "iPhone10,5": "iPhone 8 Plus", # GSM "iPhone10,6": "iPhone X", # GSM "iPhone11,2": "iPhone XS", "iPhone11,4": "iPhone XS Max", "iPhone11,6": "iPhone XS Max", "iPhone11,8": "iPhone XR", "iPhone12,1": "iPhone 11", "iPhone12,3": "iPhone 11 Pro", "iPhone12,5": "iPhone 11 Pro Max", "iPhone12,8": "iPhone SE (2nd generation)", "iPhone13,1": "iPhone 12 mini", "iPhone13,2": "iPhone 12", "iPhone13,3": "iPhone 12 Pro", "iPhone13,4": "iPhone 12 Pro Max", "iPhone14,2": "iPhone 13 Pro", "iPhone14,3": "iPhone 13 Pro Max", "iPhone14,4": "iPhone 13 mini", "iPhone14,5": "iPhone 13", "iPhone14,6": "iPhone SE (3rd generation)", "iPhone14,7": "iPhone 14", "iPhone14,8": "iPhone 14 Plus", "iPhone15,2": "iPhone 14 Pro", "iPhone15,3": "iPhone 14 Pro Max", # iPad mini "iPad2,5": "iPad mini", "iPad2,6": "iPad mini", "iPad2,7": "iPad mini", "iPad4,4": "iPad mini 2", "iPad4,5": "iPad mini 2", "iPad4,6": "iPad mini 2", "iPad4,7": "iPad mini 3", "iPad4,8": "iPad mini 3", "iPad4,9": "iPad mini 3", "iPad5,1": "iPad mini 4", "iPad5,2": "iPad mini 4", "iPad11,1": "iPad mini (5th generation)", "iPad11,2": "iPad mini (5th generation)", "iPad14,1": "iPad mini (6th generation)", "iPad14,2": "iPad mini (6th generation)", # iPad "iPad1,1": "iPad 1", "iPad2,1": "iPad (2rd generation)", "iPad2,2": "iPad (2rd generation)", "iPad2,3": "iPad (2rd generation)", "iPad2,4": "iPad (2rd generation)", "iPad3,1": "iPad (3rd generation)", "iPad3,2": "iPad (3rd generation)", "iPad3,3": "iPad (3rd generation)", "iPad3,4": "iPad (4rd generation)", "iPad3,5": "iPad (4rd generation)", "iPad3,6": "iPad (4rd generation)", "iPad6,11": "iPad (5th generation)", "iPad6,12": "iPad (5th generation)", "iPad7,5": "iPad (6th generation)", "iPad7,6": "iPad (6th generation)", "iPad7,11": "iPad (7th generation)", "iPad7,12": "iPad (7th generation)", "iPad11,6": "iPad (8th generation)", "iPad11,7": "iPad (8th generation)", "iPad12,1": "iPad (9th generation)", "iPad12,2": "iPad (9th generation)", # iPad Air "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air", "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2", "iPad13,1": "iPad Air (4th generation)", "iPad13,2": "iPad Air (4th generation)", "iPad11,3": "iPad Air (3th generation)", "iPad11,4": "iPad Air (3th generation)", "iPad13,1": "iPad Air (4th generation)", "iPad13,2": "iPad Air (4th generation)", # iPad Pro "iPad6,3": "iPad Pro (9.7-inch)", "iPad6,4": "iPad Pro (9.7-inch)", "iPad6,7": "iPad Pro (12.9-inch)", "iPad6,8": "iPad Pro (12.9-inch)", "iPad7,1": "iPad Pro (12.9-inch) (2nd generation)", "iPad7,2": "iPad Pro (12.9-inch) (2nd generation)", "iPad7,3": "iPad Pro (10.5-inch)", "iPad7,4": "iPad Pro (10.5-inch)", "iPad8,1": "iPad Pro (11-inch)", "iPad8,2": "iPad Pro (11-inch)", "iPad8,3": "iPad Pro (11-inch)", "iPad8,4": "iPad Pro (11-inch)", "iPad8,5": "iPad Pro (12.9-inch) (3rd generation)", "iPad8,6": "iPad Pro (12.9-inch) (3rd generation)", "iPad8,7": "iPad Pro (12.9-inch) (3rd generation)", "iPad8,8": "iPad Pro (12.9-inch) (3rd generation)", "iPad8,9": "iPad Pro (11-inch) (2nd generation)", "iPad8,10": "iPad Pro (11-inch) (2nd generation)", "iPad8,11": "iPad Pro (12.9-inch) (4th generation)", "iPad8,12": "iPad Pro (12.9-inch) (4th generation)", "iPad13,4": "iPad Pro (11-inch) (3rd generation)", "iPad13,5": "iPad Pro (11-inch) (3rd generation)", "iPad13,6": "iPad Pro (11-inch) (3rd generation)", "iPad13,7": "iPad Pro (11-inch) (3rd generation)", "iPad13,8": "iPad Pro (12.9-inch) (5th generation)", "iPad13,9": "iPad Pro (12.9-inch) (5th generation)", "iPad13,10": "iPad Pro (12.9-inch) (5th generation)", "iPad13,11": "iPad Pro (12.9-inch) (5th generation)", # simulator "i386": "iPhone Simulator", "x86_64": "iPhone Simulator", # TODO iPod touch, etc ... } class ConnectionType(str, enum.Enum): USB = "usb" NETWORK = "network" class MuxError(BaseError): """ Mutex error """ pass def cmd_list(args: argparse.Namespace): _json: typing.Final[bool] = args.json ds = um.device_list() if args.usb: ds = [info for info in ds if info.conn_type == ConnectionType.USB] if args.one: for info in ds: print(info.udid) return headers = ['UDID', 'SerialNumber', 'NAME', 'MarketName', 'ProductVersion', "ConnType"] keys = ["udid", "serial", "name", "market_name", "product_version", "conn_type"] tabdata = [] for dinfo in ds: udid, conn_type = dinfo.udid, dinfo.conn_type try: _d = Device(udid, um) name = _d.name serial = _d.get_value("SerialNumber") tabdata.append([udid, serial, name, MODELS.get(_d.product_type, "-"), _d.product_version, conn_type]) except MuxError: name = "" if _json: result = [] for item in tabdata: result.append({key: item[idx] for idx, key in enumerate(keys)}) _print_json(result) else: print(tabulate(tabdata, headers=headers, tablefmt="plain"))
null
154,702
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def _print_json(value): def _bytes_hook(obj): if isinstance(obj, bytes): return base64.b64encode(obj).decode() else: return str(obj) print(json.dumps(value, indent=4, ensure_ascii=False, default=_bytes_hook)) MODELS = { # iPhone "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5", "iPhone5,3": "iPhone 5c", "iPhone5,4": "iPhone 5c", "iPhone6,1": "iPhone 5s", "iPhone6,2": "iPhone 5s", "iPhone7,1": "iPhone 6 Plus", "iPhone7,2": "iPhone 6", "iPhone8,1": "iPhone 6s", "iPhone8,2": "iPhone 6s Plus", "iPhone8,4": "iPhone SE (1st generation)", "iPhone9,1": "iPhone 7", # Global "iPhone9,2": "iPhone 7 Plus", # Global "iPhone9,3": "iPhone 7", # GSM "iPhone9,4": "iPhone 7 Plus", # GSM "iPhone10,1": "iPhone 8", # Global "iPhone10,2": "iPhone 8 Plus", # Global "iPhone10,3": "iPhone X", # Global "iPhone10,4": "iPhone 8", # GSM "iPhone10,5": "iPhone 8 Plus", # GSM "iPhone10,6": "iPhone X", # GSM "iPhone11,2": "iPhone XS", "iPhone11,4": "iPhone XS Max", "iPhone11,6": "iPhone XS Max", "iPhone11,8": "iPhone XR", "iPhone12,1": "iPhone 11", "iPhone12,3": "iPhone 11 Pro", "iPhone12,5": "iPhone 11 Pro Max", "iPhone12,8": "iPhone SE (2nd generation)", "iPhone13,1": "iPhone 12 mini", "iPhone13,2": "iPhone 12", "iPhone13,3": "iPhone 12 Pro", "iPhone13,4": "iPhone 12 Pro Max", "iPhone14,2": "iPhone 13 Pro", "iPhone14,3": "iPhone 13 Pro Max", "iPhone14,4": "iPhone 13 mini", "iPhone14,5": "iPhone 13", "iPhone14,6": "iPhone SE (3rd generation)", "iPhone14,7": "iPhone 14", "iPhone14,8": "iPhone 14 Plus", "iPhone15,2": "iPhone 14 Pro", "iPhone15,3": "iPhone 14 Pro Max", # iPad mini "iPad2,5": "iPad mini", "iPad2,6": "iPad mini", "iPad2,7": "iPad mini", "iPad4,4": "iPad mini 2", "iPad4,5": "iPad mini 2", "iPad4,6": "iPad mini 2", "iPad4,7": "iPad mini 3", "iPad4,8": "iPad mini 3", "iPad4,9": "iPad mini 3", "iPad5,1": "iPad mini 4", "iPad5,2": "iPad mini 4", "iPad11,1": "iPad mini (5th generation)", "iPad11,2": "iPad mini (5th generation)", "iPad14,1": "iPad mini (6th generation)", "iPad14,2": "iPad mini (6th generation)", # iPad "iPad1,1": "iPad 1", "iPad2,1": "iPad (2rd generation)", "iPad2,2": "iPad (2rd generation)", "iPad2,3": "iPad (2rd generation)", "iPad2,4": "iPad (2rd generation)", "iPad3,1": "iPad (3rd generation)", "iPad3,2": "iPad (3rd generation)", "iPad3,3": "iPad (3rd generation)", "iPad3,4": "iPad (4rd generation)", "iPad3,5": "iPad (4rd generation)", "iPad3,6": "iPad (4rd generation)", "iPad6,11": "iPad (5th generation)", "iPad6,12": "iPad (5th generation)", "iPad7,5": "iPad (6th generation)", "iPad7,6": "iPad (6th generation)", "iPad7,11": "iPad (7th generation)", "iPad7,12": "iPad (7th generation)", "iPad11,6": "iPad (8th generation)", "iPad11,7": "iPad (8th generation)", "iPad12,1": "iPad (9th generation)", "iPad12,2": "iPad (9th generation)", # iPad Air "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air", "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2", "iPad13,1": "iPad Air (4th generation)", "iPad13,2": "iPad Air (4th generation)", "iPad11,3": "iPad Air (3th generation)", "iPad11,4": "iPad Air (3th generation)", "iPad13,1": "iPad Air (4th generation)", "iPad13,2": "iPad Air (4th generation)", # iPad Pro "iPad6,3": "iPad Pro (9.7-inch)", "iPad6,4": "iPad Pro (9.7-inch)", "iPad6,7": "iPad Pro (12.9-inch)", "iPad6,8": "iPad Pro (12.9-inch)", "iPad7,1": "iPad Pro (12.9-inch) (2nd generation)", "iPad7,2": "iPad Pro (12.9-inch) (2nd generation)", "iPad7,3": "iPad Pro (10.5-inch)", "iPad7,4": "iPad Pro (10.5-inch)", "iPad8,1": "iPad Pro (11-inch)", "iPad8,2": "iPad Pro (11-inch)", "iPad8,3": "iPad Pro (11-inch)", "iPad8,4": "iPad Pro (11-inch)", "iPad8,5": "iPad Pro (12.9-inch) (3rd generation)", "iPad8,6": "iPad Pro (12.9-inch) (3rd generation)", "iPad8,7": "iPad Pro (12.9-inch) (3rd generation)", "iPad8,8": "iPad Pro (12.9-inch) (3rd generation)", "iPad8,9": "iPad Pro (11-inch) (2nd generation)", "iPad8,10": "iPad Pro (11-inch) (2nd generation)", "iPad8,11": "iPad Pro (12.9-inch) (4th generation)", "iPad8,12": "iPad Pro (12.9-inch) (4th generation)", "iPad13,4": "iPad Pro (11-inch) (3rd generation)", "iPad13,5": "iPad Pro (11-inch) (3rd generation)", "iPad13,6": "iPad Pro (11-inch) (3rd generation)", "iPad13,7": "iPad Pro (11-inch) (3rd generation)", "iPad13,8": "iPad Pro (12.9-inch) (5th generation)", "iPad13,9": "iPad Pro (12.9-inch) (5th generation)", "iPad13,10": "iPad Pro (12.9-inch) (5th generation)", "iPad13,11": "iPad Pro (12.9-inch) (5th generation)", # simulator "i386": "iPhone Simulator", "x86_64": "iPhone Simulator", # TODO iPod touch, etc ... } def cmd_device_info(args: argparse.Namespace): d = _udid2device(args.udid) value = d.get_value(no_session=args.simple, key=args.key, domain=args.domain) if args.json: _print_json(value) elif args.key or args.domain: pprint(value) else: print("{:17s} {}".format("MarketName:", MODELS.get(value['ProductType']))) for attr in ('DeviceName', 'ProductVersion', 'ProductType', 'ModelNumber', 'SerialNumber', 'PhoneNumber', 'CPUArchitecture', 'ProductName', 'ProtocolVersion', 'RegionInfo', 'TimeIntervalSince1970', 'TimeZone', 'UniqueDeviceID', 'WiFiAddress', 'BluetoothAddress', 'BasebandVersion'): print("{:17s} {}".format(attr + ":", value.get(attr)))
null
154,703
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_date(args: argparse.Namespace): d = _udid2device(args.udid) value = d.get_value() or {} timestamp = value.get("TimeIntervalSince1970") if args.timestamp: print(timestamp) else: print(datetime.fromtimestamp(int(timestamp)))
null
154,704
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError PROGRAM_NAME = "tidevice" try: __version__ = pkg_resources.get_distribution(PROGRAM_NAME).version except pkg_resources.DistributionNotFound: __version__ = "unknown" def cmd_version(args: argparse.Namespace): print(PROGRAM_NAME, "version", __version__)
null
154,705
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError logger = logging.getLogger(__name__) def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_install(args: argparse.Namespace): d = _udid2device(args.udid) bundle_id = d.app_install(args.filepath_or_url) if args.launch: with d.connect_instruments() as ts: pid = ts.app_launch(bundle_id) logger.info("Launch %r, process pid: %d", bundle_id, pid)
null
154,706
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: def cmd_uninstall(args: argparse.Namespace): d = _udid2device(args.udid) ok = d.app_uninstall(args.bundle_id) if not ok: sys.exit(1)
null
154,707
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_reboot(args: argparse.Namespace): d = _udid2device(args.udid) print(d.reboot())
null
154,708
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_shutdown(args: argparse.Namespace): d = _udid2device(args.udid) print(d.shutdown())
null
154,709
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError class IPAReader(zipfile.ZipFile): def get_infoplist_zipinfo(self) -> zipfile.ZipInfo: re_infoplist = re.compile(r"^Payload/[^/]+\.app/Info.plist$") for zipinfo in self.filelist: if re_infoplist.match(zipinfo.filename): return zipinfo raise IPAError("Info.plist not found") def get_mobileprovision_zipinfo(self) -> zipfile.ZipInfo: re_provision_file = re.compile(r"^Payload/[^/]+\.app/embedded.mobileprovision$") for zipinfo in self.filelist: if re_provision_file.match(zipinfo.filename): return zipinfo raise IPAError("embedded.mobileprovision not found") def get_mobileprovision(self) -> dict: """ mobileprovision usally contains keys AppIDName, ApplicationIdentifierPrefix, CreationDate, Platform, IsXcodeManaged, DeveloperCertificates, Entitlements, ExpirationDate, Name, ProvisionedDevices, TeamIdentifier, TeamName, TimeToLive, UUID, Version """ provision_xml_rx = re.compile(br'<\?xml.+</plist>', re.DOTALL) content = self.read(self.get_mobileprovision_zipinfo()) match = provision_xml_rx.search(content) if match: xml_content = match.group() data = plistlib2.loads(xml_content) return data else: raise IPAError('unable to parse embedded.mobileprovision file') def get_infoplist(self) -> dict: finfo = self.get_infoplist_zipinfo() with self.open(finfo, 'r') as fp: if sys.version_info[:2] <= (3, 6): # for compatiable with py3.6 with tempfile.TemporaryFile() as tmpf: shutil.copyfileobj(fp, tmpf) tmpf.seek(0) return bplist.load(tmpf) return bplist.load(fp) def get_bundle_id(self) -> str: """ return CFBundleIdentifier """ return self.get_infoplist()['CFBundleIdentifier'] def get_short_version(self) -> str: return self.get_infoplist().get('CFBundleShortVersionString', "") def dump_info(self, all: bool = False): data = self.get_infoplist() print("BundleID:", data['CFBundleIdentifier']) print("ShortVersion:", data['CFBundleShortVersionString']) if all: m = self.get_mobileprovision() pprint(m['ProvisionedDevices']) def cmd_parse(args: argparse.Namespace): uri = args.uri _all = args.all fp = None if re.match(r"^https?://", uri): try: import httpio except ImportError: print("Install missing lib: httpip") retcode = subprocess.call( [sys.executable, '-m', 'pip', 'install', '-U', 'httpio']) assert retcode == 0 import httpio fp = httpio.open(uri, block_size=-1) else: assert os.path.isfile(uri) fp = open(uri, 'rb') try: ir = IPAReader(fp) ir.dump_info(all=_all) finally: fp.close()
null
154,710
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError um: Usbmux = None logger = logging.getLogger(__name__) The provided code snippet includes necessary dependencies for implementing the `cmd_watch` function. Write a Python function `def cmd_watch(args: argparse.Namespace)` to solve the following problem: Info example: {'DeviceID': 13, 'MessageType': 'Attached', 'Properties': {'ConnectionSpeed': 480000000, 'ConnectionType': 'USB', 'DeviceID': 13, 'LocationID': 340918272, 'ProductID': 4776, 'SerialNumber': '84ad172e22d8372eb752f413280722cdcc200954', 'USBSerialNumber': '84ad172e22d8372eb752f413280722cdcc200954'}} Here is the function: def cmd_watch(args: argparse.Namespace): """ Info example: {'DeviceID': 13, 'MessageType': 'Attached', 'Properties': {'ConnectionSpeed': 480000000, 'ConnectionType': 'USB', 'DeviceID': 13, 'LocationID': 340918272, 'ProductID': 4776, 'SerialNumber': '84ad172e22d8372eb752f413280722cdcc200954', 'USBSerialNumber': '84ad172e22d8372eb752f413280722cdcc200954'}} """ for info in um.watch_device(): logger.info("%s", pformat(info))
Info example: {'DeviceID': 13, 'MessageType': 'Attached', 'Properties': {'ConnectionSpeed': 480000000, 'ConnectionType': 'USB', 'DeviceID': 13, 'LocationID': 340918272, 'ProductID': 4776, 'SerialNumber': '84ad172e22d8372eb752f413280722cdcc200954', 'USBSerialNumber': '84ad172e22d8372eb752f413280722cdcc200954'}}
154,711
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError logger = logging.getLogger(__name__) class Usbmux: def __init__(self, address: Optional[Union[str, tuple]] = None): if address is None: if os.name == "posix": # linux or darwin address = "/var/run/usbmuxd" elif os.name == "nt": # windows address = ('127.0.0.1', 27015) else: raise EnvironmentError("Unsupported os.name", os.name) self.__address = address self.__tag = 0 def address(self) -> str: if isinstance(self.__address, str): return self.__address ip, port = self.__address return f"{ip}:{port}" def _next_tag(self) -> int: self.__tag += 1 return self.__tag def create_connection(self) -> PlistSocketProxy: psock = PlistSocket(self.__address, self._next_tag()) return PlistSocketProxy(psock) def send_recv(self, payload: dict, timeout: float = None) -> dict: s = self.create_connection() data = s.send_recv_packet(payload, timeout) self._check(data) return data def device_list(self) -> typing.List[DeviceInfo]: """ Return DeviceInfo and contains bother USB and NETWORK device Data processing example: {'DeviceList': [{'DeviceID': 37, 'MessageType': 'Attached', 'Properties': {'ConnectionSpeed': 480000000, 'ConnectionType': 'USB', 'DeviceID': 37, 'LocationID': 341966848, 'ProductID': 4776, 'SerialNumber': '539c5fffb18f2be0bf7f771d68f7c327fb68d2d9', 'UDID': '539c5fffb18f2be0bf7f771d68f7c327fb68d2d9', 'USBSerialNumber': '539c5fffb18f2be0bf7f771d68f7c327fb68d2d9'}}]} """ payload = { "MessageType": "ListDevices", # 必选 "ClientVersionString": "libusbmuxd 1.1.0", "ProgName": PROGRAM_NAME, "kLibUSBMuxVersion": 3, # "ProcessID": 0, # Xcode send it processID } data = self.send_recv(payload, timeout=10) result = {} for item in data['DeviceList']: prop = item['Properties'] prop['ConnectionType'] = prop['ConnectionType'].lower() # 兼容旧代码 info = DeviceInfo.from_json(prop) # always skip network device if info.udid in result and info.conn_type == ConnectionType.NETWORK: continue result[info.udid] = info return list(result.values()) def device_udid_list(self) -> typing.List[str]: return [d.udid for d in self.device_list()] def _check(self, data: dict): if 'Number' in data and data['Number'] != 0: raise MuxReplyError(data['Number']) def read_system_BUID(self) -> str: """ BUID is always same """ data = self.send_recv({ 'ClientVersionString': 'libusbmuxd 1.1.0', 'MessageType': 'ReadBUID', 'ProgName': PROGRAM_NAME, 'kLibUSBMuxVersion': 3 }) return data['BUID'] def _gen_host_id(self): hostname = platform.node() hostid = uuid.uuid3(uuid.NAMESPACE_DNS, hostname) return str(hostid).upper() def watch_device(self) -> typing.Iterator[dict]: """ Return iterator of data as follows - {'DeviceID': 59, 'MessageType': 'Detached'} - {'DeviceID': 59, 'MessageType': 'Attached', 'Properties': { 'ConnectionSpeed': 100, 'ConnectionType': 'USB', 'DeviceID': 59, 'LocationID': 341966848, 'ProductID': 4776, 'SerialNumber': 'xxx.xxx', 'USBSerialNumber': 'xxxx..xxx'}} """ with self.create_connection() as s: s.send_packet({ 'ClientVersionString': 'qt4i-usbmuxd', 'MessageType': 'Listen', 'ProgName': 'tcprelay' }) data = s.recv_packet() self._check(data) while True: data = s.recv_packet(header_size=16) yield data def connect_device_port(self, devid: int, port: int) -> PlistSocketProxy: """ Create connection to mobile phone """ _port = socket.htons(port) # Same as: ((port & 0xff) << 8) | (port >> 8) del (port) conn = self.create_connection() payload = { 'DeviceID': devid, # Required 'MessageType': 'Connect', # Required 'PortNumber': _port, # Required 'ProgName': PROGRAM_NAME, } logger.debug("Send payload: %s", payload) data = conn.send_recv_packet(payload) self._check(data) logger.debug("connected to port: %d", _port) return conn def cmd_wait_for_device(args): u = Usbmux(args.socket) for info in u.watch_device(): logger.debug("%s", pformat(info)) if info['MessageType'] != 'Attached': continue udid = info['Properties']['SerialNumber'] if args.udid is None: break if udid == args.udid: print("Device {!r} attached".format( info['Properties']['SerialNumber'])) break
null
154,712
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError logger = logging.getLogger(__name__) def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) class LOG(str, enum.Enum): root = "tidevice" xcuitest = "tidevice.xctest" xcuitest_process_log = "tidevice.xctest.test_process_log" xcuitest_console_log = "tidevice.xctest.test_console_log" socket = "tidevice.socket" The provided code snippet includes necessary dependencies for implementing the `cmd_xcuitest` function. Write a Python function `def cmd_xcuitest(args: argparse.Namespace)` to solve the following problem: Run XCTest required WDA installed. Here is the function: def cmd_xcuitest(args: argparse.Namespace): """ Run XCTest required WDA installed. """ log_level = logging.DEBUG if args.debug else logging.INFO setup_logger(LOG.xcuitest, level=log_level) if args.process_log_path: logger.info('XCUITest test process log file path: %s', args.process_log_path) # Use the default formatter that is a no-op formatter. setup_logger(LOG.xcuitest_process_log, logfile=args.process_log_path, disableStderrLogger=True, # Disable console logging. level=log_level, formatter=logging.Formatter()) if args.console_log_path: logger.info('XCUITest test output file path: %s', args.console_log_path) # Use the default formatter that is a no-op formatter. setup_logger(LOG.xcuitest_console_log, logfile=args.console_log_path, disableStderrLogger=True, # Disable console logging. level=log_level, formatter=logging.Formatter()) d = _udid2device(args.udid) env = {} for kv in args.env or []: key, val = kv.split(":", 1) env[key] = val if env: logger.info("Launch env: %s", env) test_runner_args = [] if args.test_runner_args: test_runner_args = args.test_runner_args.split(',') logger.info("Launch test runner args: %s", test_runner_args) target_app_env = dict( token.split(":", 1) for token in args.target_app_env or []) if target_app_env: logger.info("Target app env: %s", target_app_env) target_app_args = [] if args.target_app_args: target_app_args = args.target_app_args.split(',') logger.info("Target app args: %s", target_app_args) tests_to_run = set() if args.tests_to_run: tests_to_run = set(args.tests_to_run.strip().split(',')) logger.info("Target app args: %s", target_app_args) d.runwda(args.bundle_id, target_bundle_id=args.target_bundle_id, test_runner_env=env, test_runner_args=test_runner_args, target_app_env=target_app_env, target_app_args=target_app_args, tests_to_run=tests_to_run)
Run XCTest required WDA installed.
154,713
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: def cmd_screenshot(args: argparse.Namespace): d = _udid2device(args.udid) filename = args.filename or "screenshot.jpg" d.screenshot().convert("RGB").save(filename) print("Screenshot saved to", filename)
null
154,714
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: def _print_json(value): def cmd_appinfo(args: argparse.Namespace): d = _udid2device(args.udid) info = d.installation.lookup(args.bundle_id) if info is None: sys.exit(1) if args.json: _print_json(info) else: pprint(info)
null
154,715
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_applist(args: argparse.Namespace): d = _udid2device(args.udid) # appinfos = d.installation.list_installed() # apps = d.instruments.app_list() # pprint(apps) _type = args.type app_type = { "user": "User", "system": "System", "all": None, }[_type] for info in d.installation.iter_installed(app_type=app_type): # bundle_path = info['BundlePath'] bundle_id = info['CFBundleIdentifier'] try: display_name = info['CFBundleDisplayName'] # major.minor.patch version = info.get('CFBundleShortVersionString', '') print(bundle_id, display_name, version) except BrokenPipeError: break # print(" ".join( # (bundle_path, bundle_id, info['DisplayName'], # info.get('Version', ''), info['Type'])))
null
154,716
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError logger = logging.getLogger(__name__) def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) class ServiceError(MuxError): """ Service error """ def cmd_energy(args: argparse.Namespace): if args.kill: logger.warning("kill is deprecated, kill is always True now") d = _udid2device(args.udid) ts = d.connect_instruments() try: pid = ts.app_launch(args.bundle_id, args=args.arguments) ts.start_energy_sampling(pid) while True: ret = ts.get_process_energy_stats(pid) if ret != None: print(json.dumps(ret)) time.sleep(1.0) except ServiceError as e: sys.exit(e)
null
154,717
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError logger = logging.getLogger(__name__) def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_launch(args: argparse.Namespace): if args.skip_running: logger.warning("skip_running is deprecated, always kill app now") d = _udid2device(args.udid) env = {} for kv in args.env or []: key, val = kv.split(":", 1) env[key] = val if env: logger.info("App launch env: %s", env) pid = d.app_start(args.bundle_id, args=args.arguments, env=env) print("PID:", pid)
null
154,718
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_kill(args: argparse.Namespace): d = _udid2device(args.udid) if args.name.isdigit(): pid = int(args.name) d.app_kill(int(args.name)) else: pid = d.app_kill(args.name) if pid is None: print("No app killed") else: print("Kill pid:", pid)
null
154,719
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: def cmd_system_info(args): d = _udid2device(args.udid) with d.connect_instruments() as ts: sinfo = ts.system_info() pprint(sinfo)
null
154,720
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def _print_json(value): def _bytes_hook(obj): if isinstance(obj, bytes): return base64.b64encode(obj).decode() else: return str(obj) print(json.dumps(value, indent=4, ensure_ascii=False, default=_bytes_hook)) def cmd_battery(args: argparse.Namespace): d = _udid2device(args.udid) power_info = d.get_io_power() if args.json: _print_json(power_info) else: if power_info['Status'] != "Success": pprint(power_info) return # dump power info info = power_info['Diagnostics']['IORegistry'] indexes = ( ('CurrentCapacity', '当前电量', '%'), ('CycleCount', '充电次数', '次'), ('AbsoluteCapacity', '当前电量', 'mAh'), ('NominalChargeCapacity', '实际容量', 'mAh'), ('DesignCapacity', '设计容量', 'mAh'), ('NominalChargeCapacity', '电池寿命', lambda cap: '{}%'.format(round(cap / info['DesignCapacity'] * 100))), ('Serial', '序列号', ''), ('Temperature', '电池温度', '/100℃'), ('Voltage', '当前电压', 'mV'), ('BootVoltage', '开机电压', 'mV'), (('AdapterDetails', 'Watts'), '充电器功率', 'W'), (('AdapterDetails', 'Voltage'), '充电器电压', 'mV'), ('InstantAmperage', '当前电流', 'mA'), ('UpdateTime', '更新时间', lambda v: datetime.fromtimestamp(v).strftime("%Y-%m-%d %H:%M:%S")), ) # 数据一般20s更新一次 for keypath, cn_name, unit in indexes: value = info if isinstance(keypath, str): value = info[keypath] else: value = info for key in keypath: value = value.get(key, {}) if callable(unit): value = unit(value) unit = "" print("{:10s}{}{}".format(cn_name, value, unit))
null
154,721
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError logger = logging.getLogger(__name__) def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_crashreport(args: argparse.Namespace): d = _udid2device(args.udid) cm = d.get_crashmanager() if args.list: cm.preview() return if args.clear: cm.remove_all() return if not args.output_directory: print("OUTPUT_DIRECTORY must be provided") sys.exit(1) remove: bool = not args.keep cm.afc.pull("/", args.output_directory, remove=remove) logger.info("Done")
null
154,722
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cache_developer_image(version: str) -> str: """ download developer image from github to local return image_zip_path """ _alias = { "12.5": "12.4", "15.8": "15.5", # "16.5": "17.0", } if version in _alias: version = _alias[version] logger.info("Use alternative developer image %s", version) # Default download image from https://github.com/JinjunHan/iOSDeviceSupport image_urls = _get_developer_image_url_list(version) # $HOME/.tidevice/device-support/12.2.zip local_device_support = get_app_dir("device-support") image_zip_path = os.path.join(local_device_support, version+".zip") if not zipfile.is_zipfile(image_zip_path): err = None for url in image_urls: try: _urlretrieve(url, image_zip_path) if zipfile.is_zipfile(image_zip_path): err = None break err = Exception("image file not zip") except requests.HTTPError as e: err = e if e.response.status_code == 404: break except requests.RequestException as e: err = e if err: raise err return image_zip_path class DownloadError(BaseError): """ Download error """ def cmd_developer(args: argparse.Namespace): if args.download_all: for major in range(14, 17): for minor in range(0, 7): version = f"{major}.{minor}" try: cache_developer_image(version) except (requests.HTTPError, DownloadError): break # print("finish cache developer image {}".format(version)) elif args.list: d = _udid2device(args.udid) print(d.imagemounter.lookup()) else: d = _udid2device(args.udid) d.mount_developer_image(reboot_ok=args.reboot_ok) return
null
154,723
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def relay(d: Device, lport: int, rport: int, debug: bool = False): """ relay tcp data from pc to device Args: lport: local port rport: remote port """ simple_tornado.patch_for_windows() RelayTCPServer(device=d, device_port=rport, debug=debug).listen(lport) try: IOLoop.instance().start() except KeyboardInterrupt: IOLoop.instance().stop() def cmd_relay(args: argparse.Namespace): d = _udid2device(args.udid) relay(d, args.lport, args.rport, debug=args.debug)
null
154,724
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError logger = logging.getLogger(__name__) def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) class WDAService: _DEFAULT_TIMEOUT = 90 # http request timeout def __init__(self, d: Device, bundle_id: str = "com.*.xctrunner", env: dict={}): self._d = d self._bundle_id = bundle_id self._service = ThreadService(self._keep_wda_running) self._env = env def set_check_interval(self, interval: float): self._service.set_arguments(interval) def udid(self) -> str: return self._d.udid def logger(self) -> logging.Logger: log_format = f'%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d] [{self.udid}]%(end_color)s %(message)s' formatter = logzero.LogFormatter(fmt=log_format) return logzero.setup_logger(formatter=formatter) def _is_alive(self) -> bool: try: with requests_usbmux.Session() as session: resp = session.get(requests_usbmux.DEFAULT_SCHEME + f"{self.udid}:8100/HEALTH", timeout=self._DEFAULT_TIMEOUT) if resp.status_code != 200: return False return resp.text.strip() == "I-AM-ALIVE" except requests.RequestException as e: self.logger.debug("request error: %s", e) return False except MuxReplyError as e: if e.reply_code != UsbmuxReplyCode.ConnectionRefused: self.logger.warning("Unknown MuxReplyError: %s", e) return False except Exception as e: self.logger.warning("Unknown exception: %s", e) return False def _wait_ready(self, proc, stop_event: threading.Event, timeout: float = 60.0) -> bool: deadline = time.time() + timeout while not stop_event.is_set() and time.time() < deadline: alive = self._is_alive() if alive: return True if proc.poll() is not None: # program quit return False stop_event.wait(1.0) return False def _wait_until_quit(self, proc: subprocess.Popen, stop_event: threading.Event, check_interval: float = 30.0) -> float: """ return running seconds """ start = time.time() elapsed = lambda: time.time() - start while not stop_event.is_set(): if proc.poll() is not None: break # stop check when check_interval is set to 0 if check_interval < 0.00001: time.sleep(.1) continue if not self._is_alive(): # maybe stuck by other request # check again after 10s self.logger.debug("WDA is not response in %d second, check again after 1s", self._DEFAULT_TIMEOUT) if stop_event.wait(1): break if not self._is_alive(): self.logger.info("WDA confirmed not running") break else: self.logger.debug("WDA is back alive") end_check_time = time.time() + check_interval while time.time() < end_check_time: if proc.poll() is not None: break time.sleep(.1) self.logger.info("WDA keeper stopped") return elapsed() def _keep_wda_running(self, stop_event: threading.Event, check_interval: float = 60.0): """ Keep wda running, launch when quit """ if check_interval > .1: self.logger.info("WDA check every %.1f seconds", check_interval) tries: int = 0 crash_times: int = 0 # detect unrecoverable launch d = Device(self.udid) while not stop_event.is_set(): self.logger.debug("launch WDA") tries += 1 cmds = [ sys.executable, '-m', 'tidevice', '-u', self.udid, 'xctest', '--bundle_id', self._bundle_id, #'-e', 'MJPEG_SERVER_PORT:8103' ] for key in self._env: cmds.append('-e') val = self._env[key] cmds.append( key + ':' + val ) try: proc = subprocess.Popen(cmds) if not self._wait_ready(proc, stop_event): self.logger.error("wda started failed") crash_times += 1 if crash_times >= 5: break continue elapsed = self._wait_until_quit(proc, stop_event, check_interval=check_interval) crash_times = 0 self.logger.info("WDA stopped for the %dst time, running %.1f minutes", tries, elapsed / 60) finally: proc.terminate() if not d.is_connected(): self.logger.warning("device offline") break def start(self): return self._service.start() def stop(self): return self._service.stop() The provided code snippet includes necessary dependencies for implementing the `cmd_wdaproxy` function. Write a Python function `def cmd_wdaproxy(args: argparse.Namespace)` to solve the following problem: start xctest and relay Here is the function: def cmd_wdaproxy(args: argparse.Namespace): """ start xctest and relay """ d = _udid2device(args.udid) env = {} for kv in args.env or []: key, val = kv.split(":", 1) env[key] = val if env: logger.info("Launch env: %s", env) serv = WDAService(d, args.bundle_id, env) serv.set_check_interval(args.check_interval) p = None if args.port: cmds = [ sys.executable, '-m', 'tidevice', '-u', d.udid, 'relay', str(args.port), '8100' ] p = subprocess.Popen(cmds, stdout=sys.stdout, stderr=sys.stderr) try: serv.start() while serv._service.running and p.poll() is None: time.sleep(.1) finally: p and p.terminate() serv.stop()
start xctest and relay
154,725
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_syslog(args: argparse.Namespace): d = _udid2device(args.udid) s = d.start_service("com.apple.syslog_relay") try: while True: text = s.psock.recv().decode('utf-8') print(text, end='', flush=True) except (BrokenPipeError, IOError): # Python flushes standard streams on exit; redirect remaining output # to devnull to avoid another BrokenPipeError at shutdown devnull = os.open(os.devnull, os.O_WRONLY) os.dup2(devnull, sys.stdout.fileno())
null
154,726
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_dump_fps(args): d = _udid2device(args.udid) for data in d.connect_instruments().iter_opengl_data(): if isinstance(data, str): continue fps = data['CoreAnimationFramesPerSecond'] print("{:>2d} {}".format(fps, "-" * fps))
null
154,727
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: def cmd_pair(args: argparse.Namespace): d = _udid2device(args.udid) pair_record = d.pair() print("Paired with device", d.udid, "HostID:", pair_record['HostID'])
null
154,728
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_unpair(args: argparse.Namespace): d = _udid2device(args.udid) d.delete_pair_record()
null
154,729
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_fsync(args: argparse.Namespace): d = _udid2device(args.udid) if args.bundle_id: sync = d.app_sync(args.bundle_id) else: sync = d.sync arg0 = args.arguments[0] if args.command == 'ls': tabdata = [] for finfo in sync.listdir_info(arg0): filename = finfo.st_name if finfo.is_dir(): filename = filename + "/" tabdata.append(['d' if finfo.is_dir() else '-', finfo.st_size, finfo.st_mtime, filename]) print(tabulate(tabdata, tablefmt="plain")) elif args.command == 'rm': # rm also support rmdir for arg in args.arguments: pprint(sync.remove(arg)) elif args.command == "touch": for arg in args.arguments: pprint(sync.touch(arg)) elif args.command == 'stat': finfo = sync.stat(arg0) print("IFMT:", finfo.st_ifmt) print("CTime:", finfo.st_ctime) print("MTime:", finfo.st_mtime) print("Size:", finfo.st_size) elif args.command == 'tree': sync.treeview(arg0, depth=-1) elif args.command == 'pull': arg1 = "./" if len(args.arguments) == 2: arg1 = args.arguments[1] src = pathlib.Path(arg0) dst = pathlib.Path(arg1) if dst.is_dir() and src.name and sync.stat(src).is_dir(): dst = dst.joinpath(src.name) sync.pull(src, dst) print("pulled", src, "->", dst) elif args.command == 'cat': for chunk in sync.iter_content(arg0): sys.stdout.write(chunk.decode('utf-8')) sys.stdout.flush() elif args.command == 'push': local_path = args.arguments[0] device_path = args.arguments[1] assert os.path.isfile(local_path) with open(local_path, "rb") as f: content = f.read() sync.push_content(device_path, content) print("pushed to", device_path) elif args.command == 'rmtree': pprint(sync.rmtree(arg0)) elif args.command == 'mkdir': pprint(sync.mkdir(arg0)) else: raise NotImplementedError()
null
154,730
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def _print_json(value): def _bytes_hook(obj): if isinstance(obj, bytes): return base64.b64encode(obj).decode() else: return str(obj) print(json.dumps(value, indent=4, ensure_ascii=False, default=_bytes_hook)) is_atty = getattr(sys.stdout, 'isatty', lambda: False)() def cmd_ps(args: argparse.Namespace): d = _udid2device(args.udid) app_infos = list(d.installation.iter_installed(app_type=None)) with d.connect_instruments() as ts: ps = list(ts.app_process_list(app_infos)) lens = defaultdict(int) json_data = [] keys = ['pid', 'name', 'bundle_id', 'display_name'] for p in ps: if not args.all and not p['isApplication']: continue for key in keys: lens[key] = max(lens[key], len(str(p[key]))) json_data.append({key: p[key] for key in keys}) if args.json: _print_json(json_data) return # {:0} is not allowed, so max(1, xx) is necessary fmt = ' '.join(['{:%d}' % max(1, lens[key]) for key in keys]) fmt = '{:>' + fmt[2:] # set PID right align if is_atty: print(fmt.format(*[key.upper() for key in keys])) for p in ps: if not args.all and not p['isApplication']: continue print(fmt.format(*[p[key] for key in keys]), flush=True)
null
154,731
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) class DataType(str, enum.Enum): SCREENSHOT = "screenshot" CPU = "cpu" MEMORY = "memory" NETWORK = "network" # 流量 FPS = "fps" PAGE = "page" GPU = "gpu" "tidevice performance" def __init__(self, d: BaseDevice, perfs: typing.List[DataType] = []): self._d = d self._bundle_id = None self._stop_event = threading.Event() self._wg = WaitGroup() self._started = False self._result = defaultdict(list) self._perfs = perfs # the callback function accepts all the data self._callback = None def start(self, bundle_id: str, callback: CallbackType = None): if not callback: # 默认不输出屏幕的截图(暂时没想好怎么处理) callback = lambda _type, data: print(_type.value, data, flush=True) if _type != DataType.SCREENSHOT and _type in self._perfs else None self._rp = RunningProcess(self._d, bundle_id) self._thread_start(callback) def _thread_start(self, callback: CallbackType): iters = [] if DataType.CPU in self._perfs or DataType.MEMORY in self._perfs: iters.append(iter_cpu_memory(self._d, self._rp)) if DataType.FPS in self._perfs: iters.append(iter_fps(self._d)) if DataType.GPU in self._perfs: iters.append(iter_gpu(self._d)) if DataType.SCREENSHOT in self._perfs: iters.append(set_interval(iter_screenshot(self._d), 2.0)) if DataType.NETWORK in self._perfs: iters.append(iter_network_flow(self._d, self._rp)) for it in (iters): # yapf: disable self._wg.add(1) threading.Thread(name="perf", target=append_data, args=(self._wg, self._stop_event, it, callback,self._perfs), daemon=True).start() def stop(self): # -> PerfReport: self._stop_event.set() with self._d.connect_instruments() as ts: print('Stop Sampling...') if DataType.NETWORK in self._perfs: ts.stop_network_iter() if DataType.GPU in self._perfs or DataType.FPS in self._perfs: ts.stop_iter_opengl_data() if DataType.CPU in self._perfs or DataType.MEMORY in self._perfs: ts.stop_iter_cpu_memory() print("\nFinished!") # memory and fps will take at least 1 second to catch _stop_event # to make function run faster, we not using self._wg.wait(..) here # > self._wg.wait(timeout=3.0) # wait all stopped # > self._started = False def wait(self, timeout: float): return self._wg.wait(timeout=timeout) def cmd_perf(args: argparse.Namespace): #print("BundleID:", args.bundle_id) from ._perf import Performance d = _udid2device(args.udid) perfs = list(DataType) if args.perfs: perfs = [] for _typename in args.perfs.split(","): perfs.append(DataType(_typename)) if (DataType.MEMORY in perfs or DataType.CPU in perfs) and not args.bundle_id: print('\033[1;31m error: the following arguments are required: -B/--bundle_id \033[0m') exit(-1) perf = Performance(d, perfs=perfs) def _cb(_type: DataType, data): if args.json and _type != DataType.SCREENSHOT: data = json.dumps(data) print(_type.value, data, flush=True) if len(perfs) != 1 else print(data,flush=True) try: perf.start(args.bundle_id, callback=_cb) #print("Ctrl-C to finish") while True: time.sleep(.1) except KeyboardInterrupt: pass finally: perf.stop()
null
154,732
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_set_assistive_touch(args: argparse.Namespace): d = _udid2device(args.udid) d.set_assistive_touch(args.enabled)
null
154,733
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def _udid2device(udid: Optional[str] = None) -> Device: _udid = _complete_udid(udid) if _udid != udid: logger.debug("AutoComplete udid %s", _udid) del (udid) return Device(_udid, um) def cmd_savesslfile(args: argparse.Namespace): os.makedirs("ssl", exist_ok=True) d = _udid2device(args.udid) pr = d.pair_record pathlib.Path(f"ssl/{d.udid}_all.pem").write_bytes( pr['HostPrivateKey'] + pr['HostCertificate'] # + pr['RootCertificate'] )
null
154,734
import argparse import base64 import json import logging import os import pathlib import re import subprocess import sys import time import typing from collections import defaultdict from datetime import datetime from pprint import pformat, pprint from typing import Optional import requests from logzero import setup_logger from tabulate import tabulate from ._device import Device from ._imagemounter import cache_developer_image from ._ipautil import IPAReader from ._perf import DataType from ._proto import LOG, MODELS, PROGRAM_NAME, ConnectionType from ._relay import relay from ._usbmux import Usbmux from ._utils import is_atty from ._version import __version__ from ._wdaproxy import WDAService from .exceptions import DownloadError, MuxError, MuxServiceError, ServiceError def cmd_test(args: argparse.Namespace): print("Just test")
null
154,735
import re import shutil import sys import tempfile import typing import zipfile from pprint import pprint from typing import Union from . import bplist, plistlib2 from ._compat import cache from .exceptions import IPAError class IPAReader(zipfile.ZipFile): def get_infoplist_zipinfo(self) -> zipfile.ZipInfo: re_infoplist = re.compile(r"^Payload/[^/]+\.app/Info.plist$") for zipinfo in self.filelist: if re_infoplist.match(zipinfo.filename): return zipinfo raise IPAError("Info.plist not found") def get_mobileprovision_zipinfo(self) -> zipfile.ZipInfo: re_provision_file = re.compile(r"^Payload/[^/]+\.app/embedded.mobileprovision$") for zipinfo in self.filelist: if re_provision_file.match(zipinfo.filename): return zipinfo raise IPAError("embedded.mobileprovision not found") def get_mobileprovision(self) -> dict: """ mobileprovision usally contains keys AppIDName, ApplicationIdentifierPrefix, CreationDate, Platform, IsXcodeManaged, DeveloperCertificates, Entitlements, ExpirationDate, Name, ProvisionedDevices, TeamIdentifier, TeamName, TimeToLive, UUID, Version """ provision_xml_rx = re.compile(br'<\?xml.+</plist>', re.DOTALL) content = self.read(self.get_mobileprovision_zipinfo()) match = provision_xml_rx.search(content) if match: xml_content = match.group() data = plistlib2.loads(xml_content) return data else: raise IPAError('unable to parse embedded.mobileprovision file') def get_infoplist(self) -> dict: finfo = self.get_infoplist_zipinfo() with self.open(finfo, 'r') as fp: if sys.version_info[:2] <= (3, 6): # for compatiable with py3.6 with tempfile.TemporaryFile() as tmpf: shutil.copyfileobj(fp, tmpf) tmpf.seek(0) return bplist.load(tmpf) return bplist.load(fp) def get_bundle_id(self) -> str: """ return CFBundleIdentifier """ return self.get_infoplist()['CFBundleIdentifier'] def get_short_version(self) -> str: return self.get_infoplist().get('CFBundleShortVersionString', "") def dump_info(self, all: bool = False): data = self.get_infoplist() print("BundleID:", data['CFBundleIdentifier']) print("ShortVersion:", data['CFBundleShortVersionString']) if all: m = self.get_mobileprovision() pprint(m['ProvisionedDevices']) def parse_bundle_id(fpath: str) -> str: with open(fpath, "rb") as f: return IPAReader(f).get_bundle_id()
null
154,736
import base64 from datetime import datetime, timedelta from OpenSSL.crypto import FILETYPE_PEM as PEM from OpenSSL.crypto import (TYPE_RSA, X509, PKey, X509Req, dump_certificate, dump_privatekey, load_publickey) from pyasn1.codec.der import decoder as der_decoder from pyasn1.codec.der import encoder as der_encoder from pyasn1.type import univ def convert_PKCS1_to_PKCS8_pubkey(data: bytes) -> bytes: pubkey_pkcs1_b64 = b''.join(data.split(b'\n')[1:-2]) pubkey_pkcs1, restOfInput = der_decoder.decode(base64.b64decode(pubkey_pkcs1_b64)) bit_str = univ.Sequence() bit_str.setComponentByPosition(0, univ.Integer(pubkey_pkcs1[0])) bit_str.setComponentByPosition(1, univ.Integer(pubkey_pkcs1[1])) bit_str = der_encoder.encode(bit_str) try: bit_str = ''.join([('00000000'+bin(ord(x))[2:])[-8:] for x in list(bit_str)]) except Exception: bit_str = ''.join([('00000000'+bin(x)[2:])[-8:] for x in list(bit_str)]) bit_str = univ.BitString("'%s'B" % bit_str) pubkeyid = univ.Sequence() pubkeyid.setComponentByPosition(0, univ.ObjectIdentifier('1.2.840.113549.1.1.1')) # == OID for rsaEncryption pubkeyid.setComponentByPosition(1, univ.Null('')) pubkey_seq = univ.Sequence() pubkey_seq.setComponentByPosition(0, pubkeyid) pubkey_seq.setComponentByPosition(1, bit_str) pubkey = der_encoder.encode(pubkey_seq) return b'-----BEGIN PUBLIC KEY-----\n' + base64.encodebytes(pubkey) + b'-----END PUBLIC KEY-----\n' def make_cert(req: X509Req, ca_pkey: PKey) -> X509: cert = X509() cert.set_serial_number(1) cert.set_version(2) cert.set_subject(req.get_subject()) cert.set_pubkey(req.get_pubkey()) cert.set_notBefore(x509_time(minutes=-1)) cert.set_notAfter(x509_time(days=30)) # noinspection PyTypeChecker cert.sign(ca_pkey, 'sha256') return cert def make_req(pub_key, cn=None, digest=None) -> X509Req: req = X509Req() req.set_version(2) req.set_pubkey(pub_key) if cn is not None: subject = req.get_subject() subject.CN = cn.encode('utf-8') if digest: req.sign(pub_key, digest) return req The provided code snippet includes necessary dependencies for implementing the `make_certs_and_key` function. Write a Python function `def make_certs_and_key(device_public_key: bytes)` to solve the following problem: 1. create private key 2. create certificate Here is the function: def make_certs_and_key(device_public_key: bytes): """ 1. create private key 2. create certificate """ device_key = load_publickey(PEM, convert_PKCS1_to_PKCS8_pubkey(device_public_key)) device_key._only_public = False # root key root_key = PKey() root_key.generate_key(TYPE_RSA, 2048) host_req = make_req(root_key) host_cert = make_cert(host_req, root_key) device_req = make_req(device_key, 'Device') device_cert = make_cert(device_req, root_key) return dump_certificate(PEM, host_cert), dump_privatekey(PEM, root_key), dump_certificate(PEM, device_cert)
1. create private key 2. create certificate
154,737
import base64 import enum import io import threading import time import typing import uuid from collections import defaultdict, namedtuple from typing import Any, Iterator, Optional, Tuple, Union import weakref from ._device import BaseDevice from ._proto import * class DataType(str, enum.Enum): SCREENSHOT = "screenshot" CPU = "cpu" MEMORY = "memory" NETWORK = "network" # 流量 FPS = "fps" PAGE = "page" GPU = "gpu" def __init__(self, d: BaseDevice, perfs: typing.List[DataType] = []): self._d = d self._bundle_id = None self._stop_event = threading.Event() self._wg = WaitGroup() self._started = False self._result = defaultdict(list) self._perfs = perfs # the callback function accepts all the data self._callback = None def start(self, bundle_id: str, callback: CallbackType = None): if not callback: # 默认不输出屏幕的截图(暂时没想好怎么处理) callback = lambda _type, data: print(_type.value, data, flush=True) if _type != DataType.SCREENSHOT and _type in self._perfs else None self._rp = RunningProcess(self._d, bundle_id) self._thread_start(callback) def _thread_start(self, callback: CallbackType): iters = [] if DataType.CPU in self._perfs or DataType.MEMORY in self._perfs: iters.append(iter_cpu_memory(self._d, self._rp)) if DataType.FPS in self._perfs: iters.append(iter_fps(self._d)) if DataType.GPU in self._perfs: iters.append(iter_gpu(self._d)) if DataType.SCREENSHOT in self._perfs: iters.append(set_interval(iter_screenshot(self._d), 2.0)) if DataType.NETWORK in self._perfs: iters.append(iter_network_flow(self._d, self._rp)) for it in (iters): # yapf: disable self._wg.add(1) threading.Thread(name="perf", target=append_data, args=(self._wg, self._stop_event, it, callback,self._perfs), daemon=True).start() def stop(self): # -> PerfReport: self._stop_event.set() with self._d.connect_instruments() as ts: print('Stop Sampling...') if DataType.NETWORK in self._perfs: ts.stop_network_iter() if DataType.GPU in self._perfs or DataType.FPS in self._perfs: ts.stop_iter_opengl_data() if DataType.CPU in self._perfs or DataType.MEMORY in self._perfs: ts.stop_iter_cpu_memory() print("\nFinished!") # memory and fps will take at least 1 second to catch _stop_event # to make function run faster, we not using self._wg.wait(..) here # > self._wg.wait(timeout=3.0) # wait all stopped # > self._started = False def wait(self, timeout: float): return self._wg.wait(timeout=timeout) class BaseDevice(): def __init__(self, udid: Optional[str] = None, usbmux: Union[Usbmux, str, None] = None): if not usbmux: self._usbmux = Usbmux() elif isinstance(usbmux, str): self._usbmux = Usbmux(usbmux) elif isinstance(usbmux, Usbmux): self._usbmux = usbmux self._udid = udid self._info: DeviceInfo = None self._lock = threading.Lock() self._pair_record = None def debug(self) -> bool: return logging.getLogger(LOG.root).level == logging.DEBUG def debug(self, v: bool): # log setup setup_logger(LOG.root, level=logging.DEBUG if v else logging.INFO) def usbmux(self) -> Usbmux: return self._usbmux def info(self) -> DeviceInfo: if self._info: return self._info devices = self._usbmux.device_list() if self._udid: for d in devices: if d.udid == self._udid: self._info = d else: if len(devices) == 0: raise MuxError("No device connected") elif len(devices) > 1: raise MuxError("More then one device connected") _d = devices[0] self._udid = _d.udid self._info = _d if not self._info: raise MuxError("Device: {} not ready".format(self._udid)) return self._info def is_connected(self) -> bool: return self.udid in self.usbmux.device_udid_list() def udid(self) -> str: return self._udid def devid(self) -> int: return self.info.device_id def pair_record(self) -> dict: if not self._pair_record: self.handshake() return self._pair_record def pair_record(self, val: Optional[dict]): self._pair_record = val def _read_pair_record(self) -> dict: """ DeviceCertificate EscrowBag HostID HostCertificate HostPrivateKey RootCertificate RootPrivateKey SystemBUID WiFiMACAddress Pair data can be found in win32: os.environ["ALLUSERSPROFILE"] + "/Apple/Lockdown/" darwin: /var/db/lockdown/ linux: /var/lib/lockdown/ if ios version > 13.0 get pair data from usbmuxd else: generate pair data with python """ payload = { 'MessageType': 'ReadPairRecord', # Required 'PairRecordID': self.udid, # Required 'ClientVersionString': 'libusbmuxd 1.1.0', 'ProgName': PROGRAM_NAME, 'kLibUSBMuxVersion': 3 } data = self._usbmux.send_recv(payload) record_data = data['PairRecordData'] return bplist.loads(record_data) def delete_pair_record(self): data = self._usbmux.send_recv({ "MessageType": "DeletePairRecord", "PairRecordID": self.udid, "ProgName": PROGRAM_NAME, }) # Expect: {'MessageType': 'Result', 'Number': 0} def pair(self): """ Same as idevicepair pair iconsole is a github project, hosted in https://github.com/anonymous5l/iConsole """ device_public_key = self.get_value("DevicePublicKey", no_session=True) if not device_public_key: raise MuxError("Unable to retrieve DevicePublicKey") buid = self._usbmux.read_system_BUID() wifi_address = self.get_value("WiFiAddress", no_session=True) try: from ._ca import make_certs_and_key except ImportError: #print("DevicePair require pyOpenSSL and pyans1, install by the following command") #print("\tpip3 install pyOpenSSL pyasn1", flush=True) raise RuntimeError("DevicePair required lib, fix with: pip3 install pyOpenSSL pyasn1") cert_pem, priv_key_pem, dev_cert_pem = make_certs_and_key(device_public_key) pair_record = { 'DevicePublicKey': device_public_key, 'DeviceCertificate': dev_cert_pem, 'HostCertificate': cert_pem, 'HostID': str(uuid.uuid4()).upper(), 'RootCertificate': cert_pem, 'SystemBUID': buid, } with self.create_inner_connection() as s: ret = s.send_recv_packet({ "Request": "Pair", "PairRecord": pair_record, "Label": PROGRAM_NAME, "ProtocolVersion": "2", "PairingOptions": { "ExtendedPairingErrors": True, } }) assert ret, "Pair request got empty response" if "Error" in ret: # error could be "PasswordProtected" or "PairingDialogResponsePending" raise MuxError("pair:", ret['Error']) assert 'EscrowBag' in ret, ret pair_record['HostPrivateKey'] = priv_key_pem pair_record['EscrowBag'] = ret['EscrowBag'] pair_record['WiFiMACAddress'] = wifi_address self.usbmux.send_recv({ "MessageType": "SavePairRecord", "PairRecordID": self.udid, "PairRecordData": bplist.dumps(pair_record), "DeviceID": self.devid, }) return pair_record def handshake(self): """ set self._pair_record """ try: self._pair_record = self._read_pair_record() except MuxReplyError as err: if err.reply_code == UsbmuxReplyCode.BadDevice: self._pair_record = self.pair() def ssl_pemfile_path(self): with self._lock: appdir = get_app_dir("ssl") fpath = os.path.join(appdir, self._udid + "-" + self._host_id + ".pem") if os.path.exists(fpath): # 3 minutes not regenerate pemfile st_mtime = datetime.datetime.fromtimestamp( os.stat(fpath).st_mtime) if datetime.datetime.now() - st_mtime < datetime.timedelta( minutes=3): return fpath with open(fpath, "wb") as f: pdata = self.pair_record f.write(pdata['HostPrivateKey']) f.write(b"\n") f.write(pdata['HostCertificate']) return fpath def _host_id(self): return self.pair_record['HostID'] def _system_BUID(self): return self.pair_record['SystemBUID'] def create_inner_connection( self, port: int = LOCKDOWN_PORT, # 0xf27e, _ssl: bool = False, ssl_dial_only: bool = False) -> PlistSocketProxy: """ make connection to iphone inner port """ device_id = self.info.device_id conn = self._usbmux.connect_device_port(device_id, port) if _ssl: with set_socket_timeout(conn.get_socket, 10.0): psock = conn.psock psock.switch_to_ssl(self.ssl_pemfile_path) if ssl_dial_only: psock.ssl_unwrap() return conn def create_session(self) -> Session: """ create secure connection to lockdown service """ s = self.create_inner_connection() data = s.send_recv_packet({"Request": "QueryType"}) assert data['Type'] == LockdownService.MobileLockdown data = s.send_recv_packet({ 'Request': 'GetValue', 'Key': 'ProductVersion', 'Label': PROGRAM_NAME, }) # Expect: {'Key': 'ProductVersion', 'Request': 'GetValue', 'Value': '13.4.1'} data = s.send_recv_packet({ "Request": "StartSession", "HostID": self.pair_record['HostID'], "SystemBUID": self.pair_record['SystemBUID'], "ProgName": PROGRAM_NAME, }) if 'Error' in data: if data['Error'] == 'InvalidHostID': # try to repair device self.pair_record = None self.delete_pair_record() self.handshake() # After paired, call StartSession again data = s.send_recv_packet({ "Request": "StartSession", "HostID": self.pair_record['HostID'], "SystemBUID": self.pair_record['SystemBUID'], "ProgName": PROGRAM_NAME, }) else: raise MuxError("StartSession", data['Error']) session_id = data['SessionID'] if data['EnableSessionSSL']: # tempfile.NamedTemporaryFile is not working well on windows # See: https://stackoverflow.com/questions/6416782/what-is-namedtemporaryfile-useful-for-on-windows s.psock.switch_to_ssl(self.ssl_pemfile_path) return Session(s, session_id) def device_info(self, domain: Optional[str] = None) -> dict: """ Args: domain: can be found in "ideviceinfo -h", eg: com.apple.disk_usage """ return self.get_value(domain=domain) def get_value(self, key: str = '', domain: str = "", no_session: bool = False): """ key can be: ProductVersion Args: domain (str): com.apple.disk_usage no_session: set to True when not paired """ request = { "Request": "GetValue", "Label": PROGRAM_NAME, } if key: request['Key'] = key if domain: request['Domain'] = domain if no_session: with self.create_inner_connection() as s: ret = s.send_recv_packet(request) return ret['Value'] else: with self.create_session() as conn: ret = conn.send_recv_packet(request) return ret.get('Value') def set_value(self, domain: str, key: str, value: typing.Any): request = { "Domain": domain, "Key": key, "Label": "oa", "Request": "SetValue", "Value": value } with self.create_session() as s: ret = s.send_recv_packet(request) error = ret.get("Error") if error: raise ServiceError(error) def set_assistive_touch(self, enabled: bool): """ show or close screen assitive touch button Raises: ServiceError """ self.set_value("com.apple.Accessibility", "AssistiveTouchEnabledByiTunes", enabled) def screen_info(self) -> ScreenInfo: info = self.device_info("com.apple.mobile.iTunes") kwargs = { "width": info['ScreenWidth'], "height": info['ScreenHeight'], "scale": info['ScreenScaleFactor'], # type: float } return ScreenInfo(**kwargs) def battery_info(self) -> BatteryInfo: info = self.device_info('com.apple.mobile.battery') return BatteryInfo( level=info['BatteryCurrentCapacity'], is_charging=info.get('BatteryIsCharging'), external_charge_capable=info.get('ExternalChargeCapable'), external_connected=info.get('ExternalConnected'), fully_charged=info.get('FullyCharged'), gas_gauge_capability=info.get('GasGaugeCapability'), has_battery=info.get('HasBattery') ) def storage_info(self) -> StorageInfo: """ the unit might be 1000 not 1024 """ info = self.device_info('com.apple.disk_usage') disk = info['TotalDiskCapacity'] size = info['TotalDataCapacity'] free = info['TotalDataAvailable'] used = size - free return StorageInfo(disk_size=disk, used=used, free=free) def reboot(self) -> str: """ reboot device """ conn = self.start_service("com.apple.mobile.diagnostics_relay") ret = conn.send_recv_packet({ "Request": "Restart", "Label": PROGRAM_NAME, }) return ret['Status'] def shutdown(self): conn = self.start_service("com.apple.mobile.diagnostics_relay") ret = conn.send_recv_packet({ "Request": "Shutdown", "Label": PROGRAM_NAME, }) return ret['Status'] def get_io_power(self) -> dict: return self.get_io_registry('IOPMPowerSource') def get_io_registry(self, name: str) -> dict: conn = self.start_service("com.apple.mobile.diagnostics_relay") ret = conn.send_recv_packet({ 'Request': 'IORegistry', 'EntryClass': name, "Label": PROGRAM_NAME, }) return ret def get_crashmanager(self) -> CrashManager: """ https://github.com/libimobiledevice/libimobiledevice/blob/master/tools/idevicecrashreport.c """ # read "ping" message which indicates the crash logs have been moved to a safe harbor move_conn = self.start_service(LockdownService.CRASH_REPORT_MOVER_SERVICE) ack = b'ping\x00' if ack != move_conn.psock.recvall(len(ack)): raise ServiceError("ERROR: Crash logs could not be moved. Connection interrupted") copy_conn = self.start_service(LockdownService.CRASH_REPORT_COPY_MOBILE_SERVICE) return CrashManager(copy_conn) def enable_ios16_developer_mode(self, reboot_ok: bool = False): """ enabling developer mode on iOS 16 """ is_developer = self.get_value("DeveloperModeStatus", domain="com.apple.security.mac.amfi") if is_developer: return True if reboot_ok: if self._send_action_to_amfi_lockdown(action=1) == 0xe6: raise ServiceError("Device is rebooting in order to enable \"Developer Mode\"") # https://developer.apple.com/documentation/xcode/enabling-developer-mode-on-a-device resp_code = self._send_action_to_amfi_lockdown(action=0) if resp_code == 0xd9: raise ServiceError("Developer Mode is not opened, to enable Developer Mode goto Settings -> Privacy & Security -> Developer Mode") else: raise ServiceError("Failed to enable \"Developer Mode\"") def _send_action_to_amfi_lockdown(self, action: int) -> int: """ Args: action: 0: Show "Developer Mode" Tab in Privacy & Security 1: Reboot device to dialog of Open "Developer Mode" (经过测试发现只有在设备没设置密码的情况下才能用) """ conn = self.start_service(LockdownService.AmfiLockdown) body = plistlib2.dumps({"action": action}) payload = struct.pack(">I", len(body)) + body conn.psock.sendall(payload) rawdata = conn.psock.recv() (resp_code,) = struct.unpack(">I", rawdata[:4]) return resp_code def start_service(self, name: str) -> PlistSocketProxy: try: return self._unsafe_start_service(name) except (MuxServiceError, MuxError): self.mount_developer_image() # maybe should wait here time.sleep(.5) return self._unsafe_start_service(name) def _unsafe_start_service(self, name: str) -> PlistSocketProxy: with self.create_session() as _s: s: PlistSocketProxy = _s del(_s) data = s.send_recv_packet({ "Request": "StartService", "Service": name, "Label": PROGRAM_NAME, }) if 'Error' in data: # data['Error'] is InvalidService error = data['Error'] # PasswordProtected, InvalidService raise MuxServiceError(error) # Expect recv # {'EnableServiceSSL': True, # 'Port': 53428, # 'Request': 'StartService', # 'Service': 'com.apple.xxx'} assert data.get('Service') == name _ssl = data.get( 'EnableServiceSSL', False) # These DTX based services only execute a SSL Handshake # and then go back to sending unencrypted data right after the handshake. ssl_dial_only = False if name in ("com.apple.instruments.remoteserver", "com.apple.accessibility.axAuditDaemon.remoteserver", "com.apple.testmanagerd.lockdown", "com.apple.debugserver"): ssl_dial_only = True conn = self.create_inner_connection(data['Port'], _ssl=_ssl, ssl_dial_only=ssl_dial_only) conn.name = data['Service'] return conn def screenshot(self) -> Image.Image: return next(self.iter_screenshot()) def iter_screenshot(self) -> Iterator[Image.Image]: """ take screenshot infinite """ conn = self.start_service(LockdownService.MobileScreenshotr) version_exchange = conn.recv_packet() # Expect recv: ['DLMessageVersionExchange', 300, 0] data = conn.send_recv_packet([ 'DLMessageVersionExchange', 'DLVersionsOk', version_exchange[1] ]) # Expect recv: ['DLMessageDeviceReady'] assert data[0] == 'DLMessageDeviceReady' while True: # code will be blocked here until next(..) called data = conn.send_recv_packet([ 'DLMessageProcessMessage', { 'MessageType': 'ScreenShotRequest' } ]) # Expect recv: ['DLMessageProcessMessage', {'MessageType': 'ScreenShotReply', ScreenShotData': b'\x89PNG\r\n\x...'}] assert len(data) == 2 and data[0] == 'DLMessageProcessMessage' assert isinstance(data[1], dict) assert data[1]['MessageType'] == "ScreenShotReply" png_data = data[1]['ScreenShotData'] yield pil_imread(png_data) def name(self) -> str: return self.get_value("DeviceName", no_session=True) def product_version(self) -> str: return self.get_value("ProductVersion", no_session=True) def product_type(self) -> str: return self.get_value("ProductType", no_session=True) def app_sync(self, bundle_id: str, command: str = "VendDocuments") -> Sync: # Change command(VendContainer -> VendDocuments) # According to https://github.com/GNOME/gvfs/commit/b8ad223b1e2fbe0aec24baeec224a76d91f4ca2f # Ref: https://github.com/libimobiledevice/libimobiledevice/issues/193 conn = self.start_service(LockdownService.MobileHouseArrest) conn.send_packet({ "Command": command, "Identifier": bundle_id, }) return Sync(conn) def installation(self) -> Installation: conn = self.start_service(Installation.SERVICE_NAME) return Installation(conn) def imagemounter(self) -> ImageMounter: """ start_service will call imagemounter, so here should call _unsafe_start_service instead """ conn = self._unsafe_start_service(ImageMounter.SERVICE_NAME) return ImageMounter(conn) def _request_developer_image_dir(self, major: int, minor: int) -> typing.Optional[str]: # 1. use local path # 2. use download cache resource # 3. download from network version = str(major) + "." + str(minor) if platform.system() == "Darwin": mac_developer_dir = f"/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/{version}" image_path = os.path.join(mac_developer_dir, "DeveloperDiskImage.dmg") signature_path = image_path + ".signature" if os.path.isfile(image_path) and os.path.isfile(signature_path): return mac_developer_dir try: image_path = get_developer_image_path(version) return image_path except (DownloadError, DeveloperImageError): logger.debug("DeveloperImage not found: %s", version) return None def _test_if_developer_mounted(self) -> bool: try: with self.create_session(): self._unsafe_start_service(LockdownService.MobileLockdown) return True except MuxServiceError: return False def mount_developer_image(self, reboot_ok: bool = False): """ Raises: MuxError, ServiceError """ product_version = self.get_value("ProductVersion") if semver_compare(product_version, "16.0.0") >= 0: self.enable_ios16_developer_mode(reboot_ok=reboot_ok) try: if self.imagemounter.is_developer_mounted(): logger.info("DeveloperImage already mounted") return except MuxError: # expect: DeviceLocked pass if self._test_if_developer_mounted(): logger.info("DeviceLocked, but DeveloperImage already mounted") return major, minor = product_version.split(".")[:2] for guess_minor in range(int(minor), -1, -1): version = f"{major}.{guess_minor}" developer_img_dir = self._request_developer_image_dir(int(major), guess_minor) if developer_img_dir: image_path = os.path.join(developer_img_dir, "DeveloperDiskImage.dmg") signature_path = image_path + ".signature" try: self.imagemounter.mount(image_path, signature_path) logger.info("DeveloperImage %s mounted successfully", version) return except MuxError as err: if "ImageMountFailed" in str(err): logger.info("DeveloperImage %s mount failed, try next version", version) else: raise ServiceError("ImageMountFailed") raise ServiceError("DeveloperImage not found") def sync(self) -> Sync: conn = self.start_service(LockdownService.AFC) return Sync(conn) def app_stop(self, pid_or_name: Union[int, str]) -> int: """ return pid killed """ with self.connect_instruments() as ts: if isinstance(pid_or_name, int): ts.app_kill(pid_or_name) return pid_or_name elif isinstance(pid_or_name, str): bundle_id = pid_or_name app_infos = list(self.installation.iter_installed(app_type=None)) ps = ts.app_process_list(app_infos) for p in ps: if p['bundle_id'] == bundle_id: ts.app_kill(p['pid']) return p['pid'] return None def app_kill(self, *args, **kwargs) -> int: """ alias of app_stop """ return self.app_stop(*args, **kwargs) def app_start(self, bundle_id: str, args: Optional[list] = [], env: typing.Mapping = {}) -> int: """ start application Args: bundle_id: com.apple.Preferences args: eg ['-AppleLanguages', '(en)'] env: eg {'MYPATH': '/tmp'} Returns: pid """ if args is None: args = [] with self.connect_instruments() as ts: return ts.app_launch(bundle_id, args=args, app_env=env) def app_install(self, file_or_url: Union[str, typing.IO]) -> str: """ Args: file_or_url: local path or url Returns: bundle_id Raises: ServiceError, IOError # Copying 'WebDriverAgentRunner-Runner-resign.ipa' to device... DONE. # Installing 'com.facebook.WebDriverAgentRunner.xctrunner' # - CreatingStagingDirectory (5%) # - ExtractingPackage (15%) # - InspectingPackage (20%) # - TakingInstallLock (20%) # - PreflightingApplication (30%) # - InstallingEmbeddedProfile (30%) # - VerifyingApplication (40%) # - CreatingContainer (50%) # - InstallingApplication (60%) # - PostflightingApplication (70%) # - SandboxingApplication (80%) # - GeneratingApplicationMap (90%) # - Complete """ is_url = bool(re.match(r"^https?://", file_or_url)) if is_url: url = file_or_url tmpdir = tempfile.TemporaryDirectory() filepath = os.path.join(tmpdir.name, "_tmp.ipa") logger.info("Download to tmp path: %s", filepath) with requests.get(url, stream=True) as r: filesize = int(r.headers.get("content-length")) preader = ProgressReader(r.raw, filesize) with open(filepath, "wb") as f: shutil.copyfileobj(preader, f) preader.finish() elif os.path.isfile(file_or_url): filepath = file_or_url else: raise IOError( "Local path {} not exist".format(file_or_url)) ir = IPAReader(filepath) bundle_id = ir.get_bundle_id() short_version = ir.get_short_version() ir.close() conn = self.start_service(LockdownService.AFC) afc = Sync(conn) ipa_tmp_dir = "PublicStaging" if not afc.exists(ipa_tmp_dir): afc.mkdir(ipa_tmp_dir) print("Copying {!r} to device...".format(filepath), end=" ") sys.stdout.flush() target_path = ipa_tmp_dir + "/" + bundle_id + ".ipa" filesize = os.path.getsize(filepath) with open(filepath, 'rb') as f: preader = ProgressReader(f, filesize) afc.push_content(target_path, preader) preader.finish() print("DONE.") print("Installing {!r} {!r}".format(bundle_id, short_version)) return self.installation.install(bundle_id, target_path) def app_uninstall(self, bundle_id: str) -> bool: """ Note: It seems always return True """ return self.installation.uninstall(bundle_id) def _connect_testmanagerd_lockdown(self) -> DTXService: if self.major_version() >= 14: conn = self.start_service( LockdownService.TestmanagerdLockdownSecure) else: conn = self.start_service(LockdownService.TestmanagerdLockdown) return DTXService(conn) # 2022-08-24 add retry delay, looks like sometime can recover # BrokenPipeError(ConnectionError) def connect_instruments(self) -> ServiceInstruments: """ start service for instruments """ if self.major_version() >= 14: conn = self.start_service( LockdownService.InstrumentsRemoteServerSecure) else: conn = self.start_service(LockdownService.InstrumentsRemoteServer) return ServiceInstruments(conn) def _gen_xctest_configuration(self, app_info: dict, session_identifier: uuid.UUID, target_app_bundle_id: str = None, target_app_env: Optional[dict] = None, target_app_args: Optional[list] = None, tests_to_run: Optional[set] = None) -> bplist.XCTestConfiguration: # CFBundleName always endswith -Runner exec_name: str = app_info['CFBundleExecutable'] assert exec_name.endswith("-Runner"), "Invalid CFBundleExecutable: %s" % exec_name target_name = exec_name[:-len("-Runner")] # xctest_path = f"/tmp/{target_name}-{str(session_identifier).upper()}.xctestconfiguration" # yapf: disable return bplist.XCTestConfiguration({ "testBundleURL": bplist.NSURL(None, f"file://{app_info['Path']}/PlugIns/{target_name}.xctest"), "sessionIdentifier": session_identifier, "targetApplicationBundleID": target_app_bundle_id, "targetApplicationArguments": target_app_args or [], "targetApplicationEnvironment": target_app_env or {}, "testsToRun": tests_to_run or set(), # We can use "set()" or "None" as default value, but "{}" won't work because the decoding process regards "{}" as a dictionary. "testsMustRunOnMainThread": True, "reportResultsToIDE": True, "reportActivities": True, "automationFrameworkPath": "/Developer/Library/PrivateFrameworks/XCTAutomationSupport.framework", }) # yapf: disable def _launch_wda_app(self, bundle_id: str, session_identifier: uuid.UUID, xctest_configuration: bplist.XCTestConfiguration, quit_event: threading.Event = None, test_runner_env: Optional[dict] = None, test_runner_args: Optional[list] = None ) -> typing.Tuple[ServiceInstruments, int]: # pid app_info = self.installation.lookup(bundle_id) sign_identity = app_info.get("SignerIdentity", "") logger.info("SignIdentity: %r", sign_identity) app_container = app_info['Container'] # CFBundleName always endswith -Runner exec_name = app_info['CFBundleExecutable'] logger.info("CFBundleExecutable: %s", exec_name) assert exec_name.endswith("-Runner"), "Invalid CFBundleExecutable: %s" % exec_name target_name = exec_name[:-len("-Runner")] xctest_path = f"/tmp/{target_name}-{str(session_identifier).upper()}.xctestconfiguration" # yapf: disable xctest_content = bplist.objc_encode(xctest_configuration) fsync = self.app_sync(bundle_id, command="VendContainer") for fname in fsync.listdir("/tmp"): if fname.endswith(".xctestconfiguration"): logger.debug("remove /tmp/%s", fname) fsync.remove("/tmp/" + fname) fsync.push_content(xctest_path, xctest_content) # service: com.apple.instruments.remoteserver conn = self.connect_instruments() channel = conn.make_channel(InstrumentsService.ProcessControl) conn.call_message(channel, "processIdentifierForBundleIdentifier:", [bundle_id]) # launch app identifier = "launchSuspendedProcessWithDevicePath:bundleIdentifier:environment:arguments:options:" app_path = app_info['Path'] xctestconfiguration_path = app_container + xctest_path # xctest_path="/tmp/WebDriverAgentRunner-" + str(session_identifier).upper() + ".xctestconfiguration" logger.debug("AppPath: %s", app_path) logger.debug("AppContainer: %s", app_container) app_env = { 'CA_ASSERT_MAIN_THREAD_TRANSACTIONS': '0', 'CA_DEBUG_TRANSACTIONS': '0', 'DYLD_FRAMEWORK_PATH': app_path + '/Frameworks:', 'DYLD_LIBRARY_PATH': app_path + '/Frameworks', 'MTC_CRASH_ON_REPORT': '1', 'NSUnbufferedIO': 'YES', 'SQLITE_ENABLE_THREAD_ASSERTIONS': '1', 'WDA_PRODUCT_BUNDLE_IDENTIFIER': '', 'XCTestBundlePath': f"{app_info['Path']}/PlugIns/{target_name}.xctest", 'XCTestConfigurationFilePath': xctestconfiguration_path, 'XCODE_DBG_XPC_EXCLUSIONS': 'com.apple.dt.xctestSymbolicator', 'MJPEG_SERVER_PORT': '', 'USE_PORT': '', # maybe no needed 'LLVM_PROFILE_FILE': app_container + "/tmp/%p.profraw", # %p means pid } # yapf: disable if test_runner_env: app_env.update(test_runner_env) if self.major_version() >= 11: app_env['DYLD_INSERT_LIBRARIES'] = '/Developer/usr/lib/libMainThreadChecker.dylib' app_env['OS_ACTIVITY_DT_MODE'] = 'YES' app_args = [ '-NSTreatUnknownArgumentsAsOpen', 'NO', '-ApplePersistenceIgnoreState', 'YES' ] app_args.extend(test_runner_args or []) app_options = {'StartSuspendedKey': False} if self.major_version() >= 12: app_options['ActivateSuspended'] = True pid = conn.call_message( channel, identifier, [app_path, bundle_id, app_env, app_args, app_options]) if not isinstance(pid, int): logger.error("Launch failed: %s", pid) raise MuxError("Launch failed") logger.info("Launch %r pid: %d", bundle_id, pid) aux = AUXMessageBuffer() aux.append_obj(pid) conn.call_message(channel, "startObservingPid:", aux) def _callback(m: DTXMessage): # logger.info("output: %s", m.result) if m is None: logger.warning("WebDriverAgentRunner quitted") return if m.flags == 0x02: method, args = m.result if method == 'outputReceived:fromProcess:atTime:': # logger.info("Output: %s", args[0].strip()) logger.debug("logProcess: %s", args[0].rstrip()) # XCTestOutputBarrier is just ouput separators, no need to # print them in the logs. if args[0].rstrip() != 'XCTestOutputBarrier': xcuitest_console_logger.debug('%s', args[0].rstrip()) # In low iOS versions, 'Using singleton test manager' may not be printed... mark wda launch status = True if server url has been printed if "ServerURLHere" in args[0]: logger.info("%s", args[0].rstrip()) logger.info("WebDriverAgent start successfully") def _log_message_callback(m: DTXMessage): identifier, args = m.result logger.debug("logConsole: %s", args) if isinstance(args, (tuple, list)): for msg in args: msg = msg.rstrip() if isinstance(msg, str) else msg xcuitest_process_logger.debug('%s', msg) else: xcuitest_process_logger.debug('%s', args) conn.register_callback("_XCT_logDebugMessage:", _log_message_callback) conn.register_callback(Event.NOTIFICATION, _callback) if quit_event: conn.register_callback(Event.FINISHED, lambda _: quit_event.set()) return conn, pid def major_version(self) -> int: version = self.get_value("ProductVersion") return int(version.split(".")[0]) def _fnmatch_find_bundle_id(self, bundle_id: str) -> str: bundle_ids = [] for binfo in self.installation.iter_installed( attrs=['CFBundleIdentifier']): if fnmatch.fnmatch(binfo['CFBundleIdentifier'], bundle_id): bundle_ids.append(binfo['CFBundleIdentifier']) if not bundle_ids: raise MuxError("No app matches", bundle_id) # use irma first bundle_ids.sort( key=lambda v: v != 'com.facebook.wda.irmarunner.xctrunner') return bundle_ids[0] def runwda(self, fuzzy_bundle_id="com.*.xctrunner", target_bundle_id=None, test_runner_env: Optional[dict]=None, test_runner_args: Optional[list]=None, target_app_env: Optional[dict]=None, target_app_args: Optional[list]=None, tests_to_run: Optional[set]=None): """ Alias of xcuitest """ bundle_id = self._fnmatch_find_bundle_id(fuzzy_bundle_id) logger.info("BundleID: %s", bundle_id) return self.xcuitest(bundle_id, target_bundle_id=target_bundle_id, test_runner_env=test_runner_env, test_runner_args=test_runner_args, target_app_env=target_app_env, target_app_args=target_app_args, tests_to_run=tests_to_run) def xcuitest(self, bundle_id, target_bundle_id=None, test_runner_env: dict={}, test_runner_args: Optional[list]=None, target_app_env: Optional[dict]=None, target_app_args: Optional[list]=None, tests_to_run: Optional[set]=None): """ Launch xctrunner and wait until quit Args: bundle_id (str): xctrunner bundle id target_bundle_id (str): optional, launch WDA-UITests will not need it test_runner_env (dict[str, str]): optional, the environment variables to be passed to the test runner test_runner_args (list[str]): optional, the command line arguments to be passed to the test runner target_app_env (dict[str, str]): optional, the environmen variables to be passed to the target app target_app_args (list[str]): optional, the command line arguments to be passed to the target app tests_to_run (set[str]): optional, the specific test classes or test methods to run """ product_version = self.get_value("ProductVersion") logger.info("ProductVersion: %s", product_version) logger.info("UDID: %s", self.udid) XCODE_VERSION = 29 session_identifier = uuid.uuid4() # when connections closes, this event will be set quit_event = threading.Event() ## ## IDE 1st connection x1 = self._connect_testmanagerd_lockdown() # index: 427 x1_daemon_chan = x1.make_channel( 'dtxproxy:XCTestManager_IDEInterface:XCTestManager_DaemonConnectionInterface' ) if self.major_version() >= 11: identifier = '_IDE_initiateControlSessionWithProtocolVersion:' aux = AUXMessageBuffer() aux.append_obj(XCODE_VERSION) x1.call_message(x1_daemon_chan, identifier, aux) x1.register_callback(Event.FINISHED, lambda _: quit_event.set()) ## ## IDE 2nd connection x2 = self._connect_testmanagerd_lockdown() x2_deamon_chan = x2.make_channel( 'dtxproxy:XCTestManager_IDEInterface:XCTestManager_DaemonConnectionInterface' ) x2.register_callback(Event.FINISHED, lambda _: quit_event.set()) #x2.register_callback("pidDiedCallback:" # maybe no needed _start_flag = threading.Event() def _start_executing(m: Optional[DTXMessage] = None): if _start_flag.is_set(): return _start_flag.set() logger.info("Start execute test plan with IDE version: %d", XCODE_VERSION) x2.call_message(0xFFFFFFFF, '_IDE_startExecutingTestPlanWithProtocolVersion:', [XCODE_VERSION], expects_reply=False) def _show_log_message(m: DTXMessage): logger.debug("logMessage: %s", m.result[1]) if 'Received test runner ready reply' in ''.join( m.result[1]): logger.info("Test runner ready detected") _start_executing() if isinstance(m.result[1], (tuple, list)): for msg in m.result[1]: msg = msg.rstrip() if isinstance(msg, str) else msg xcuitest_process_logger.debug('%s', msg) else: xcuitest_process_logger.debug('%s', m.result[1]) test_results = [] test_results_lock = threading.Lock() def _record_test_result_callback(m: DTXMessage): result = None if isinstance(m.result, (tuple, list)) and len(m.result) >= 1: if isinstance(m.result[1], (tuple, list)): try: result = XCTestResult(*m.result[1]) except TypeError: pass if not result: logger.warning('Ignore unknown test result message: %s', m) return with test_results_lock: test_results.append(result) x2.register_callback( '_XCT_testBundleReadyWithProtocolVersion:minimumVersion:', _start_executing) # This only happends <= iOS 13 x2.register_callback('_XCT_logDebugMessage:', _show_log_message) x2.register_callback( "_XCT_testSuite:didFinishAt:runCount:withFailures:unexpected:testDuration:totalDuration:", _record_test_result_callback) app_info = self.installation.lookup(bundle_id) xctest_configuration = self._gen_xctest_configuration(app_info, session_identifier, target_bundle_id, target_app_env, target_app_args, tests_to_run) def _ready_with_caps_callback(m: DTXMessage): x2.send_dtx_message(m.channel_id, payload=DTXPayload.build_other(0x03, xctest_configuration), message_id=m.message_id) x2.register_callback('_XCT_testRunnerReadyWithCapabilities:', _ready_with_caps_callback) # index: 469 identifier = '_IDE_initiateSessionWithIdentifier:forClient:atPath:protocolVersion:' aux = AUXMessageBuffer() aux.append_obj(session_identifier) aux.append_obj(str(session_identifier) + '-6722-000247F15966B083') aux.append_obj( '/Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild') aux.append_obj(XCODE_VERSION) result = x2.call_message(x2_deamon_chan, identifier, aux) if "NSError" in str(result): raise RuntimeError("Xcode Invocation Failed: {}".format(result)) # launch test app # index: 1540 xclogger = setup_logger(name='xcuitest') _, pid = self._launch_wda_app( bundle_id, session_identifier, xctest_configuration=xctest_configuration, test_runner_env=test_runner_env, test_runner_args=test_runner_args) # xcode call the following commented method, twice # but it seems can be ignored # identifier = '_IDE_collectNewCrashReportsInDirectories:matchingProcessNames:' # aux = AUXMessageBuffer() # aux.append_obj(['/var/mobile/Library/Logs/CrashReporter/']) # aux.append_obj(['SpringBoard', 'backboardd', 'xctest']) # result = x1.call_message(chan, identifier, aux) # logger.debug("result: %s", result) # identifier = '_IDE_collectNewCrashReportsInDirectories:matchingProcessNames:' # aux = AUXMessageBuffer() # aux.append_obj(['/var/mobile/Library/Logs/CrashReporter/']) # aux.append_obj(['SpringBoard', 'backboardd', 'xctest']) # result = x1.call_message(chan, identifier, aux) # logger.debug("result: %s", result) # after app launched, operation bellow must be send in 0.1s # or wda will launch failed if self.major_version() >= 12: identifier = '_IDE_authorizeTestSessionWithProcessID:' aux = AUXMessageBuffer() aux.append_obj(pid) result = x1.call_message(x1_daemon_chan, identifier, aux) elif self.major_version() <= 9: identifier = '_IDE_initiateControlSessionForTestProcessID:' aux = AUXMessageBuffer() aux.append_obj(pid) result = x1.call_message(x1_daemon_chan, identifier, aux) else: identifier = '_IDE_initiateControlSessionForTestProcessID:protocolVersion:' aux = AUXMessageBuffer() aux.append_obj(pid) aux.append_obj(XCODE_VERSION) result = x1.call_message(x1_daemon_chan, identifier, aux) if "NSError" in str(result): raise RuntimeError("Xcode Invocation Failed: {}".format(result)) # wait for quit # on windows threading.Event.wait can't handle ctrl-c while not quit_event.wait(.1): pass test_result_str = "\n".join(map(str, test_results)) if any(result.failure_count > 0 for result in test_results): raise RuntimeError( "Xcode test failed on device with test results:\n" f"{test_result_str}" ) logger.info("xctrunner quited with result:\n%s", test_result_str) def iter_fps(d: BaseDevice) -> Iterator[Any]: with d.connect_instruments() as ts: for data in ts.iter_opengl_data(): fps = data['CoreAnimationFramesPerSecond'] # fps from GPU # print("FPS:", fps) yield DataType.FPS, {"fps": fps, "time": time.time(), "value": fps}
null