language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | ansible__ansible | lib/ansible/module_utils/facts/hardware/aix.py | {
"start": 11817,
"end": 11916
} | class ____(HardwareCollector):
_platform = 'AIX'
_fact_class = AIXHardware
| AIXHardwareCollector |
python | getsentry__sentry | src/sentry/replays/lib/eap/snuba_transpiler.py | {
"start": 31316,
"end": 31428
} | class ____(TypedDict):
can_go_to_higher_accuracy: bool
estimated_rows: int
| QueryResultMetaDownsamplingMode |
python | great-expectations__great_expectations | great_expectations/expectations/set_based_column_map_expectation.py | {
"start": 3093,
"end": 13816
} | class ____(ColumnMapExpectation, ABC):
"""Base class for SetBasedColumnMapExpectations.
SetBasedColumnMapExpectations facilitate set-based comparisons as the core logic for a Map Expectation.
Example Definition:
```python
ExpectColumnValuesToBeInSolfegeScaleSet(SetBasedColumnMapExpectation):
set_camel_name = SolfegeScale
set_ = ['do', 're', 'mi', 'fa', 'so', 'la', 'ti']
set_semantic_name = "the Solfege scale"
map_metric = SetBasedColumnMapExpectation.register_metric(
set_camel_name=set_camel_name,
set_=set_
)
```
Args:
set_camel_name (str): A name describing a set of values, in camel case.
set_ (str): A value set.
set_semantic_name (optional[str]): A name for the semantic type representing the set being validated..
map_metric (str): The name of an ephemeral metric, as returned by `register_metric(...)`.
---Documentation---
- https://docs.greatexpectations.io/docs/guides/expectations/creating_custom_expectations/how_to_create_custom_set_based_column_map_expectations
""" # noqa: E501 # FIXME CoP
@staticmethod
def register_metric(
set_camel_name: str,
set_: str,
) -> str:
"""Register an ephemeral metric using a constructed name with the logic provided by SetColumnMapMetricProvider.
Args:
set_camel_name: A name describing a set of values, in camel case.
set_: A value set.
Returns:
map_metric: The constructed name of the ephemeral metric.
""" # noqa: E501 # FIXME CoP
set_snake_name = camel_to_snake(set_camel_name)
map_metric: str = "column_values.match_" + set_snake_name + "_set"
# Define the class using `type`. This allows us to name it dynamically.
new_column_set_metric_provider = type( # noqa: F841 # never used
f"(ColumnValuesMatch{set_camel_name}Set",
(SetColumnMapMetricProvider,),
{
"condition_metric_name": map_metric,
"set_": set_,
},
)
return map_metric
def validate_configuration(
self, configuration: Optional[ExpectationConfiguration] = None
) -> None:
"""Raise an exception if the configuration is not viable for an expectation.
Args:
configuration: An ExpectationConfiguration
Raises:
InvalidExpectationConfigurationError: If no `set_` or `column` specified, or if `mostly` parameter
incorrectly defined.
""" # noqa: E501 # FIXME CoP
super().validate_configuration(configuration)
try:
assert getattr(self, "set_", None) is not None, (
"set_ is required for SetBasedColumnMap Expectations"
)
assert "column" in configuration.kwargs, (
"'column' parameter is required for ColumnMap expectations"
)
if "mostly" in configuration.kwargs:
mostly = configuration.kwargs["mostly"]
assert isinstance(mostly, (int, float)), (
"'mostly' parameter must be an integer or float"
)
assert 0 <= mostly <= 1, "'mostly' parameter must be between 0 and 1"
except AssertionError as e:
raise InvalidExpectationConfigurationError(str(e))
# question, descriptive, prescriptive, diagnostic
@classmethod
@renderer(renderer_type=LegacyRendererType.QUESTION)
def _question_renderer(cls, configuration, result=None, runtime_configuration=None):
column = configuration.kwargs.get("column")
mostly = configuration.kwargs.get("mostly")
set_ = cls.set_
set_semantic_name = getattr(cls, "set_semantic_name", None)
if mostly == 1 or mostly is None:
if set_semantic_name is not None:
return f'Are all values in column "{column}" in {set_semantic_name}: {set_!s}?'
else:
return f'Are all values in column "{column}" in the set {set_!s}?'
else: # noqa: PLR5501 # FIXME CoP
if set_semantic_name is not None:
return f'Are at least {mostly * 100}% of values in column "{column}" in {set_semantic_name}: {set_!s}?' # noqa: E501 # FIXME CoP
else:
return f'Are at least {mostly * 100}% of values in column "{column}" in the set {set_!s}?' # noqa: E501 # FIXME CoP
@classmethod
@renderer(renderer_type=LegacyRendererType.ANSWER)
def _answer_renderer(cls, configuration=None, result=None, runtime_configuration=None):
column = result.expectation_config.kwargs.get("column")
mostly = result.expectation_config.kwargs.get("mostly")
set_ = cls.set_
set_semantic_name = getattr(cls, "set_semantic_name", None)
if result.success:
if mostly == 1 or mostly is None:
if set_semantic_name is not None:
return f'All values in column "{column}" are in {set_semantic_name}: {set_!s}.'
else:
return f'All values in column "{column}" are in the set {set_!s}.'
else: # noqa: PLR5501 # FIXME CoP
if set_semantic_name is not None:
return f'At least {mostly * 100}% of values in column "{column}" are in {set_semantic_name}: {set_!s}.' # noqa: E501 # FIXME CoP
else:
return f'At least {mostly * 100}% of values in column "{column}" are in the set {set!s}.' # noqa: E501 # FIXME CoP
else: # noqa: PLR5501 # FIXME CoP
if set_semantic_name is not None:
return f' Less than {mostly * 100}% of values in column "{column}" are in {set_semantic_name}: {set_!s}.' # noqa: E501 # FIXME CoP
else:
return f'Less than {mostly * 100}% of values in column "{column}" are in the set {set_!s}.' # noqa: E501 # FIXME CoP
@classmethod
def _prescriptive_template(
cls,
renderer_configuration: RendererConfiguration,
) -> RendererConfiguration:
add_param_args: AddParamArgs = (
("column", RendererValueType.STRING),
("mostly", RendererValueType.NUMBER),
("set_", RendererValueType.STRING),
("set_semantic_name", RendererValueType.STRING),
)
for name, param_type in add_param_args:
renderer_configuration.add_param(name=name, param_type=param_type)
params = renderer_configuration.params
if not params.set_:
template_str = "values must match a set but none was specified."
else:
if params.set_semantic_name:
template_str = "values must match the set $set_semantic_name: $set_"
else:
template_str = "values must match this set: $set_"
if params.mostly and params.mostly.value < 1.0:
renderer_configuration = cls._add_mostly_pct_param(
renderer_configuration=renderer_configuration
)
template_str += ", at least $mostly_pct % of the time."
else:
template_str += "."
if renderer_configuration.include_column_name:
template_str = "$column " + template_str
renderer_configuration.template_str = template_str
return renderer_configuration
@classmethod
@renderer(renderer_type=LegacyRendererType.PRESCRIPTIVE)
@render_suite_parameter_string
def _prescriptive_renderer(
cls,
configuration: Optional[ExpectationConfiguration] = None,
result: Optional[ExpectationValidationResult] = None,
runtime_configuration: Optional[dict] = None,
**kwargs,
):
runtime_configuration = runtime_configuration or {}
include_column_name = runtime_configuration.get("include_column_name") is not False
styling = runtime_configuration.get("styling")
params = substitute_none_for_missing(
configuration.kwargs,
[
"column",
"set_",
"mostly",
"row_condition",
"condition_parser",
"set_semantic_name",
],
)
if not params.get("set_"):
template_str = "values must match a set but none was specified."
else:
if params.get("set_semantic_name"):
template_str = "values must match the set $set_semantic_name: $set_"
else:
template_str = "values must match this set: $set_"
if params["mostly"] is not None:
params["mostly_pct"] = num_to_str(params["mostly"] * 100, no_scientific=True)
template_str += ", at least $mostly_pct % of the time."
else:
template_str += "."
if include_column_name:
template_str = "$column " + template_str
if params["row_condition"] is not None:
conditional_template_str = parse_row_condition_string(params["row_condition"])
template_str, styling = _style_row_condition(
conditional_template_str,
template_str,
params,
styling,
)
params_with_json_schema = { # noqa: F841 # never used
"column": {"schema": {"type": "string"}, "value": params.get("column")},
"mostly": {"schema": {"type": "number"}, "value": params.get("mostly")},
"mostly_pct": {
"schema": {"type": "number"},
"value": params.get("mostly_pct"),
},
"set_": {"schema": {"type": "string"}, "value": params.get("set_")},
"row_condition": {
"schema": {"type": "string"},
"value": params.get("row_condition"),
},
"condition_parser": {
"schema": {"type": "string"},
"value": params.get("condition_parser"),
},
"set_semantic_name": {
"schema": {"type": "string"},
"value": params.get("set_semantic_name"),
},
}
return [
RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": template_str,
"params": params,
"styling": styling,
},
}
)
]
| SetBasedColumnMapExpectation |
python | great-expectations__great_expectations | great_expectations/data_context/store/metric_store.py | {
"start": 449,
"end": 2292
} | class ____(Store):
"""
A MetricStore stores ValidationMetric information to be used between runs.
"""
_key_class: ClassVar[Type] = ValidationMetricIdentifier
def __init__(self, store_backend=None, store_name=None) -> None:
if store_backend is not None:
store_backend_module_name = store_backend.get(
"module_name", "great_expectations.data_context.store"
)
store_backend_class_name = store_backend.get("class_name", "InMemoryStoreBackend")
verify_dynamic_loading_support(module_name=store_backend_module_name)
store_backend_class = load_class(store_backend_class_name, store_backend_module_name)
if issubclass(store_backend_class, DatabaseStoreBackend):
# Provide defaults for this common case
if "table_name" not in store_backend:
store_backend["table_name"] = store_backend.get("table_name", "ge_metrics")
if "key_columns" not in store_backend:
store_backend["key_columns"] = store_backend.get(
"key_columns",
[
"run_name",
"run_time",
"data_asset_name",
"expectation_suite_identifier",
"metric_name",
"metric_kwargs_id",
],
)
super().__init__(store_backend=store_backend, store_name=store_name)
def serialize(self, value): # type: ignore[explicit-override] # FIXME
return json.dumps({"value": value})
def deserialize(self, value): # type: ignore[explicit-override] # FIXME
if value:
return json.loads(value)["value"]
| MetricStore |
python | wandb__wandb | wandb/vendor/pygments/styles/arduino.py | {
"start": 392,
"end": 4490
} | class ____(Style):
"""
The Arduino® language style. This style is designed to highlight the
Arduino source code, so exepect the best results with it.
"""
background_color = "#ffffff"
default_style = ""
styles = {
Whitespace: "", # class: 'w'
Error: "#a61717", # class: 'err'
Comment: "#95a5a6", # class: 'c'
Comment.Multiline: "", # class: 'cm'
Comment.Preproc: "#728E00", # class: 'cp'
Comment.Single: "", # class: 'c1'
Comment.Special: "", # class: 'cs'
Keyword: "#728E00", # class: 'k'
Keyword.Constant: "#00979D", # class: 'kc'
Keyword.Declaration: "", # class: 'kd'
Keyword.Namespace: "", # class: 'kn'
Keyword.Pseudo: "#00979D", # class: 'kp'
Keyword.Reserved: "#00979D", # class: 'kr'
Keyword.Type: "#00979D", # class: 'kt'
Operator: "#728E00", # class: 'o'
Operator.Word: "", # class: 'ow'
Name: "#434f54", # class: 'n'
Name.Attribute: "", # class: 'na'
Name.Builtin: "#728E00", # class: 'nb'
Name.Builtin.Pseudo: "", # class: 'bp'
Name.Class: "", # class: 'nc'
Name.Constant: "", # class: 'no'
Name.Decorator: "", # class: 'nd'
Name.Entity: "", # class: 'ni'
Name.Exception: "", # class: 'ne'
Name.Function: "#D35400", # class: 'nf'
Name.Property: "", # class: 'py'
Name.Label: "", # class: 'nl'
Name.Namespace: "", # class: 'nn'
Name.Other: "#728E00", # class: 'nx'
Name.Tag: "", # class: 'nt'
Name.Variable: "", # class: 'nv'
Name.Variable.Class: "", # class: 'vc'
Name.Variable.Global: "", # class: 'vg'
Name.Variable.Instance: "", # class: 'vi'
Number: "#8A7B52", # class: 'm'
Number.Float: "", # class: 'mf'
Number.Hex: "", # class: 'mh'
Number.Integer: "", # class: 'mi'
Number.Integer.Long: "", # class: 'il'
Number.Oct: "", # class: 'mo'
String: "#7F8C8D", # class: 's'
String.Backtick: "", # class: 'sb'
String.Char: "", # class: 'sc'
String.Doc: "", # class: 'sd'
String.Double: "", # class: 's2'
String.Escape: "", # class: 'se'
String.Heredoc: "", # class: 'sh'
String.Interpol: "", # class: 'si'
String.Other: "", # class: 'sx'
String.Regex: "", # class: 'sr'
String.Single: "", # class: 's1'
String.Symbol: "", # class: 'ss'
Generic: "", # class: 'g'
Generic.Deleted: "", # class: 'gd',
Generic.Emph: "", # class: 'ge'
Generic.Error: "", # class: 'gr'
Generic.Heading: "", # class: 'gh'
Generic.Inserted: "", # class: 'gi'
Generic.Output: "", # class: 'go'
Generic.Prompt: "", # class: 'gp'
Generic.Strong: "", # class: 'gs'
Generic.Subheading: "", # class: 'gu'
Generic.Traceback: "", # class: 'gt'
}
| ArduinoStyle |
python | pydata__xarray | xarray/core/accessor_dt.py | {
"start": 7847,
"end": 10308
} | class ____(Generic[T_DataArray]):
__slots__ = ("_obj",)
def __init__(self, obj: T_DataArray) -> None:
self._obj = obj
def _date_field(self, name: str, dtype: DTypeLike | None) -> T_DataArray:
if dtype is None:
dtype = self._obj.dtype
result = _get_date_field(_index_or_data(self._obj), name, dtype)
newvar = Variable(
dims=self._obj.dims,
attrs=self._obj.attrs,
encoding=self._obj.encoding,
data=result,
)
return self._obj._replace(newvar, name=name)
def _tslib_round_accessor(self, name: str, freq: str) -> T_DataArray:
result = _round_field(_index_or_data(self._obj), name, freq)
newvar = Variable(
dims=self._obj.dims,
attrs=self._obj.attrs,
encoding=self._obj.encoding,
data=result,
)
return self._obj._replace(newvar, name=name)
def floor(self, freq: str) -> T_DataArray:
"""
Round timestamps downward to specified frequency resolution.
Parameters
----------
freq : str
a freq string indicating the rounding resolution e.g. "D" for daily resolution
Returns
-------
floor-ed timestamps : same type as values
Array-like of datetime fields accessed for each element in values
"""
return self._tslib_round_accessor("floor", freq)
def ceil(self, freq: str) -> T_DataArray:
"""
Round timestamps upward to specified frequency resolution.
Parameters
----------
freq : str
a freq string indicating the rounding resolution e.g. "D" for daily resolution
Returns
-------
ceil-ed timestamps : same type as values
Array-like of datetime fields accessed for each element in values
"""
return self._tslib_round_accessor("ceil", freq)
def round(self, freq: str) -> T_DataArray:
"""
Round timestamps to specified frequency resolution.
Parameters
----------
freq : str
a freq string indicating the rounding resolution e.g. "D" for daily resolution
Returns
-------
rounded timestamps : same type as values
Array-like of datetime fields accessed for each element in values
"""
return self._tslib_round_accessor("round", freq)
| TimeAccessor |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 273866,
"end": 274482
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("DeploymentEdge"), graphql_name="edges"
)
nodes = sgqlc.types.Field(sgqlc.types.list_of("Deployment"), graphql_name="nodes")
page_info = sgqlc.types.Field(
sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo"
)
total_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="totalCount"
)
| DeploymentConnection |
python | pdm-project__pdm | src/pdm/cli/commands/cache.py | {
"start": 3749,
"end": 4148
} | class ____(BaseCommand):
"""Remove files matching the given pattern"""
arguments = (verbose_option,)
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
parser.add_argument("pattern", help="The pattern to remove")
def handle(self, project: Project, options: argparse.Namespace) -> None:
return remove_cache_files(project, options.pattern)
| RemoveCommand |
python | langchain-ai__langchain | libs/core/langchain_core/example_selectors/semantic_similarity.py | {
"start": 8276,
"end": 13577
} | class ____(_VectorStoreExampleSelector):
"""Select examples based on Max Marginal Relevance.
This was shown to improve performance in this paper:
https://arxiv.org/pdf/2211.13892.pdf
"""
fetch_k: int = 20
"""Number of examples to fetch to rerank."""
def select_examples(self, input_variables: dict[str, str]) -> list[dict]:
"""Select examples based on Max Marginal Relevance.
Args:
input_variables: The input variables to use for search.
Returns:
The selected examples.
"""
example_docs = self.vectorstore.max_marginal_relevance_search(
self._example_to_text(input_variables, self.input_keys),
k=self.k,
fetch_k=self.fetch_k,
)
return self._documents_to_examples(example_docs)
async def aselect_examples(self, input_variables: dict[str, str]) -> list[dict]:
"""Asynchronously select examples based on Max Marginal Relevance.
Args:
input_variables: The input variables to use for search.
Returns:
The selected examples.
"""
example_docs = await self.vectorstore.amax_marginal_relevance_search(
self._example_to_text(input_variables, self.input_keys),
k=self.k,
fetch_k=self.fetch_k,
)
return self._documents_to_examples(example_docs)
@classmethod
def from_examples(
cls,
examples: list[dict],
embeddings: Embeddings,
vectorstore_cls: type[VectorStore],
k: int = 4,
input_keys: list[str] | None = None,
fetch_k: int = 20,
example_keys: list[str] | None = None,
vectorstore_kwargs: dict | None = None,
**vectorstore_cls_kwargs: Any,
) -> MaxMarginalRelevanceExampleSelector:
"""Create k-shot example selector using example list and embeddings.
Reshuffles examples dynamically based on Max Marginal Relevance.
Args:
examples: List of examples to use in the prompt.
embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
vectorstore_cls: A vector store DB interface class, e.g. FAISS.
k: Number of examples to select.
fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
input_keys: If provided, the search is based on the input variables
instead of all variables.
example_keys: If provided, keys to filter examples to.
vectorstore_kwargs: Extra arguments passed to similarity_search function
of the `VectorStore`.
vectorstore_cls_kwargs: optional kwargs containing url for vector store
Returns:
The ExampleSelector instantiated, backed by a vector store.
"""
string_examples = [cls._example_to_text(eg, input_keys) for eg in examples]
vectorstore = vectorstore_cls.from_texts(
string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
)
return cls(
vectorstore=vectorstore,
k=k,
fetch_k=fetch_k,
input_keys=input_keys,
example_keys=example_keys,
vectorstore_kwargs=vectorstore_kwargs,
)
@classmethod
async def afrom_examples(
cls,
examples: list[dict],
embeddings: Embeddings,
vectorstore_cls: type[VectorStore],
*,
k: int = 4,
input_keys: list[str] | None = None,
fetch_k: int = 20,
example_keys: list[str] | None = None,
vectorstore_kwargs: dict | None = None,
**vectorstore_cls_kwargs: Any,
) -> MaxMarginalRelevanceExampleSelector:
"""Create k-shot example selector using example list and embeddings.
Reshuffles examples dynamically based on Max Marginal Relevance.
Args:
examples: List of examples to use in the prompt.
embeddings: An initialized embedding API interface, e.g. OpenAIEmbeddings().
vectorstore_cls: A vector store DB interface class, e.g. FAISS.
k: Number of examples to select.
fetch_k: Number of `Document` objects to fetch to pass to MMR algorithm.
input_keys: If provided, the search is based on the input variables
instead of all variables.
example_keys: If provided, keys to filter examples to.
vectorstore_kwargs: Extra arguments passed to similarity_search function
of the `VectorStore`.
vectorstore_cls_kwargs: optional kwargs containing url for vector store
Returns:
The ExampleSelector instantiated, backed by a vector store.
"""
string_examples = [cls._example_to_text(eg, input_keys) for eg in examples]
vectorstore = await vectorstore_cls.afrom_texts(
string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
)
return cls(
vectorstore=vectorstore,
k=k,
fetch_k=fetch_k,
input_keys=input_keys,
example_keys=example_keys,
vectorstore_kwargs=vectorstore_kwargs,
)
| MaxMarginalRelevanceExampleSelector |
python | pypa__hatch | backend/src/hatchling/builders/hooks/custom.py | {
"start": 263,
"end": 1378
} | class ____:
PLUGIN_NAME = "custom"
def __new__( # type: ignore[misc]
cls,
root: str,
config: dict[str, Any],
*args: Any,
**kwargs: Any,
) -> BuildHookInterface:
build_script = config.get("path", DEFAULT_BUILD_SCRIPT)
if not isinstance(build_script, str):
message = f"Option `path` for build hook `{cls.PLUGIN_NAME}` must be a string"
raise TypeError(message)
if not build_script:
message = f"Option `path` for build hook `{cls.PLUGIN_NAME}` must not be empty if defined"
raise ValueError(message)
path = os.path.normpath(os.path.join(root, build_script))
if not os.path.isfile(path):
message = f"Build script does not exist: {build_script}"
raise OSError(message)
hook_class = load_plugin_from_script(path, build_script, BuildHookInterface, "build_hook")
hook = hook_class(root, config, *args, **kwargs)
# Always keep the name to avoid confusion
hook.PLUGIN_NAME = cls.PLUGIN_NAME
return hook
| CustomBuildHook |
python | gevent__gevent | src/gevent/tests/test__event.py | {
"start": 11172,
"end": 12433
} | class ____(greentest.TestCase):
N = 5
count = None
timeout = 1
period = timeout / 100.0
def _sender(self, events, asyncs):
while events or asyncs:
gevent.sleep(self.period)
if events:
events.pop().set()
gevent.sleep(self.period)
if asyncs:
asyncs.pop().set()
@greentest.skipOnAppVeyor("Not all results have arrived sometimes due to timer issues")
def test(self):
events = [Event() for _ in xrange(self.N)]
asyncs = [AsyncResult() for _ in xrange(self.N)]
max_len = len(events) + len(asyncs)
sender = gevent.spawn(self._sender, events, asyncs)
results = gevent.wait(events + asyncs, count=self.count, timeout=self.timeout)
if self.timeout is None:
expected_len = max_len
else:
expected_len = min(max_len, self.timeout / self.period)
if self.count is None:
self.assertTrue(sender.ready(), sender)
else:
expected_len = min(self.count, expected_len)
self.assertFalse(sender.ready(), sender)
sender.kill()
self.assertEqual(expected_len, len(results), (expected_len, len(results), results))
| TestWait |
python | joke2k__faker | tests/providers/test_internet.py | {
"start": 26212,
"end": 26511
} | class ____:
"""Test zh_TW internet provider methods"""
def test_email(self, faker):
email = faker.email()
validate_email(email)
def test_slug(self, faker):
num_of_samples = 100
for _ in range(num_of_samples):
assert faker.slug() != ""
| TestZhTw |
python | doocs__leetcode | solution/3000-3099/3021.Alice and Bob Playing Flower Game/Solution.py | {
"start": 0,
"end": 190
} | class ____:
def flowerGame(self, n: int, m: int) -> int:
a1 = (n + 1) // 2
b1 = (m + 1) // 2
a2 = n // 2
b2 = m // 2
return a1 * b2 + a2 * b1
| Solution |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_test.py | {
"start": 60223,
"end": 63140
} | class ____(test_util.TensorFlowTestCase):
def testGenerateName(self):
g = ops.Graph()
op0 = g.create_op("TwoFloatOutputs", [], [dtypes.float32, dtypes.float32])
self.assertEqual("TwoFloatOutputs", op0.name)
self.assertEqual("TwoFloatOutputs:0", op0.outputs[0].name)
self.assertEqual("TwoFloatOutputs:1", op0.outputs[1].name)
op1 = g.create_op("FloatOutput", [], [dtypes.float32])
self.assertEqual("FloatOutput", op1.name)
self.assertEqual("FloatOutput:0", op1.outputs[0].name)
op2 = g.create_op("FloatOutput", [], [dtypes.float32])
self.assertEqual("FloatOutput_1", op2.name)
self.assertEqual("FloatOutput_1:0", op2.outputs[0].name)
op3 = g.create_op("FloatOutput", [], [dtypes.float32], name="my_op")
self.assertEqual("my_op", op3.name)
self.assertEqual("my_op:0", op3.outputs[0].name)
def testNameScope(self):
g = ops.Graph()
with g.name_scope("foo") as foo:
self.assertEqual("foo/", foo)
with g.name_scope("foo2") as foo2:
self.assertEqual("foo/foo2/", foo2)
with g.name_scope(None) as empty1:
self.assertEqual("", empty1)
with g.name_scope("foo3") as foo3:
self.assertEqual("foo3/", foo3)
with g.name_scope("") as empty2:
self.assertEqual("", empty2)
self.assertEqual("FloatOutput",
g.create_op("FloatOutput", [], [dtypes.float32]).name)
with g.name_scope("bar") as scope:
self.assertEqual("bar/FloatOutput",
g.create_op("FloatOutput", [], [dtypes.float32]).name)
self.assertEqual("bar/FloatOutput_1",
g.create_op("FloatOutput", [], [dtypes.float32]).name)
# If you use the value from "with .. as", that values is used as-is.
self.assertEqual(
"bar", g.create_op(
"FloatOutput", [], [dtypes.float32], name=scope).name)
with g.name_scope("baz") as scope:
with g.name_scope("quux"):
self.assertEqual("baz/quux/FloatOutput",
g.create_op("FloatOutput", [], [dtypes.float32]).name)
# If you use the value from the enclosing "with .. as", nothing is pushed.
with g.name_scope(scope):
self.assertEqual("baz/FloatOutput",
g.create_op("FloatOutput", [], [dtypes.float32]).name)
self.assertEqual(
"baz", g.create_op(
"FloatOutput", [], [dtypes.float32], name=scope).name)
self.assertEqual(
"trailing",
g.create_op(
"FloatOutput", [], [dtypes.float32], name="trailing/").name)
with g.name_scope("bar"):
self.assertEqual("bar_1/FloatOutput",
g.create_op("FloatOutput", [], [dtypes.float32]).name)
with g.name_scope("bar/"):
self.assertEqual("bar/FloatOutput_2",
g.create_op("FloatOutput", [], [dtypes.float32]).name)
| NameTest |
python | getsentry__sentry | src/sentry/rules/conditions/event_frequency.py | {
"start": 2948,
"end": 4425
} | class ____(forms.Form):
intervals = STANDARD_INTERVALS
interval = forms.ChoiceField(
choices=[
(key, label)
for key, (label, _) in sorted(
intervals.items(), key=lambda key____label__duration: key____label__duration[1][1]
)
]
)
value = forms.IntegerField(widget=forms.TextInput())
comparisonType = forms.ChoiceField(
choices=ComparisonType,
required=False,
)
comparisonInterval = forms.ChoiceField(
choices=[
(key, label)
for key, (label, _) in sorted(COMPARISON_INTERVALS.items(), key=lambda item: item[1][1])
],
required=False,
)
def clean(self) -> dict[str, Any] | None:
cleaned_data = super().clean()
if cleaned_data is None:
return None
# Don't store an empty string here if the value isn't passed
if cleaned_data.get("comparisonInterval") == "":
del cleaned_data["comparisonInterval"]
cleaned_data["comparisonType"] = cleaned_data.get("comparisonType") or ComparisonType.COUNT
if cleaned_data["comparisonType"] == ComparisonType.PERCENT and not cleaned_data.get(
"comparisonInterval"
):
msg = forms.ValidationError("comparisonInterval is required when comparing by percent")
self.add_error("comparisonInterval", msg)
return None
return cleaned_data
| EventFrequencyForm |
python | ray-project__ray | doc/source/serve/doc_code/app_builder.py | {
"start": 157,
"end": 750
} | class ____:
def __init__(self, message: str):
self._message = message
print("Message:", self._message)
def __call__(self, request):
return self._message
def app_builder(args: Dict[str, str]) -> Application:
return HelloWorld.bind(args["message"])
# __end_untyped_builder__
import requests
serve.run(app_builder({"message": "Hello bar"}))
resp = requests.get("http://localhost:8000")
assert resp.text == "Hello bar"
# __begin_typed_builder__
# hello.py
from pydantic import BaseModel
from ray import serve
from ray.serve import Application
| HelloWorld |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 66373,
"end": 66625
} | class ____:
xlHebrewFullScript = 0 # from enum XlHebrewModes
xlHebrewMixedAuthorizedScript = 3 # from enum XlHebrewModes
xlHebrewMixedScript = 2 # from enum XlHebrewModes
xlHebrewPartialScript = 1 # from enum XlHebrewModes
| HebrewModes |
python | ZoranPandovski__al-go-rithms | greedy/kruskal's_algorithm/python/kruskalMST.py | {
"start": 38,
"end": 1770
} | class ____:
def __init__(self,vertices):
self.V= vertices
self.graph = []
def addEdge(self,u,v,w):
self.graph.append([u,v,w])
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else :
parent[yroot] = xroot
rank[xroot] += 1
def KruskalMST(self):
result =[]
i,e = 0,0
self.graph = sorted(self.graph,key=lambda item: item[2])
parent = [] ; rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V -1 :
u,v,w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent ,v)
if x != y:
e = e + 1
result.append([u,v,w])
self.union(parent, rank, x, y)
print("Constructed MST :")
print("Vertex A Vertex B Weight")
for u,v,weight in result:
print (" %d %d %d" % (u,v,weight))
#vetx = int(input("Enter no. of vertices :"))
eegde = int(input("Enter no. of edges :"))
g = Graph(eegde-1)
print("For each edge input (Source vertex , Destination vertex , Weight of the edge ) :")
for x in range(eegde):
qq,xx,yy = map(int,input().split(" "))
g.addEdge(qq, xx, yy)
g.KruskalMST() | Graph |
python | readthedocs__readthedocs.org | readthedocs/api/v3/serializers.py | {
"start": 1833,
"end": 1976
} | class ____(serializers.ModelSerializer):
class Meta:
model = User
fields = [
"username",
]
| UserSerializer |
python | redis__redis-py | tests/test_maint_notifications.py | {
"start": 18533,
"end": 25503
} | class ____:
"""Test the MaintNotificationsPoolHandler class."""
def setup_method(self):
"""Set up test fixtures."""
self.mock_pool = Mock()
self.mock_pool._lock = MagicMock()
self.mock_pool._lock.__enter__.return_value = None
self.mock_pool._lock.__exit__.return_value = None
self.config = MaintNotificationsConfig(
enabled=True, proactive_reconnect=True, relaxed_timeout=20
)
self.handler = MaintNotificationsPoolHandler(self.mock_pool, self.config)
def test_init(self):
"""Test MaintNotificationsPoolHandler initialization."""
assert self.handler.pool == self.mock_pool
assert self.handler.config == self.config
assert isinstance(self.handler._processed_notifications, set)
assert isinstance(self.handler._lock, type(threading.RLock()))
def test_remove_expired_notifications(self):
"""Test removal of expired notifications."""
with patch("time.monotonic", return_value=1000):
notification1 = NodeMovingNotification(
id=1, new_node_host="host1", new_node_port=6379, ttl=10
)
notification2 = NodeMovingNotification(
id=2, new_node_host="host2", new_node_port=6380, ttl=5
)
self.handler._processed_notifications.add(notification1)
self.handler._processed_notifications.add(notification2)
# Move time forward but not enough to expire notification2 (expires at 1005)
with patch("time.monotonic", return_value=1003):
self.handler.remove_expired_notifications()
assert notification1 in self.handler._processed_notifications
assert (
notification2 in self.handler._processed_notifications
) # Not expired yet
# Move time forward to expire notification2 but not notification1
with patch("time.monotonic", return_value=1006):
self.handler.remove_expired_notifications()
assert notification1 in self.handler._processed_notifications
assert (
notification2 not in self.handler._processed_notifications
) # Now expired
def test_handle_notification_node_moving(self):
"""Test handling of NodeMovingNotification."""
notification = NodeMovingNotification(
id=1, new_node_host="localhost", new_node_port=6379, ttl=10
)
with patch.object(
self.handler, "handle_node_moving_notification"
) as mock_handle:
self.handler.handle_notification(notification)
mock_handle.assert_called_once_with(notification)
def test_handle_notification_unknown_type(self):
"""Test handling of unknown notification type."""
notification = NodeMigratingNotification(
id=1, ttl=5
) # Not handled by pool handler
result = self.handler.handle_notification(notification)
assert result is None
def test_handle_node_moving_notification_disabled_config(self):
"""Test node moving notification handling when both features are disabled."""
config = MaintNotificationsConfig(proactive_reconnect=False, relaxed_timeout=-1)
handler = MaintNotificationsPoolHandler(self.mock_pool, config)
notification = NodeMovingNotification(
id=1, new_node_host="localhost", new_node_port=6379, ttl=10
)
result = handler.handle_node_moving_notification(notification)
assert result is None
assert notification not in handler._processed_notifications
def test_handle_node_moving_notification_already_processed(self):
"""Test node moving notification handling when notification already processed."""
notification = NodeMovingNotification(
id=1, new_node_host="localhost", new_node_port=6379, ttl=10
)
self.handler._processed_notifications.add(notification)
result = self.handler.handle_node_moving_notification(notification)
assert result is None
def test_handle_node_moving_notification_success(self):
"""Test successful node moving notification handling."""
notification = NodeMovingNotification(
id=1, new_node_host="localhost", new_node_port=6379, ttl=10
)
with (
patch("threading.Timer") as mock_timer,
patch("time.monotonic", return_value=1000),
):
self.handler.handle_node_moving_notification(notification)
# Verify timer was started
mock_timer.assert_called_once_with(
notification.ttl,
self.handler.handle_node_moved_notification,
args=(notification,),
)
mock_timer.return_value.start.assert_called_once()
# Verify notification was added to processed set
assert notification in self.handler._processed_notifications
# Verify pool methods were called
self.mock_pool.update_connections_settings.assert_called_once()
def test_handle_node_moving_notification_with_no_host_and_port(self):
"""Test successful node moving notification handling."""
notification = NodeMovingNotification(
id=1, new_node_host=None, new_node_port=None, ttl=2
)
with (
patch("threading.Timer") as mock_timer,
patch("time.monotonic", return_value=1000),
):
self.handler.handle_node_moving_notification(notification)
# Verify timer was started
mock_timer.assert_has_calls(
[
call(
notification.ttl / 2,
self.handler.run_proactive_reconnect,
args=(None,),
),
call().start(),
call(
notification.ttl,
self.handler.handle_node_moved_notification,
args=(notification,),
),
call().start(),
]
)
# Verify notification was added to processed set
assert notification in self.handler._processed_notifications
# Verify pool methods were called
self.mock_pool.update_connections_settings.assert_called_once()
def test_handle_node_moved_notification(self):
"""Test handling of node moved notification (cleanup)."""
notification = NodeMovingNotification(
id=1, new_node_host="localhost", new_node_port=6379, ttl=10
)
self.mock_pool.connection_kwargs = {"host": "localhost"}
self.handler.handle_node_moved_notification(notification)
# Verify cleanup methods were called
self.mock_pool.update_connections_settings.assert_called_once()
| TestMaintNotificationsPoolHandler |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 398755,
"end": 420118
} | class ____(Request):
"""
Validate task properties (before create)
:param name: Task name. Unique within the company.
:type name: str
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tags: System tags list. This field is reserved for system use,
please don't use it.
:type system_tags: Sequence[str]
:param type: Type of task
:type type: TaskTypeEnum
:param comment: Free text comment
:type comment: str
:param parent: Parent task id Must be a completed task.
:type parent: str
:param project: Project ID of the project to which this task is assigned Must
exist[ab]
:type project: str
:param output_dest: Output storage id Must be a reference to an existing
storage.
:type output_dest: str
:param execution: Task execution params
:type execution: Execution
:param script: Script info
:type script: Script
:param hyperparams: Task hyper params per section
:type hyperparams: dict
:param configuration: Task configuration params
:type configuration: dict
:param models: Task models
:type models: TaskModels
:param container: Docker container parameters
:type container: dict
"""
_service = "tasks"
_action = "validate"
_version = "2.13"
_schema = {
"definitions": {
"artifact": {
"properties": {
"content_size": {
"description": "Raw data length in bytes",
"type": "integer",
},
"display_data": {
"description": "User-defined list of key/value pairs, sorted",
"items": {"items": {"type": "string"}, "type": "array"},
"type": "array",
},
"hash": {
"description": "Hash of entire raw data",
"type": "string",
},
"key": {"description": "Entry key", "type": "string"},
"mode": {
"$ref": "#/definitions/artifact_mode_enum",
"description": "System defined input/output indication",
},
"timestamp": {
"description": "Epoch time when artifact was created",
"type": "integer",
},
"type": {"description": "System defined type", "type": "string"},
"type_data": {
"$ref": "#/definitions/artifact_type_data",
"description": "Additional fields defined by the system",
},
"uri": {"description": "Raw data location", "type": "string"},
},
"required": ["key", "type"],
"type": "object",
},
"artifact_mode_enum": {
"default": "output",
"enum": ["input", "output"],
"type": "string",
},
"artifact_type_data": {
"properties": {
"content_type": {
"description": "System defined raw data content type",
"type": ["string", "null"],
},
"data_hash": {
"description": "Hash of raw data, without any headers or descriptive parts",
"type": ["string", "null"],
},
"preview": {
"description": "Description or textual data",
"type": ["string", "null"],
},
},
"type": "object",
},
"configuration_item": {
"properties": {
"description": {
"description": "The parameter description. Optional",
"type": ["string", "null"],
},
"name": {
"description": "Name of the parameter. Should be unique",
"type": ["string", "null"],
},
"type": {
"description": "Type of the parameter. Optional",
"type": ["string", "null"],
},
"value": {
"description": "Value of the parameter",
"type": ["string", "null"],
},
},
"type": "object",
},
"execution": {
"properties": {
"artifacts": {
"description": "Task artifacts",
"items": {"$ref": "#/definitions/artifact"},
"type": ["array", "null"],
},
"framework": {
"description": "Framework related to the task. Case insensitive. Mandatory for Training tasks. ",
"type": ["string", "null"],
},
"model_desc": {
"additionalProperties": True,
"description": "Json object representing the Model descriptors",
"type": ["object", "null"],
},
"model_labels": {
"additionalProperties": {"type": "integer"},
"description": "Json object representing the ids of the labels in the model.\n The keys are the layers' names and the values are the IDs.\n Not applicable for Register (Import) tasks.\n Mandatory for Training tasks",
"type": ["object", "null"],
},
"parameters": {
"additionalProperties": True,
"description": "Json object containing the Task parameters",
"type": ["object", "null"],
},
"queue": {
"description": "Queue ID where task was queued.",
"type": ["string", "null"],
},
},
"type": "object",
},
"params_item": {
"properties": {
"description": {
"description": "The parameter description. Optional",
"type": ["string", "null"],
},
"name": {
"description": "Name of the parameter. The combination of section and name should be unique",
"type": ["string", "null"],
},
"section": {
"description": "Section that the parameter belongs to",
"type": ["string", "null"],
},
"type": {
"description": "Type of the parameter. Optional",
"type": ["string", "null"],
},
"value": {
"description": "Value of the parameter",
"type": ["string", "null"],
},
},
"type": "object",
},
"script": {
"properties": {
"binary": {
"default": "python",
"description": "Binary to use when running the script",
"type": ["string", "null"],
},
"branch": {
"description": "Repository branch id If not provided and tag not provided, default repository branch is used.",
"type": ["string", "null"],
},
"diff": {
"description": "Uncommitted changes found in the repository when task was run",
"type": ["string", "null"],
},
"entry_point": {
"description": "Path to execute within the repository",
"type": ["string", "null"],
},
"repository": {
"description": "Name of the repository where the script is located",
"type": ["string", "null"],
},
"requirements": {
"description": "A JSON object containing requirements strings by key",
"type": ["object", "null"],
},
"tag": {
"description": "Repository tag",
"type": ["string", "null"],
},
"version_num": {
"description": "Version (changeset) number. Optional (default is head version) Unused if tag is provided.",
"type": ["string", "null"],
},
"working_dir": {
"description": "Path to the folder from which to run the script Default - root folder of repository",
"type": ["string", "null"],
},
},
"type": "object",
},
"section_params": {
"additionalProperties": {"$ref": "#/definitions/params_item"},
"description": "Task section params",
"type": "object",
},
"task_model_item": {
"properties": {
"model": {"description": "The model ID", "type": "string"},
"name": {"description": "The task model name", "type": "string"},
},
"required": ["name", "model"],
"type": "object",
},
"task_models": {
"properties": {
"input": {
"description": "The list of task input models",
"items": {"$ref": "#/definitions/task_model_item"},
"type": ["array", "null"],
},
"output": {
"description": "The list of task output models",
"items": {"$ref": "#/definitions/task_model_item"},
"type": ["array", "null"],
},
},
"type": "object",
},
"task_type_enum": {
"enum": [
"training",
"testing",
"inference",
"data_processing",
"application",
"monitor",
"controller",
"optimizer",
"service",
"qc",
"custom",
],
"type": "string",
},
},
"properties": {
"comment": {"description": "Free text comment ", "type": "string"},
"configuration": {
"additionalProperties": {"$ref": "#/definitions/configuration_item"},
"description": "Task configuration params",
"type": "object",
},
"container": {
"type": "object",
"description": "Docker container parameters",
"additionalProperties": {"type": ["string", "null"]},
},
"execution": {
"$ref": "#/definitions/execution",
"description": "Task execution params",
},
"hyperparams": {
"additionalProperties": {"$ref": "#/definitions/section_params"},
"description": "Task hyper params per section",
"type": "object",
},
"models": {
"$ref": "#/definitions/task_models",
"description": "Task models",
},
"name": {
"description": "Task name. Unique within the company.",
"type": "string",
},
"output_dest": {
"description": "Output storage id Must be a reference to an existing storage.",
"type": "string",
},
"parent": {
"description": "Parent task id Must be a completed task.",
"type": "string",
},
"project": {
"description": "Project ID of the project to which this task is assigned Must exist[ab]",
"type": "string",
},
"script": {"$ref": "#/definitions/script", "description": "Script info"},
"system_tags": {
"description": "System tags list. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": "array",
},
"tags": {
"description": "User-defined tags list",
"items": {"type": "string"},
"type": "array",
},
"type": {
"$ref": "#/definitions/task_type_enum",
"description": "Type of task",
},
},
"required": ["name", "type"],
"type": "object",
}
def __init__(
self,
name: str,
type: Any,
tags: Optional[List[str]] = None,
system_tags: Optional[List[str]] = None,
comment: Optional[str] = None,
parent: Optional[str] = None,
project: Optional[str] = None,
output_dest: Optional[str] = None,
execution: Any = None,
script: Any = None,
hyperparams: Optional[dict] = None,
configuration: Optional[dict] = None,
models: Any = None,
container: Optional[dict] = None,
**kwargs: Any
) -> None:
super(ValidateRequest, self).__init__(**kwargs)
self.name = name
self.tags = tags
self.system_tags = system_tags
self.type = type
self.comment = comment
self.parent = parent
self.project = project
self.output_dest = output_dest
self.execution = execution
self.script = script
self.hyperparams = hyperparams
self.configuration = configuration
self.models = models
self.container = container
@schema_property("name")
def name(self) -> str:
return self._property_name
@name.setter
def name(self, value: str) -> None:
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
@schema_property("tags")
def tags(self) -> Optional[List[str]]:
return self._property_tags
@tags.setter
def tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self) -> Optional[List[str]]:
return self._property_system_tags
@system_tags.setter
def system_tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
@schema_property("type")
def type(self) -> Any:
return self._property_type
@type.setter
def type(self, value: Any) -> None:
if value is None:
self._property_type = None
return
if isinstance(value, six.string_types):
try:
value = TaskTypeEnum(value)
except ValueError:
pass
else:
self.assert_isinstance(value, "type", enum.Enum)
self._property_type = value
@schema_property("comment")
def comment(self) -> Optional[str]:
return self._property_comment
@comment.setter
def comment(self, value: Optional[str]) -> None:
if value is None:
self._property_comment = None
return
self.assert_isinstance(value, "comment", six.string_types)
self._property_comment = value
@schema_property("parent")
def parent(self) -> Optional[str]:
return self._property_parent
@parent.setter
def parent(self, value: Optional[str]) -> None:
if value is None:
self._property_parent = None
return
self.assert_isinstance(value, "parent", six.string_types)
self._property_parent = value
@schema_property("project")
def project(self) -> Optional[str]:
return self._property_project
@project.setter
def project(self, value: Optional[str]) -> None:
if value is None:
self._property_project = None
return
self.assert_isinstance(value, "project", six.string_types)
self._property_project = value
@schema_property("output_dest")
def output_dest(self) -> Optional[str]:
return self._property_output_dest
@output_dest.setter
def output_dest(self, value: Optional[str]) -> None:
if value is None:
self._property_output_dest = None
return
self.assert_isinstance(value, "output_dest", six.string_types)
self._property_output_dest = value
@schema_property("execution")
def execution(self) -> Any:
return self._property_execution
@execution.setter
def execution(self, value: Any) -> None:
if value is None:
self._property_execution = None
return
if isinstance(value, dict):
value = Execution.from_dict(value)
else:
self.assert_isinstance(value, "execution", Execution)
self._property_execution = value
@schema_property("hyperparams")
def hyperparams(self) -> Optional[dict]:
return self._property_hyperparams
@hyperparams.setter
def hyperparams(self, value: Optional[dict]) -> None:
if value is None:
self._property_hyperparams = None
return
self.assert_isinstance(value, "hyperparams", dict)
self.assert_isinstance(value.keys(), "hyperparams_keys", six.string_types, is_array=True)
self.assert_isinstance(value.values(), "hyperparams_values", (SectionParams, dict), is_array=True)
value = dict(((k, SectionParams(**v) if isinstance(v, dict) else v) for (k, v) in value.items()))
self._property_hyperparams = value
@schema_property("configuration")
def configuration(self) -> Optional[dict]:
return self._property_configuration
@configuration.setter
def configuration(self, value: Optional[dict]) -> None:
if value is None:
self._property_configuration = None
return
self.assert_isinstance(value, "configuration", dict)
self.assert_isinstance(value.keys(), "configuration_keys", six.string_types, is_array=True)
self.assert_isinstance(
value.values(),
"configuration_values",
(ConfigurationItem, dict),
is_array=True,
)
value = dict(((k, ConfigurationItem(**v) if isinstance(v, dict) else v) for (k, v) in value.items()))
self._property_configuration = value
@schema_property("script")
def script(self) -> Any:
return self._property_script
@script.setter
def script(self, value: Any) -> None:
if value is None:
self._property_script = None
return
if isinstance(value, dict):
value = Script.from_dict(value)
else:
self.assert_isinstance(value, "script", Script)
self._property_script = value
@schema_property("models")
def models(self) -> Any:
return self._property_models
@models.setter
def models(self, value: Any) -> None:
if value is None:
self._property_models = None
return
if isinstance(value, dict):
value = TaskModels.from_dict(value)
else:
self.assert_isinstance(value, "models", TaskModels)
self._property_models = value
@schema_property("container")
def container(self) -> Optional[dict]:
return self._property_container
@container.setter
def container(self, value: Optional[dict]) -> None:
if value is None:
self._property_container = None
return
self.assert_isinstance(value, "container", dict)
self._property_container = value
| ValidateRequest |
python | ray-project__ray | rllib/examples/envs/classes/mock_env.py | {
"start": 2709,
"end": 4447
} | class ____(VectorEnv):
"""Vectorized version of the MockEnv.
Contains `num_envs` MockEnv instances, each one having its own
`episode_length` horizon.
"""
def __init__(self, episode_length, num_envs):
super().__init__(
observation_space=gym.spaces.Discrete(1),
action_space=gym.spaces.Discrete(2),
num_envs=num_envs,
)
self.envs = [MockEnv(episode_length) for _ in range(num_envs)]
@override(VectorEnv)
def vector_reset(self, *, seeds=None, options=None):
seeds = seeds or [None] * self.num_envs
options = options or [None] * self.num_envs
obs_and_infos = [
e.reset(seed=seeds[i], options=options[i]) for i, e in enumerate(self.envs)
]
return [oi[0] for oi in obs_and_infos], [oi[1] for oi in obs_and_infos]
@override(VectorEnv)
def reset_at(self, index, *, seed=None, options=None):
return self.envs[index].reset(seed=seed, options=options)
@override(VectorEnv)
def vector_step(self, actions):
obs_batch, rew_batch, terminated_batch, truncated_batch, info_batch = (
[],
[],
[],
[],
[],
)
for i in range(len(self.envs)):
obs, rew, terminated, truncated, info = self.envs[i].step(actions[i])
obs_batch.append(obs)
rew_batch.append(rew)
terminated_batch.append(terminated)
truncated_batch.append(truncated)
info_batch.append(info)
return obs_batch, rew_batch, terminated_batch, truncated_batch, info_batch
@override(VectorEnv)
def get_sub_environments(self):
return self.envs
| VectorizedMockEnv |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_tasks.py | {
"start": 11753,
"end": 22984
} | class ____(TestTaskEndpoint):
def test_should_respond_200(self, test_client):
expected = {
"tasks": [
{
"class_ref": {
"class_name": "EmptyOperator",
"module_path": "airflow.providers.standard.operators.empty",
},
"depends_on_past": False,
"downstream_task_ids": [self.task_id2],
"end_date": None,
"execution_timeout": None,
"extra_links": [],
"operator_name": "EmptyOperator",
"owner": "airflow",
"params": {
"foo": {
"value": "bar",
"schema": {},
"description": None,
"source": "task",
}
},
"pool": "default_pool",
"pool_slots": 1.0,
"priority_weight": 1.0,
"queue": "default",
"retries": 0.0,
"retry_delay": {"__type": "TimeDelta", "days": 0, "seconds": 300, "microseconds": 0},
"retry_exponential_backoff": 0,
"start_date": "2020-06-15T00:00:00Z",
"task_id": "op1",
"task_display_name": "op1",
"template_fields": [],
"trigger_rule": "all_success",
"ui_color": "#e8f7e4",
"ui_fgcolor": "#000",
"wait_for_downstream": False,
"weight_rule": "downstream",
"is_mapped": False,
"doc_md": None,
},
{
"class_ref": {
"class_name": "EmptyOperator",
"module_path": "airflow.providers.standard.operators.empty",
},
"depends_on_past": False,
"downstream_task_ids": [],
"end_date": None,
"execution_timeout": None,
"extra_links": [],
"operator_name": "EmptyOperator",
"owner": "airflow",
"params": {},
"pool": "default_pool",
"pool_slots": 1.0,
"priority_weight": 1.0,
"queue": "default",
"retries": 0.0,
"retry_delay": {"__type": "TimeDelta", "days": 0, "seconds": 300, "microseconds": 0},
"retry_exponential_backoff": 0,
"start_date": "2020-06-16T00:00:00Z",
"task_id": self.task_id2,
"task_display_name": self.task_id2,
"template_fields": [],
"trigger_rule": "all_success",
"ui_color": "#e8f7e4",
"ui_fgcolor": "#000",
"wait_for_downstream": False,
"weight_rule": "downstream",
"is_mapped": False,
"doc_md": None,
},
],
"total_entries": 2,
}
with assert_queries_count(2):
response = test_client.get(f"{self.api_prefix}/{self.dag_id}/tasks")
assert response.status_code == 200
assert response.json() == expected
def test_get_tasks_mapped(self, test_client):
expected = {
"tasks": [
{
"class_ref": {
"class_name": "EmptyOperator",
"module_path": "airflow.providers.standard.operators.empty",
},
"depends_on_past": False,
"downstream_task_ids": [],
"end_date": None,
"execution_timeout": None,
"extra_links": [],
"is_mapped": True,
"operator_name": "EmptyOperator",
"owner": "airflow",
"params": {},
"pool": "default_pool",
"pool_slots": 1.0,
"priority_weight": 1.0,
"queue": "default",
"retries": 0.0,
"retry_delay": {"__type": "TimeDelta", "days": 0, "microseconds": 0, "seconds": 300},
"retry_exponential_backoff": 0,
"start_date": "2020-06-15T00:00:00Z",
"task_id": "mapped_task",
"task_display_name": "mapped_task",
"template_fields": [],
"trigger_rule": "all_success",
"ui_color": "#e8f7e4",
"ui_fgcolor": "#000",
"wait_for_downstream": False,
"weight_rule": "downstream",
"doc_md": None,
},
{
"class_ref": {
"class_name": "EmptyOperator",
"module_path": "airflow.providers.standard.operators.empty",
},
"depends_on_past": False,
"downstream_task_ids": [],
"end_date": None,
"execution_timeout": None,
"extra_links": [],
"operator_name": "EmptyOperator",
"owner": "airflow",
"params": {},
"pool": "default_pool",
"pool_slots": 1.0,
"priority_weight": 1.0,
"queue": "default",
"retries": 0.0,
"retry_delay": {"__type": "TimeDelta", "days": 0, "seconds": 300, "microseconds": 0},
"retry_exponential_backoff": 0,
"start_date": "2020-06-15T00:00:00Z",
"task_id": self.task_id3,
"task_display_name": self.task_id3,
"template_fields": [],
"trigger_rule": "all_success",
"ui_color": "#e8f7e4",
"ui_fgcolor": "#000",
"wait_for_downstream": False,
"weight_rule": "downstream",
"is_mapped": False,
"doc_md": None,
},
],
"total_entries": 2,
}
with assert_queries_count(2):
response = test_client.get(f"{self.api_prefix}/{self.mapped_dag_id}/tasks")
assert response.status_code == 200
assert response.json() == expected
def test_get_unscheduled_tasks(self, test_client):
downstream_dict = {
self.unscheduled_task_id1: self.unscheduled_task_id2,
self.unscheduled_task_id2: None,
}
expected = {
"tasks": [
{
"class_ref": {
"class_name": "EmptyOperator",
"module_path": "airflow.providers.standard.operators.empty",
},
"depends_on_past": False,
"downstream_task_ids": [downstream_task_id] if downstream_task_id else [],
"end_date": None,
"execution_timeout": None,
"extra_links": [],
"operator_name": "EmptyOperator",
"owner": "airflow",
"params": {
"is_unscheduled": {
"value": True,
"schema": {},
"description": None,
"source": "task",
}
},
"pool": "default_pool",
"pool_slots": 1.0,
"priority_weight": 1.0,
"queue": "default",
"retries": 0.0,
"retry_delay": {"__type": "TimeDelta", "days": 0, "seconds": 300, "microseconds": 0},
"retry_exponential_backoff": 0,
"start_date": None,
"task_id": task_id,
"task_display_name": task_id,
"template_fields": [],
"trigger_rule": "all_success",
"ui_color": "#e8f7e4",
"ui_fgcolor": "#000",
"wait_for_downstream": False,
"weight_rule": "downstream",
"is_mapped": False,
"doc_md": None,
}
for (task_id, downstream_task_id) in downstream_dict.items()
],
"total_entries": len(downstream_dict),
}
with assert_queries_count(2):
response = test_client.get(f"{self.api_prefix}/{self.unscheduled_dag_id}/tasks")
assert response.status_code == 200
assert response.json() == expected
def test_should_respond_200_ascending_order_by_start_date(self, test_client):
with assert_queries_count(2):
response = test_client.get(
f"{self.api_prefix}/{self.dag_id}/tasks?order_by=start_date",
)
assert response.status_code == 200
assert self.task1_start_date < self.task2_start_date
assert response.json()["tasks"][0]["task_id"] == self.task_id
assert response.json()["tasks"][1]["task_id"] == self.task_id2
def test_should_respond_200_descending_order_by_start_date(self, test_client):
with assert_queries_count(2):
response = test_client.get(
f"{self.api_prefix}/{self.dag_id}/tasks?order_by=-start_date",
)
assert response.status_code == 200
# - means is descending
assert self.task1_start_date < self.task2_start_date
assert response.json()["tasks"][0]["task_id"] == self.task_id2
assert response.json()["tasks"][1]["task_id"] == self.task_id
def test_should_raise_400_for_invalid_order_by_name(self, test_client):
response = test_client.get(
f"{self.api_prefix}/{self.dag_id}/tasks?order_by=invalid_task_colume_name",
)
assert response.status_code == 400
assert (
response.json()["detail"] == "'EmptyOperator' object has no attribute 'invalid_task_colume_name'"
)
def test_should_respond_404(self, test_client):
dag_id = "xxxx_not_existing"
response = test_client.get(f"{self.api_prefix}/{dag_id}/tasks")
assert response.status_code == 404
def test_should_respond_401(self, unauthenticated_test_client):
response = unauthenticated_test_client.get(f"{self.api_prefix}/{self.dag_id}/tasks")
assert response.status_code == 401
def test_should_respond_403(self, unauthorized_test_client):
response = unauthorized_test_client.get(f"{self.api_prefix}/{self.dag_id}/tasks")
assert response.status_code == 403
| TestGetTasks |
python | plotly__plotly.py | tests/test_core/test_update_objects/test_update_subplots.py | {
"start": 155,
"end": 17706
} | class ____(TestCase):
def setUp(self):
fig = make_subplots(
rows=3,
cols=3,
specs=[
[{}, {"type": "scene"}, {}],
[{"secondary_y": True}, {"type": "polar"}, {"type": "polar"}],
[{"type": "xy", "colspan": 2}, None, {"type": "ternary"}],
],
).update(layout={"height": 800})
fig.layout.xaxis.title.text = "A"
fig.layout.xaxis2.title.text = "A"
fig.layout.xaxis3.title.text = "B"
fig.layout.xaxis4.title.text = "B"
fig.layout.yaxis.title.text = "A"
fig.layout.yaxis2.title.text = "B"
fig.layout.yaxis3.title.text = "A"
fig.layout.yaxis4.title.text = "B"
fig.layout.polar.angularaxis.rotation = 45
fig.layout.polar2.angularaxis.rotation = 45
fig.layout.polar.radialaxis.title.text = "A"
fig.layout.polar2.radialaxis.title.text = "B"
fig.layout.scene.xaxis.title.text = "A"
fig.layout.scene.yaxis.title.text = "B"
fig.layout.ternary.aaxis.title.text = "A"
self.fig = fig
self.fig_no_grid = go.Figure(self.fig.to_dict())
def assert_select_subplots(
self,
subplot_type,
subplots_name,
expected_nums,
selector=None,
row=None,
col=None,
secondary_y=None,
test_no_grid=False,
):
select_fn = getattr(Figure, "select_" + subplots_name)
for_each_fn = getattr(Figure, "for_each_" + subplot_type)
if secondary_y is not None:
sec_y_args = dict(secondary_y=secondary_y)
else:
sec_y_args = {}
def check_select(fig):
# Check select_*
subplots = list(
select_fn(fig, selector=selector, row=row, col=col, **sec_y_args)
)
expected_keys = [
subplot_type + (str(cnt) if cnt > 1 else "") for cnt in expected_nums
]
self.assertEqual(len(subplots), len(expected_keys))
self.assertTrue(
all(v1 is fig.layout[k] for v1, k in zip(subplots, expected_keys))
)
# Check for_each_*
subplots = []
res = for_each_fn(
fig,
lambda obj: subplots.append(obj),
selector=selector,
row=row,
col=col,
**sec_y_args,
)
self.assertIs(res, fig)
self.assertEqual(len(subplots), len(expected_keys))
self.assertTrue(
all(v1 is fig.layout[k] for v1, k in zip(subplots, expected_keys))
)
check_select(self.fig)
if test_no_grid:
check_select(self.fig_no_grid)
def test_select_by_type(self):
self.assert_select_subplots("xaxis", "xaxes", [1, 2, 3, 4], test_no_grid=True)
self.assert_select_subplots(
"yaxis", "yaxes", [1, 2, 3, 4, 5], test_no_grid=True
)
self.assert_select_subplots("scene", "scenes", [1], test_no_grid=True)
self.assert_select_subplots("polar", "polars", [1, 2], test_no_grid=True)
self.assert_select_subplots("ternary", "ternaries", [1], test_no_grid=True)
# No 'geo' or 'mapbox' subplots initialized, but the first subplot
# object is always present
self.assert_select_subplots("geo", "geos", [1], test_no_grid=True)
self.assert_select_subplots("mapbox", "mapboxes", [1], test_no_grid=True)
def test_select_by_type_and_grid(self):
self.assert_select_subplots("xaxis", "xaxes", [1, 2], row=1)
self.assert_select_subplots("xaxis", "xaxes", [1, 3, 4], col=1)
self.assert_select_subplots("xaxis", "xaxes", [2], col=3)
self.assert_select_subplots("xaxis", "xaxes", [4], row=3, col=1)
self.assert_select_subplots("xaxis", "xaxes", [], row=2, col=2)
def test_select_by_secondary_y(self):
self.assert_select_subplots("yaxis", "yaxes", [4], secondary_y=True)
self.assert_select_subplots("yaxis", "yaxes", [1, 2, 3, 5], secondary_y=False)
self.assert_select_subplots("yaxis", "yaxes", [4], col=1, secondary_y=True)
self.assert_select_subplots("yaxis", "yaxes", [], col=3, secondary_y=True)
def test_select_by_type_and_selector(self):
# xaxis
self.assert_select_subplots(
"xaxis", "xaxes", [1, 2], selector={"title.text": "A"}, test_no_grid=True
)
self.assert_select_subplots(
"xaxis", "xaxes", [3, 4], selector={"title.text": "B"}, test_no_grid=True
)
self.assert_select_subplots(
"xaxis", "xaxes", [], selector={"title.text": "C"}, test_no_grid=True
)
self.assert_select_subplots(
"xaxis", "xaxes", [4], selector=-1, test_no_grid=True
)
# yaxis
self.assert_select_subplots(
"yaxis", "yaxes", [1, 3], selector={"title.text": "A"}, test_no_grid=True
)
self.assert_select_subplots(
"yaxis", "yaxes", [2, 4], selector={"title.text": "B"}, test_no_grid=True
)
self.assert_select_subplots(
"yaxis", "yaxes", [], selector={"title.text": "C"}, test_no_grid=True
)
self.assert_select_subplots(
"yaxis", "yaxes", [5], selector=-1, test_no_grid=True
)
self.assert_select_subplots(
"yaxis", "yaxes", [2], selector=1, test_no_grid=True
)
# scene
self.assert_select_subplots(
"scene",
"scenes",
[1],
selector={"xaxis.title.text": "A"},
test_no_grid=True,
)
self.assert_select_subplots(
"scene",
"scenes",
[1],
selector={"xaxis.title.text": "A", "yaxis.title.text": "B"},
test_no_grid=True,
)
self.assert_select_subplots(
"scene",
"scenes",
[],
selector={"xaxis.title.text": "A", "yaxis.title.text": "C"},
test_no_grid=True,
)
self.assert_select_subplots(
"scene", "scenes", [1], selector=0, test_no_grid=True
)
# polar
self.assert_select_subplots(
"polar",
"polars",
[1, 2],
selector={"angularaxis.rotation": 45},
test_no_grid=True,
)
self.assert_select_subplots(
"polar",
"polars",
[2],
selector={"angularaxis.rotation": 45, "radialaxis_title_text": "B"},
test_no_grid=True,
)
self.assert_select_subplots(
"polar",
"polars",
[],
selector={"angularaxis.rotation": 45, "radialaxis_title_text": "C"},
test_no_grid=True,
)
self.assert_select_subplots(
"polar", "polars", [2], selector=-1, test_no_grid=True
)
# ternary
self.assert_select_subplots(
"ternary",
"ternaries",
[1],
selector={"aaxis.title.text": "A"},
test_no_grid=True,
)
self.assert_select_subplots(
"ternary",
"ternaries",
[],
selector={"aaxis.title.text": "C"},
test_no_grid=True,
)
self.assert_select_subplots(
"ternary",
"ternaries",
[],
selector={"aaxis.bogus.text": "A"},
test_no_grid=True,
)
self.assert_select_subplots(
"ternary", "ternaries", [1], selector=-1, test_no_grid=True
)
# No 'geo' or 'mapbox' subplots initialized, but the first subplot
# object is always present
self.assert_select_subplots(
"geo", "geos", [], selector={"bgcolor": "blue"}, test_no_grid=True
)
self.assert_select_subplots(
"geo", "geos", [], selector={"bogus": "blue"}, test_no_grid=True
)
self.assert_select_subplots(
"mapbox", "mapboxes", [], selector={"pitch": 45}, test_no_grid=True
)
def test_select_by_type_and_grid_and_selector(self):
# xaxis
self.assert_select_subplots(
"xaxis", "xaxes", [1, 2], row=1, selector={"title.text": "A"}
)
self.assert_select_subplots(
"xaxis", "xaxes", [1], col=1, selector={"title.text": "A"}
)
self.assert_select_subplots(
"xaxis", "xaxes", [], col=2, selector={"title.text": "A"}
)
self.assert_select_subplots(
"xaxis", "xaxes", [3, 4], col=1, selector={"title.text": "B"}
)
self.assert_select_subplots("xaxis", "xaxes", [4], col=1, selector=-1)
self.assert_select_subplots(
"xaxis", "xaxes", [3], row=2, selector={"title.text": "B"}
)
self.assert_select_subplots(
"xaxis", "xaxes", [4], row=3, col=1, selector={"title.text": "B"}
)
# yaxis
self.assert_select_subplots(
"yaxis", "yaxes", [1, 3], col=1, selector={"title.text": "A"}
)
self.assert_select_subplots("yaxis", "yaxes", [5], col=1, selector=-1)
self.assert_select_subplots("yaxis", "yaxes", [1], col=1, selector=0)
self.assert_select_subplots(
"yaxis", "yaxes", [4], col=1, selector={"title.text": "B"}
)
# polar
self.assert_select_subplots(
"polar", "polars", [1, 2], row=2, selector={"angularaxis.rotation": 45}
)
self.assert_select_subplots("polar", "polars", [2], row=2, selector=-1)
self.assert_select_subplots(
"polar", "polars", [1], col=2, selector={"angularaxis.rotation": 45}
)
self.assert_select_subplots(
"polar", "polars", [2], row=2, col=3, selector={"angularaxis.rotation": 45}
)
self.assert_select_subplots(
"polar", "polars", [], row=2, col=3, selector={"angularaxis.rotation": 0}
)
def assert_update_subplots(
self,
subplot_type,
subplots_name,
expected_nums,
patch=None,
selector=None,
row=None,
col=None,
secondary_y=None,
test_no_grid=False,
**kwargs,
):
update_fn = getattr(Figure, "update_" + subplots_name)
if secondary_y is not None:
secy_kwargs = dict(secondary_y=secondary_y)
else:
secy_kwargs = {}
def check_update(fig):
# Copy input figure so that we don't modify it
fig_orig = fig
fig = copy.deepcopy(fig)
# perform update_*
update_res = update_fn(
fig,
patch,
selector=selector,
row=row,
col=col,
**dict(kwargs, **secy_kwargs),
)
self.assertIs(update_res, fig)
# Build expected layout keys
expected_keys = [
subplot_type + (str(cnt) if cnt > 1 else "") for cnt in expected_nums
]
# Iterate over all layout keys
for k in fig.layout:
orig_obj = copy.deepcopy(fig_orig.layout[k])
new_obj = fig.layout[k]
if k in expected_keys:
# Make sure sure there is an initial difference
self.assertNotEqual(orig_obj, new_obj)
orig_obj.update(patch, **kwargs)
self.assertEqual(new_obj, orig_obj)
check_update(self.fig)
if test_no_grid:
check_update(self.fig_no_grid)
def test_update_by_type(self):
self.assert_update_subplots(
"xaxis",
"xaxes",
[1, 2, 3, 4],
{"title.font.family": "Rockwell"},
test_no_grid=True,
)
self.assert_update_subplots(
"yaxis", "yaxes", [1, 2, 3, 4, 5], {"range": [5, 10]}, test_no_grid=True
)
self.assert_update_subplots(
"scene", "scenes", [1], {"zaxis.title.text": "Z-AXIS"}, test_no_grid=True
)
self.assert_update_subplots(
"polar", "polars", [1, 2], {"angularaxis.rotation": 15}, test_no_grid=True
)
self.assert_update_subplots(
"ternary",
"ternaries",
[1],
{"aaxis.title.font.family": "Rockwell"},
test_no_grid=True,
)
# No 'geo' or 'mapbox' subplots initialized, but the first subplot
# object is always present
self.assert_update_subplots(
"geo", "geos", [1], {"bgcolor": "purple"}, test_no_grid=True
)
self.assert_update_subplots(
"mapbox", "mapboxes", [1], {"pitch": 99}, test_no_grid=True
)
def test_update_by_type_and_grid(self):
self.assert_update_subplots(
"xaxis", "xaxes", [1, 3, 4], {"title.font.family": "Rockwell"}, col=1
)
self.assert_update_subplots(
"xaxis", "xaxes", [1, 2], {"title.font.family": "Rockwell"}, row=1
)
self.assert_update_subplots(
"xaxis", "xaxes", [1], {"title.font.family": "Rockwell"}, row=1, col=1
)
self.assert_update_subplots(
"polar", "polars", [1, 2], {"angularaxis.rotation": 15}, row=2
)
self.assert_update_subplots(
"polar", "polars", [1], {"angularaxis.rotation": 15}, col=2
)
self.assert_update_subplots(
"polar", "polars", [2], {"angularaxis.rotation": 15}, row=2, col=3
)
def test_update_by_secondary_y(self):
self.assert_update_subplots(
"yaxis", "yaxes", [4], {"range": [5, 10]}, secondary_y=True
)
self.assert_update_subplots(
"yaxis", "yaxes", [1, 2, 3, 5], {"range": [5, 10]}, secondary_y=False
)
def test_update_by_type_and_grid_and_selector(self):
# xaxis
self.assert_update_subplots(
"xaxis",
"xaxes",
[1, 2],
{"title.font.family": "Rockwell"},
row=1,
selector={"title.text": "A"},
)
self.assert_update_subplots(
"xaxis",
"xaxes",
[1],
{"title.font.family": "Rockwell"},
col=1,
selector={"title.text": "A"},
)
self.assert_update_subplots(
"xaxis",
"xaxes",
[],
{"title.font.family": "Rockwell"},
col=2,
selector={"title.text": "A"},
)
self.assert_update_subplots(
"xaxis",
"xaxes",
[3, 4],
{"title.font.family": "Rockwell"},
col=1,
selector={"title.text": "B"},
)
self.assert_update_subplots(
"xaxis",
"xaxes",
[3],
{"title.font.family": "Rockwell"},
row=2,
selector={"title.text": "B"},
)
self.assert_update_subplots(
"xaxis",
"xaxes",
[4],
{"title.font.family": "Rockwell"},
row=3,
col=1,
selector={"title.text": "B"},
)
# yaxis
self.assert_update_subplots(
"yaxis",
"yaxes",
[1, 3],
{"title.font.family": "Rockwell"},
col=1,
selector={"title.text": "A"},
)
self.assert_update_subplots(
"yaxis",
"yaxes",
[4],
{"title.font.family": "Rockwell"},
col=1,
selector={"title.text": "B"},
)
# polar
self.assert_update_subplots(
"polar",
"polars",
[1, 2],
{"radialaxis.title.font.family": "Rockwell"},
row=2,
selector={"angularaxis.rotation": 45},
)
self.assert_update_subplots(
"polar",
"polars",
[1],
{"radialaxis.title.font.family": "Rockwell"},
col=2,
selector={"angularaxis.rotation": 45},
)
self.assert_update_subplots(
"polar",
"polars",
[2],
{"radialaxis.title.font.family": "Rockwell"},
row=2,
col=3,
selector={"angularaxis.rotation": 45},
)
self.assert_update_subplots(
"polar",
"polars",
[],
{"radialaxis.title.font.family": "Rockwell"},
row=2,
col=3,
selector={"angularaxis.rotation": 0},
)
# kwargs
self.assert_update_subplots(
"xaxis",
"xaxes",
[1, 2],
title_font_family="Courier",
title_font_color="yellow",
row=1,
selector={"title.text": "A"},
)
def test_update_subplot_overwrite(self):
fig = go.Figure(layout_xaxis_title_text="Axis title")
fig.update_xaxes(overwrite=True, title={"font": {"family": "Courier"}})
self.assertEqual(
fig.layout.xaxis.to_plotly_json(),
{"title": {"font": {"family": "Courier"}}},
)
| TestSelectForEachUpdateSubplots |
python | psf__black | src/black/trans.py | {
"start": 87598,
"end": 95162
} | class ____:
"""
A state machine that aids in parsing a string's "trailer", which can be
either non-existent, an old-style formatting sequence (e.g. `% varX` or `%
(varX, varY)`), or a method-call / attribute access (e.g. `.format(varX,
varY)`).
NOTE: A new StringParser object MUST be instantiated for each string
trailer we need to parse.
Examples:
We shall assume that `line` equals the `Line` object that corresponds
to the following line of python code:
```
x = "Some {}.".format("String") + some_other_string
```
Furthermore, we will assume that `string_idx` is some index such that:
```
assert line.leaves[string_idx].value == "Some {}."
```
The following code snippet then holds:
```
string_parser = StringParser()
idx = string_parser.parse(line.leaves, string_idx)
assert line.leaves[idx].type == token.PLUS
```
"""
DEFAULT_TOKEN: Final = 20210605
# String Parser States
START: Final = 1
DOT: Final = 2
NAME: Final = 3
PERCENT: Final = 4
SINGLE_FMT_ARG: Final = 5
LPAR: Final = 6
RPAR: Final = 7
DONE: Final = 8
# Lookup Table for Next State
_goto: Final[dict[tuple[ParserState, NodeType], ParserState]] = {
# A string trailer may start with '.' OR '%'.
(START, token.DOT): DOT,
(START, token.PERCENT): PERCENT,
(START, DEFAULT_TOKEN): DONE,
# A '.' MUST be followed by an attribute or method name.
(DOT, token.NAME): NAME,
# A method name MUST be followed by an '(', whereas an attribute name
# is the last symbol in the string trailer.
(NAME, token.LPAR): LPAR,
(NAME, DEFAULT_TOKEN): DONE,
# A '%' symbol can be followed by an '(' or a single argument (e.g. a
# string or variable name).
(PERCENT, token.LPAR): LPAR,
(PERCENT, DEFAULT_TOKEN): SINGLE_FMT_ARG,
# If a '%' symbol is followed by a single argument, that argument is
# the last leaf in the string trailer.
(SINGLE_FMT_ARG, DEFAULT_TOKEN): DONE,
# If present, a ')' symbol is the last symbol in a string trailer.
# (NOTE: LPARS and nested RPARS are not included in this lookup table,
# since they are treated as a special case by the parsing logic in this
# classes' implementation.)
(RPAR, DEFAULT_TOKEN): DONE,
}
def __init__(self) -> None:
self._state = self.START
self._unmatched_lpars = 0
def parse(self, leaves: list[Leaf], string_idx: int) -> int:
"""
Pre-conditions:
* @leaves[@string_idx].type == token.STRING
Returns:
The index directly after the last leaf which is a part of the string
trailer, if a "trailer" exists.
OR
@string_idx + 1, if no string "trailer" exists.
"""
assert leaves[string_idx].type == token.STRING
idx = string_idx + 1
while idx < len(leaves) and self._next_state(leaves[idx]):
idx += 1
return idx
def _next_state(self, leaf: Leaf) -> bool:
"""
Pre-conditions:
* On the first call to this function, @leaf MUST be the leaf that
was directly after the string leaf in question (e.g. if our target
string is `line.leaves[i]` then the first call to this method must
be `line.leaves[i + 1]`).
* On the next call to this function, the leaf parameter passed in
MUST be the leaf directly following @leaf.
Returns:
True iff @leaf is a part of the string's trailer.
"""
# We ignore empty LPAR or RPAR leaves.
if is_empty_par(leaf):
return True
next_token = leaf.type
if next_token == token.LPAR:
self._unmatched_lpars += 1
current_state = self._state
# The LPAR parser state is a special case. We will return True until we
# find the matching RPAR token.
if current_state == self.LPAR:
if next_token == token.RPAR:
self._unmatched_lpars -= 1
if self._unmatched_lpars == 0:
self._state = self.RPAR
# Otherwise, we use a lookup table to determine the next state.
else:
# If the lookup table matches the current state to the next
# token, we use the lookup table.
if (current_state, next_token) in self._goto:
self._state = self._goto[current_state, next_token]
else:
# Otherwise, we check if a the current state was assigned a
# default.
if (current_state, self.DEFAULT_TOKEN) in self._goto:
self._state = self._goto[current_state, self.DEFAULT_TOKEN]
# If no default has been assigned, then this parser has a logic
# error.
else:
raise RuntimeError(f"{self.__class__.__name__} LOGIC ERROR!")
if self._state == self.DONE:
return False
return True
def insert_str_child_factory(string_leaf: Leaf) -> Callable[[LN], None]:
"""
Factory for a convenience function that is used to orphan @string_leaf
and then insert multiple new leaves into the same part of the node
structure that @string_leaf had originally occupied.
Examples:
Let `string_leaf = Leaf(token.STRING, '"foo"')` and `N =
string_leaf.parent`. Assume the node `N` has the following
original structure:
Node(
expr_stmt, [
Leaf(NAME, 'x'),
Leaf(EQUAL, '='),
Leaf(STRING, '"foo"'),
]
)
We then run the code snippet shown below.
```
insert_str_child = insert_str_child_factory(string_leaf)
lpar = Leaf(token.LPAR, '(')
insert_str_child(lpar)
bar = Leaf(token.STRING, '"bar"')
insert_str_child(bar)
rpar = Leaf(token.RPAR, ')')
insert_str_child(rpar)
```
After which point, it follows that `string_leaf.parent is None` and
the node `N` now has the following structure:
Node(
expr_stmt, [
Leaf(NAME, 'x'),
Leaf(EQUAL, '='),
Leaf(LPAR, '('),
Leaf(STRING, '"bar"'),
Leaf(RPAR, ')'),
]
)
"""
string_parent = string_leaf.parent
string_child_idx = string_leaf.remove()
def insert_str_child(child: LN) -> None:
nonlocal string_child_idx
assert string_parent is not None
assert string_child_idx is not None
string_parent.insert_child(string_child_idx, child)
string_child_idx += 1
return insert_str_child
def is_valid_index_factory(seq: Sequence[Any]) -> Callable[[int], bool]:
"""
Examples:
```
my_list = [1, 2, 3]
is_valid_index = is_valid_index_factory(my_list)
assert is_valid_index(0)
assert is_valid_index(2)
assert not is_valid_index(3)
assert not is_valid_index(-1)
```
"""
def is_valid_index(idx: int) -> bool:
"""
Returns:
True iff @idx is positive AND seq[@idx] does NOT raise an
IndexError.
"""
return 0 <= idx < len(seq)
return is_valid_index
| StringParser |
python | simonw__datasette | datasette/utils/__init__.py | {
"start": 25734,
"end": 26446
} | class ____(OrderedDict):
# Loose imitation of sqlite3.Row which offers
# both index-based AND key-based lookups
def __init__(self, columns, values=None):
self.columns = columns
if values:
self.update(values)
def __getitem__(self, key):
if isinstance(key, int):
return super().__getitem__(self.columns[key])
else:
return super().__getitem__(key)
def __iter__(self):
for column in self.columns:
yield self[column]
def value_as_boolean(value):
if value.lower() not in ("on", "off", "true", "false", "1", "0"):
raise ValueAsBooleanError
return value.lower() in ("on", "true", "1")
| CustomRow |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchClass1.py | {
"start": 421,
"end": 511
} | class ____:
__match_args__ = ("attr_a", "attr_b")
attr_a: int
attr_b: str
| ClassA |
python | google__jax | jax/_src/effects.py | {
"start": 2660,
"end": 3587
} | class ____(Effect):
"""A side-effect associated with the input of a `JaxprEqn` or a `Jaxpr`.
This is used as a base class for effects associated with inputs, e.g.,
reading/writing from mutable inputs.
When used in a `JaxprEqn`, `input_index` refers to `eqn.invars`.
When used in a `Jaxpr`, `input_index` refers to `jaxpr.constvars + jaxpr.invars`.
"""
def __init__(self, input_index: Any):
self.input_index = input_index
def replace(self, *, input_index: Any | None = None):
if input_index is None:
input_index = self.input_index
return self.__class__(input_index)
def __eq__(self, other):
if not isinstance(other, JaxprInputEffect):
return NotImplemented
return self.input_index == other.input_index
def __hash__(self):
return hash((self.__class__, self.input_index))
def __repr__(self):
return f"{self.__class__.__name__}({self.input_index})"
| JaxprInputEffect |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_low_rank_update_test.py | {
"start": 7280,
"end": 8106
} | class ____(
BaseLinearOperatorLowRankUpdatetest,
linear_operator_test_util.SquareLinearOperatorDerivedClassTest):
"""A = L + UDU^H, D > 0, L > 0 ==> A > 0 and we can use a Cholesky."""
_use_diag_update = True
_is_diag_update_positive = True
_use_v = False
def tearDown(self):
config.enable_tensor_float_32_execution(self.tf32_keep_)
def setUp(self):
self.tf32_keep_ = config.tensor_float_32_execution_enabled()
config.enable_tensor_float_32_execution(False)
# Decrease tolerance since we are testing with condition numbers as high as
# 1e4.
self._atol[dtypes.float32] = 1e-5
self._rtol[dtypes.float32] = 1e-5
self._atol[dtypes.float64] = 1e-10
self._rtol[dtypes.float64] = 1e-10
self._rtol[dtypes.complex64] = 1e-4
| LinearOperatorLowRankUpdatetestWithDiagUseCholesky |
python | scrapy__scrapy | tests/spiders.py | {
"start": 16306,
"end": 17004
} | class ____(MetaSpider):
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = super().from_crawler(crawler, *args, **kwargs)
crawler.signals.connect(spider.headers_received, signals.headers_received)
return spider
async def start(self):
yield Request(self.mockserver.url("/status"), errback=self.errback)
def parse(self, response):
self.meta["response"] = response
def errback(self, failure):
self.meta["failure"] = failure
def headers_received(self, headers, body_length, request, spider):
self.meta["headers_received"] = headers
raise StopDownload(fail=False)
| HeadersReceivedCallbackSpider |
python | ray-project__ray | rllib/models/torch/complex_input_net.py | {
"start": 785,
"end": 9287
} | class ____(TorchModelV2, nn.Module):
"""TorchModelV2 concat'ing CNN outputs to flat input(s), followed by FC(s).
Note: This model should be used for complex (Dict or Tuple) observation
spaces that have one or more image components.
The data flow is as follows:
`obs` (e.g. Tuple[img0, img1, discrete0]) -> `CNN0 + CNN1 + ONE-HOT`
`CNN0 + CNN1 + ONE-HOT` -> concat all flat outputs -> `out`
`out` -> (optional) FC-stack -> `out2`
`out2` -> action (logits) and value heads.
"""
def __init__(self, obs_space, action_space, num_outputs, model_config, name):
self.original_space = (
obs_space.original_space
if hasattr(obs_space, "original_space")
else obs_space
)
self.processed_obs_space = (
self.original_space
if model_config.get("_disable_preprocessor_api")
else obs_space
)
nn.Module.__init__(self)
TorchModelV2.__init__(
self, self.original_space, action_space, num_outputs, model_config, name
)
self.flattened_input_space = flatten_space(self.original_space)
# Atari type CNNs or IMPALA type CNNs (with residual layers)?
# self.cnn_type = self.model_config["custom_model_config"].get(
# "conv_type", "atari")
# Build the CNN(s) given obs_space's image components.
self.cnns = nn.ModuleDict()
self.one_hot = nn.ModuleDict()
self.flatten_dims = {}
self.flatten = nn.ModuleDict()
concat_size = 0
for i, component in enumerate(self.flattened_input_space):
i = str(i)
# Image space.
if len(component.shape) == 3 and isinstance(component, Box):
config = {
"conv_filters": model_config["conv_filters"]
if "conv_filters" in model_config
else get_filter_config(component.shape),
"conv_activation": model_config.get("conv_activation"),
"post_fcnet_hiddens": [],
}
# if self.cnn_type == "atari":
self.cnns[i] = ModelCatalog.get_model_v2(
component,
action_space,
num_outputs=None,
model_config=config,
framework="torch",
name="cnn_{}".format(i),
)
# TODO (sven): add IMPALA-style option.
# else:
# cnn = TorchImpalaVisionNet(
# component,
# action_space,
# num_outputs=None,
# model_config=config,
# name="cnn_{}".format(i))
concat_size += self.cnns[i].num_outputs
self.add_module("cnn_{}".format(i), self.cnns[i])
# Discrete|MultiDiscrete inputs -> One-hot encode.
elif isinstance(component, (Discrete, MultiDiscrete)):
if isinstance(component, Discrete):
size = component.n
else:
size = np.sum(component.nvec)
config = {
"fcnet_hiddens": model_config["fcnet_hiddens"],
"fcnet_activation": model_config.get("fcnet_activation"),
"post_fcnet_hiddens": [],
}
self.one_hot[i] = ModelCatalog.get_model_v2(
Box(-1.0, 1.0, (size,), np.float32),
action_space,
num_outputs=None,
model_config=config,
framework="torch",
name="one_hot_{}".format(i),
)
concat_size += self.one_hot[i].num_outputs
self.add_module("one_hot_{}".format(i), self.one_hot[i])
# Everything else (1D Box).
else:
size = int(np.prod(component.shape))
config = {
"fcnet_hiddens": model_config["fcnet_hiddens"],
"fcnet_activation": model_config.get("fcnet_activation"),
"post_fcnet_hiddens": [],
}
self.flatten[i] = ModelCatalog.get_model_v2(
Box(-1.0, 1.0, (size,), np.float32),
action_space,
num_outputs=None,
model_config=config,
framework="torch",
name="flatten_{}".format(i),
)
self.flatten_dims[i] = size
concat_size += self.flatten[i].num_outputs
self.add_module("flatten_{}".format(i), self.flatten[i])
# Optional post-concat FC-stack.
post_fc_stack_config = {
"fcnet_hiddens": model_config.get("post_fcnet_hiddens", []),
"fcnet_activation": model_config.get("post_fcnet_activation", "relu"),
}
self.post_fc_stack = ModelCatalog.get_model_v2(
Box(float("-inf"), float("inf"), shape=(concat_size,), dtype=np.float32),
self.action_space,
None,
post_fc_stack_config,
framework="torch",
name="post_fc_stack",
)
# Actions and value heads.
self.logits_layer = None
self.value_layer = None
self._value_out = None
if num_outputs:
# Action-distribution head.
self.logits_layer = SlimFC(
in_size=self.post_fc_stack.num_outputs,
out_size=num_outputs,
activation_fn=None,
initializer=torch_normc_initializer(0.01),
)
# Create the value branch model.
self.value_layer = SlimFC(
in_size=self.post_fc_stack.num_outputs,
out_size=1,
activation_fn=None,
initializer=torch_normc_initializer(0.01),
)
else:
self.num_outputs = concat_size
@override(ModelV2)
def forward(self, input_dict, state, seq_lens):
if SampleBatch.OBS in input_dict and "obs_flat" in input_dict:
orig_obs = input_dict[SampleBatch.OBS]
else:
orig_obs = restore_original_dimensions(
input_dict[SampleBatch.OBS], self.processed_obs_space, tensorlib="torch"
)
# Push observations through the different components
# (CNNs, one-hot + FC, etc..).
outs = []
for i, component in enumerate(tree.flatten(orig_obs)):
i = str(i)
if i in self.cnns:
cnn_out, _ = self.cnns[i](SampleBatch({SampleBatch.OBS: component}))
outs.append(cnn_out)
elif i in self.one_hot:
if component.dtype in [
torch.int8,
torch.int16,
torch.int32,
torch.int64,
torch.uint8,
]:
one_hot_in = {
SampleBatch.OBS: one_hot(
component, self.flattened_input_space[int(i)]
)
}
else:
one_hot_in = {SampleBatch.OBS: component}
one_hot_out, _ = self.one_hot[i](SampleBatch(one_hot_in))
outs.append(one_hot_out)
else:
nn_out, _ = self.flatten[i](
SampleBatch(
{
SampleBatch.OBS: torch.reshape(
component, [-1, self.flatten_dims[i]]
)
}
)
)
outs.append(nn_out)
# Concat all outputs and the non-image inputs.
out = torch.cat(outs, dim=1)
# Push through (optional) FC-stack (this may be an empty stack).
out, _ = self.post_fc_stack(SampleBatch({SampleBatch.OBS: out}))
# No logits/value branches.
if self.logits_layer is None:
return out, []
# Logits- and value branches.
logits, values = self.logits_layer(out), self.value_layer(out)
self._value_out = torch.reshape(values, [-1])
return logits, []
@override(ModelV2)
def value_function(self):
return self._value_out
| ComplexInputNetwork |
python | openai__openai-python | src/openai/_response.py | {
"start": 18786,
"end": 19309
} | class ____(AsyncAPIResponse[bytes]):
async def stream_to_file(
self,
file: str | os.PathLike[str],
*,
chunk_size: int | None = None,
) -> None:
"""Streams the output to the given file.
Accepts a filename or any path-like object, e.g. pathlib.Path
"""
path = anyio.Path(file)
async with await path.open(mode="wb") as f:
async for data in self.iter_bytes(chunk_size):
await f.write(data)
| AsyncStreamedBinaryAPIResponse |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/io_test.py | {
"start": 5360,
"end": 5840
} | class ____(IOTest, checkpoint_test_base.CheckpointTestBase):
def _build_ds(self):
return io.load(self._save_dir)
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
checkpoint_test_base.default_test_combinations()))
def test(self, verify_fn):
dataset = dataset_ops.Dataset.range(42)
self.evaluate(io.save(dataset, self._save_dir))
verify_fn(self, self._build_ds, num_outputs=42)
| LoadCheckpointTest |
python | tensorflow__tensorflow | tensorflow/python/saved_model/load_test.py | {
"start": 117832,
"end": 123547
} | class ____(test.TestCase, parameterized.TestCase):
def test_deferred_init_module_variables(self):
"""Defer initialization of variables in a module to the load stage."""
class MyModule(module.Module):
def __init__(self, size):
super().__init__()
self.size = size
# variable initialized by a Tensor-compatible value
self.w1 = variables.Variable(
constant_op.constant(1., shape=[self.size]), trainable=False)
# variable initialized by a function
self.w2 = variables.Variable(
lambda: constant_op.constant(2., shape=[self.size]))
# variable instantiated lazily in call()
self.w3 = None
def call(self):
if self.w3 is None:
self.w3 = variables.Variable(
constant_op.constant(3., shape=[self.size]))
for w in (self.w1, self.w2, self.w3):
w.assign_add(constant_op.constant(1., shape=[self.size]))
return self.w1, self.w2, self.w3
def export_initializer(initial_value, export_dir):
class Initializer(module.Module):
@def_function.function(input_signature=[])
def call(self):
if callable(initial_value):
return initial_value()
return initial_value
save.save(Initializer(), export_dir)
def create_and_save_module(weight_size):
initial_values = {} # For storing initial_value of created variables
def variable_creator(next_creator, **kwargs):
variable = next_creator(**kwargs)
variable_name = variable.name
if ":" in variable_name:
variable_name = variable_name[:variable_name.index(":")]
initial_values[variable_name] = kwargs["initial_value"]
return variable
export_dir = self.create_tempdir().full_path
with ops.Graph().as_default():
with variable_scope.variable_creator_scope(variable_creator):
exported = MyModule(weight_size)
exported.call = def_function.function(input_signature=[])(
exported.call)
module_dir = f"{export_dir}/module"
file_io.recursive_create_dir(module_dir)
save.save_and_return_nodes(
exported, module_dir, experimental_skip_checkpoint=True)
# Save the initializer of the created variables.
for variable_name, initial_value in initial_values.items():
export_initializer(initial_value,
f"{export_dir}/variables/{variable_name}")
return export_dir
def load_and_run_module(export_dir, weight_size):
# pylint: disable=unused-argument
def layer_variable_creator(next_creator, **kwargs):
variable_dir = f"{export_dir}/variables/{kwargs['name']}"
initializer = load.load(variable_dir)
kwargs["initial_value"] = initializer.call
variable = resource_variable_ops.ResourceVariable(**kwargs)
return variable
with ops.Graph().as_default():
with variable_scope.variable_creator_scope(layer_variable_creator):
imported = load.load(
f"{export_dir}/module",
options=load_options.LoadOptions(
experimental_skip_checkpoint=True))
outputs = imported.call()
with self.cached_session() as sess:
variables.global_variables_initializer().run()
# Check if variables work as expected across multiple iterations.
for i in range(3):
np_outputs = sess.run(outputs)
for j, np_output in enumerate(np_outputs):
self.assertAllClose(np_output, np.full(weight_size, i + j + 2))
# The size of the serialized content (both module and variables) stays
# small even with a large weight_size as the initial values are not stored
# in checkpoints.
weight_size = 1024
export_dir = create_and_save_module(weight_size)
load_and_run_module(export_dir, weight_size)
def _make_asset(self, contents):
fd, filename = tempfile.mkstemp(prefix=self.get_temp_dir())
with os.fdopen(fd, "w") as f:
f.write(contents)
return filename
@parameterized.named_parameters(*_test_params())
def test_assets(self, use_cpp_bindings):
# TODO(b/264882754) Fix DeferredInitModuleVariablesTest
if use_cpp_bindings:
self.skipTest("Not implemented for cpp.")
class MyLookupModel(autotrackable.AutoTrackable):
def __init__(self, vocab_file):
vocab_initializer = lookup_ops.TextFileInitializer(
vocab_file,
key_dtype=dtypes.string,
key_index=lookup_ops.TextFileIndex.WHOLE_LINE,
value_dtype=dtypes.int64,
value_index=lookup_ops.TextFileIndex.LINE_NUMBER,
)
self._vocab_table = lookup_ops.StaticHashTable(
vocab_initializer, default_value=-1
)
@def_function.function(
input_signature=[tensor_spec.TensorSpec((None,), dtypes.string)]
)
def __call__(self, inputs):
return self._vocab_table.lookup(inputs)
vocab_file = self._make_asset("\n".join(["a", "b", "c", "d"]))
root = MyLookupModel(vocab_file)
save_dir = os.path.join(self.get_temp_dir(), "save_dir")
save.save_and_return_nodes(
root, save_dir, experimental_skip_checkpoint=True
)
file_io.delete_file(vocab_file)
load_dir = os.path.join(self.get_temp_dir(), "load_dir")
file_io.rename(save_dir, load_dir)
imported = test_load(
load_dir,
options=load_options.LoadOptions(experimental_skip_checkpoint=True),
use_cpp_bindings=use_cpp_bindings,
)
self.assertAllEqual(imported(constant_op.constant(["d", "b"])), [3, 1])
| DeferredInitModuleVariablesTest |
python | hynek__structlog | tests/test_base.py | {
"start": 938,
"end": 3540
} | class ____:
def test_repr(self):
"""
repr() of a BoundLoggerBase shows its context and processors.
"""
bl = build_bl(processors=[1, 2, 3], context={"A": "B"})
assert (
"<BoundLoggerBase(context={'A': 'B'}, processors=[1, 2, 3])>"
) == repr(bl)
def test_binds_independently(self):
"""
Ensure BoundLogger is immutable by default.
"""
b = build_bl(processors=[KeyValueRenderer(sort_keys=True)])
b = b.bind(x=42, y=23)
b1 = b.bind(foo="bar")
b2 = b.bind(foo="qux")
assert b._context != b1._context != b2._context
def test_new_clears_state(self):
"""
Calling new() on a logger clears the context.
"""
b = build_bl()
b = b.bind(x=42)
assert 42 == get_context(b)["x"]
b = b.bind()
assert 42 == get_context(b)["x"]
b = b.new()
assert {} == dict(get_context(b))
def test_comparison(self):
"""
Two bound loggers are equal if their context is equal.
"""
b = build_bl()
assert b == b.bind()
assert b is not b.bind()
assert b != b.bind(x=5)
assert b != "test"
def test_bind_keeps_class(self):
"""
Binding values does not change the type of the bound logger.
"""
class Wrapper(BoundLoggerBase):
pass
b = Wrapper(None, [], {})
assert isinstance(b.bind(), Wrapper)
def test_new_keeps_class(self):
"""
Clearing context does not change the type of the bound logger.
"""
class Wrapper(BoundLoggerBase):
pass
b = Wrapper(None, [], {})
assert isinstance(b.new(), Wrapper)
def test_unbind(self):
"""
unbind() removes keys from context.
"""
b = build_bl().bind(x=42, y=23).unbind("x", "y")
assert {} == b._context
def test_unbind_fail(self):
"""
unbind() raises KeyError if the key is missing.
"""
with pytest.raises(KeyError):
build_bl().bind(x=42, y=23).unbind("x", "z")
def test_try_unbind(self):
"""
try_unbind() removes keys from context.
"""
b = build_bl().bind(x=42, y=23).try_unbind("x", "y")
assert {} == b._context
def test_try_unbind_fail(self):
"""
try_unbind() does nothing if the key is missing.
"""
b = build_bl().bind(x=42, y=23).try_unbind("x", "z")
assert {"y": 23} == b._context
| TestBinding |
python | django__django | django/db/models/expressions.py | {
"start": 49185,
"end": 50066
} | class ____(Func):
"""
An expression containing multiple expressions. Can be used to provide a
list of expressions as an argument to another expression, like a partition
clause.
"""
template = "%(expressions)s"
def __str__(self):
return self.arg_joiner.join(str(arg) for arg in self.source_expressions)
def as_sql(self, *args, **kwargs):
if not self.source_expressions:
return "", ()
return super().as_sql(*args, **kwargs)
def as_sqlite(self, compiler, connection, **extra_context):
# Casting to numeric is unnecessary.
return self.as_sql(compiler, connection, **extra_context)
def get_group_by_cols(self):
group_by_cols = []
for expr in self.get_source_expressions():
group_by_cols.extend(expr.get_group_by_cols())
return group_by_cols
| ExpressionList |
python | facebookresearch__faiss | tests/test_residual_quantizer.py | {
"start": 36473,
"end": 38886
} | class ____(unittest.TestCase):
def test_precomp(self):
ds = datasets.SyntheticDataset(32, 1000, 1000, 0)
# make sure it work with varying nb of bits
nbits = faiss.UInt64Vector()
nbits.push_back(5)
nbits.push_back(6)
nbits.push_back(7)
rq = faiss.ResidualQuantizer(ds.d, nbits)
rq.train_type = faiss.ResidualQuantizer.Train_default
rq.train(ds.get_train())
codebooks = get_additive_quantizer_codebooks(rq)
precomp = precomp_codebooks(codebooks)
codebook_cross_prods_ref, cent_norms_ref = precomp
# validate that the python tab-based encoding works
xb = ds.get_database()
ref_codes, _, _ = beam_search_encoding_ref(codebooks, xb, 7)
new_codes, _ = beam_search_encoding_tab(codebooks, xb, 7, precomp)
np.testing.assert_array_equal(ref_codes, new_codes)
# check C++ precomp tables
rq.compute_codebook_tables()
codebook_cross_prods = faiss.vector_to_array(
rq.codebook_cross_products)
ofs = 0
for m in range(1, rq.M):
py_table = np.vstack(codebook_cross_prods_ref[m])
kk = rq.codebook_offsets.at(m)
K = 1 << rq.nbits.at(m)
cpp_table = codebook_cross_prods[ofs:ofs + K * kk].reshape(kk, K)
ofs += kk * K
np.testing.assert_allclose(py_table, cpp_table, atol=1e-5)
cent_norms = faiss.vector_to_array(rq.centroid_norms)
np.testing.assert_array_almost_equal(
np.hstack(cent_norms_ref), cent_norms, decimal=5)
# validate the C++ beam_search_encode_step_tab function
beam_search_encoding_tab(codebooks, xb, 7, precomp, implem="ref cpp")
# check implem w/ residuals
n = ref_codes.shape[0]
sp = faiss.swig_ptr
ref_codes_packed = np.zeros((n, rq.code_size), dtype='uint8')
ref_codes_int32 = ref_codes.astype('int32')
rq.pack_codes(
n, sp(ref_codes_int32),
sp(ref_codes_packed), rq.M * ref_codes.shape[1]
)
rq.max_beam_size = 7
codes_ref_residuals = rq.compute_codes(xb)
np.testing.assert_array_equal(ref_codes_packed, codes_ref_residuals)
rq.use_beam_LUT = 1
codes_new = rq.compute_codes(xb)
np.testing.assert_array_equal(codes_ref_residuals, codes_new)
| TestCrossCodebookComputations |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/bigtable.py | {
"start": 12167,
"end": 15069
} | class ____(GoogleCloudBaseOperator, BigtableValidationMixin):
"""
Deletes the Cloud Bigtable instance, including its clusters and all related tables.
For more details about deleting instance have a look at the reference:
https://googleapis.github.io/google-cloud-python/latest/bigtable/instance.html#google.cloud.bigtable.instance.Instance.delete
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BigtableDeleteInstanceOperator`
:param instance_id: The ID of the Cloud Bigtable instance to delete.
:param project_id: Optional, the ID of the Google Cloud project. If set to None or missing,
the default project_id from the Google Cloud connection is used.
:param gcp_conn_id: The connection ID to use to connect to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
REQUIRED_ATTRIBUTES = ("instance_id",) # type: Iterable[str]
template_fields: Sequence[str] = (
"project_id",
"instance_id",
"impersonation_chain",
)
def __init__(
self,
*,
instance_id: str,
project_id: str = PROVIDE_PROJECT_ID,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
self.project_id = project_id
self.instance_id = instance_id
self._validate_inputs()
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
super().__init__(**kwargs)
def execute(self, context: Context) -> None:
hook = BigtableHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
try:
hook.delete_instance(project_id=self.project_id, instance_id=self.instance_id)
except google.api_core.exceptions.NotFound:
self.log.info(
"The instance '%s' does not exist in project '%s'. Consider it as deleted",
self.instance_id,
self.project_id,
)
except google.api_core.exceptions.GoogleAPICallError as e:
self.log.error("An error occurred. Exiting.")
raise e
| BigtableDeleteInstanceOperator |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 54471,
"end": 54773
} | class ____(themeable):
"""
Aspect ratio of the panel(s)
Parameters
----------
theme_element : float
`panel_height / panel_width`
Notes
-----
For a fixed relationship between the `x` and `y` scales,
use [](`~plotnine.coords.coord_fixed`).
"""
| aspect_ratio |
python | pandas-dev__pandas | asv_bench/benchmarks/arithmetic.py | {
"start": 6577,
"end": 7397
} | class ____:
params = [None, "US/Eastern"]
param_names = ["tz"]
def setup(self, tz):
N = 10**6
halfway = (N // 2) - 1
self.s = Series(date_range("20010101", periods=N, freq="min", tz=tz))
self.ts = self.s[halfway]
self.s2 = Series(date_range("20010101", periods=N, freq="s", tz=tz))
self.ts_different_reso = Timestamp("2001-01-02", tz=tz)
def time_series_timestamp_compare(self, tz):
self.s <= self.ts
def time_series_timestamp_different_reso_compare(self, tz):
self.s <= self.ts_different_reso
def time_timestamp_series_compare(self, tz):
self.ts >= self.s
def time_timestamp_ops_diff(self, tz):
self.s2.diff()
def time_timestamp_ops_diff_with_shift(self, tz):
self.s - self.s.shift()
| Timeseries |
python | chardet__chardet | chardet/utf8prober.py | {
"start": 1299,
"end": 2746
} | class ____(CharSetProber):
ONE_CHAR_PROB = 0.5
def __init__(self) -> None:
super().__init__()
self.coding_sm = CodingStateMachine(UTF8_SM_MODEL)
self._num_mb_chars = 0
self.reset()
def reset(self) -> None:
super().reset()
self.coding_sm.reset()
self._num_mb_chars = 0
@property
def charset_name(self) -> str:
return "utf-8"
@property
def language(self) -> str:
return ""
def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
for c in byte_str:
coding_state = self.coding_sm.next_state(c)
if coding_state == MachineState.ERROR:
self._state = ProbingState.NOT_ME
break
if coding_state == MachineState.ITS_ME:
self._state = ProbingState.FOUND_IT
break
if coding_state == MachineState.START:
if self.coding_sm.get_current_charlen() >= 2:
self._num_mb_chars += 1
if self.state == ProbingState.DETECTING:
if self.get_confidence() > self.SHORTCUT_THRESHOLD:
self._state = ProbingState.FOUND_IT
return self.state
def get_confidence(self) -> float:
unlike = 0.99
if self._num_mb_chars < 6:
unlike *= self.ONE_CHAR_PROB**self._num_mb_chars
return 1.0 - unlike
return unlike
| UTF8Prober |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/util.py | {
"start": 45276,
"end": 46111
} | class ____:
"""A wrapper used within the loader_criteria lambda caller so that
we can bypass declared_attr descriptors on unmapped mixins, which
normally emit a warning for such use.
might also be useful for other per-lambda instrumentations should
the need arise.
"""
__slots__ = ("subject",)
def __init__(self, subject):
self.subject = subject
@util.preload_module("sqlalchemy.orm.decl_api")
def __getattribute__(self, name):
decl_api = util.preloaded.orm.decl_api
subject = object.__getattribute__(self, "subject")
if name in subject.__dict__ and isinstance(
subject.__dict__[name], decl_api.declared_attr
):
return subject.__dict__[name].fget(subject)
else:
return getattr(subject, name)
| _WrapUserEntity |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/schema.py | {
"start": 133335,
"end": 135160
} | class ____(Executable, SchemaItem):
"""Base class for column *default* values.
This object is only present on column.default or column.onupdate.
It's not valid as a server default.
"""
__visit_name__ = "default_generator"
_is_default_generator = True
is_sequence = False
is_identity = False
is_server_default = False
is_clause_element = False
is_callable = False
is_scalar = False
has_arg = False
is_sentinel = False
column: Optional[Column[Any]]
def __init__(self, for_update: bool = False) -> None:
self.for_update = for_update
def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
if TYPE_CHECKING:
assert isinstance(parent, Column)
self.column = parent
if self.for_update:
self.column.onupdate = self
else:
self.column.default = self
def _copy(self) -> DefaultGenerator:
raise NotImplementedError()
def _execute_on_connection(
self,
connection: Connection,
distilled_params: _CoreMultiExecuteParams,
execution_options: CoreExecuteOptionsParameter,
) -> Any:
util.warn_deprecated(
"Using the .execute() method to invoke a "
"DefaultGenerator object is deprecated; please use "
"the .scalar() method.",
"2.0",
)
return self._execute_on_scalar(
connection, distilled_params, execution_options
)
def _execute_on_scalar(
self,
connection: Connection,
distilled_params: _CoreMultiExecuteParams,
execution_options: CoreExecuteOptionsParameter,
) -> Any:
return connection._execute_default(
self, distilled_params, execution_options
)
| DefaultGenerator |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/base.py | {
"start": 9605,
"end": 10717
} | class ____:
"""
Join-key information.
Parameters
----------
column_stats
Column statistics for the join key.
Notes
-----
This class is used to track join-key information.
It is used to track the columns being joined on
and the estimated unique-value count for the join key.
"""
column_stats: tuple[ColumnStats, ...]
implied_unique_count: int | None
"""Estimated unique-value count from join heuristics."""
def __init__(self, *column_stats: ColumnStats) -> None:
self.column_stats = column_stats
self.implied_unique_count = None
@cached_property
def source_row_count(self) -> int | None:
"""
Return the estimated row-count of the source columns.
Notes
-----
This is the maximum row-count estimate of the source columns.
"""
return max(
(
cs.source_info.row_count.value
for cs in self.column_stats
if cs.source_info.row_count.value is not None
),
default=None,
)
| JoinKey |
python | huggingface__transformers | src/transformers/models/video_llama_3/modular_video_llama_3.py | {
"start": 52164,
"end": 64945
} | class ____(Qwen2VLImageProcessor):
r"""
Constructs a VideoLLaMA3 image processor that dynamically resizes images based on the original images.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions.
size (`dict[str, int]`, *optional*, defaults to `{"shortest_edge": 56 * 56, "longest_edge": 28 * 28 * 1280}`):
Size of the image after resizing. `shortest_edge` and `longest_edge` keys must be present.
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
Resampling filter to use when resizing the image.
do_rescale (`bool`, *optional*, defaults to `True`):
Whether to rescale the image by the specified scale `rescale_factor`.
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
Scale factor to use if rescaling the image.
do_normalize (`bool`, *optional*, defaults to `True`):
Whether to normalize the image.
image_mean (`float` or `list[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
Mean to use if normalizing the image. This is a float or list of floats for each channel in the image.
image_std (`float` or `list[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image.
do_convert_rgb (`bool`, *optional*, defaults to `True`):
Whether to convert the image to RGB.
min_pixels (`int`, *optional*, defaults to `56 * 56`):
The min pixels of the image to resize the image.
max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`):
The max pixels of the image to resize the image.
patch_size (`int`, *optional*, defaults to 14):
The spatial patch size of the vision encoder.
temporal_patch_size (`int`, *optional*, defaults to 1):
The temporal patch size of the vision encoder.
merge_size (`int`, *optional*, defaults to 1):
The merge size of the vision encoder to llm encoder.
"""
model_input_names = ["pixel_values", "image_grid_thw", "image_merge_sizes"]
valid_kwargs = VideoLlama3ImageProcessorKwargs
def __init__(
self,
do_resize: bool = True,
size: Optional[dict[str, int]] = None,
resample: PILImageResampling = PILImageResampling.BICUBIC,
do_rescale: bool = True,
rescale_factor: Union[int, float] = 1 / 255,
do_normalize: bool = True,
image_mean: Optional[Union[float, list[float]]] = None,
image_std: Optional[Union[float, list[float]]] = None,
do_convert_rgb: bool = True,
min_pixels: Optional[int] = None,
max_pixels: Optional[int] = None,
patch_size: int = 14,
temporal_patch_size: int = 1,
merge_size: int = 1,
**kwargs,
) -> None:
super().__init__(
do_resize=do_resize,
size=size,
resample=resample,
do_rescale=do_rescale,
rescale_factor=rescale_factor,
do_normalize=do_normalize,
image_mean=image_mean,
image_std=image_std,
do_convert_rgb=do_convert_rgb,
min_pixels=min_pixels,
max_pixels=max_pixels,
patch_size=patch_size,
temporal_patch_size=temporal_patch_size,
merge_size=merge_size,
**kwargs,
)
self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
if self.temporal_patch_size != 1:
raise ValueError("`temporal_patch_size` must be 1 for VideoLLaMA3")
def preprocess(
self,
images: ImageInput,
videos: Optional[VideoInput] = None,
do_resize: Optional[bool] = None,
size: Optional[dict[str, int]] = None,
min_pixels: Optional[int] = None,
max_pixels: Optional[int] = None,
resample: Optional[PILImageResampling] = None,
do_rescale: Optional[bool] = None,
rescale_factor: Optional[float] = None,
do_normalize: Optional[bool] = None,
image_mean: Optional[Union[float, list[float]]] = None,
image_std: Optional[Union[float, list[float]]] = None,
patch_size: Optional[int] = None,
temporal_patch_size: Optional[int] = None,
merge_size: Optional[int] = None,
do_convert_rgb: Optional[bool] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
):
"""
Args:
images (`ImageInput`):
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
videos (`VideoInput`):
Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
passing in videos with pixel values between 0 and 1, set `do_rescale=False`.
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
Whether to resize the image.
size (`dict[str, int]`, *optional*, defaults to `self.size`):
Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
the longest edge resized to keep the input aspect ratio.
resample (`int`, *optional*, defaults to `self.resample`):
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
has an effect if `do_resize` is set to `True`.
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
Whether to rescale the image.
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
Whether to normalize the image.
image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
`True`.
min_pixels (`int`, *optional*, defaults to `self.min_pixels`):
The min pixels of the image to resize the image.
max_pixels (`int`, *optional*, defaults to `self.max_pixels`):
The max pixels of the image to resize the image.
patch_size (`int`, *optional*, defaults to `self.patch_size`):
The spatial patch size of the vision encoder.
temporal_patch_size (`int`, *optional*, defaults to `self.temporal_patch_size`):
The temporal patch size of the vision encoder.
merge_size (`int`, *optional*, defaults to `self.merge_size`):
The merge size of the vision encoder to llm encoder.
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
Whether to convert the image to RGB.
return_tensors (`str` or `TensorType`, *optional*):
The type of tensors to return. Can be one of:
- Unset: Return a list of `np.ndarray`.
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
The channel dimension format for the output image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
- Unset: Use the channel dimension format of the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format for the input image. If unset, the channel dimension format is inferred
from the input image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
"""
min_pixels = min_pixels if min_pixels is not None else self.min_pixels
max_pixels = max_pixels if max_pixels is not None else self.max_pixels
if size is not None:
if "shortest_edge" not in size or "longest_edge" not in size:
raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")
min_pixels = size["shortest_edge"]
elif min_pixels is not None and max_pixels is not None:
# backward compatibility: override size with min_pixels and max_pixels if they are provided
size = {"shortest_edge": min_pixels, "longest_edge": max_pixels}
else:
size = {**self.size}
do_resize = do_resize if do_resize is not None else self.do_resize
resample = resample if resample is not None else self.resample
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
image_mean = image_mean if image_mean is not None else self.image_mean
image_std = image_std if image_std is not None else self.image_std
patch_size = patch_size if patch_size is not None else self.patch_size
temporal_patch_size = temporal_patch_size if temporal_patch_size is not None else self.temporal_patch_size
merge_size = merge_size if merge_size is not None else self.merge_size
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
if images is not None:
images = self.fetch_images(images)
images = make_flat_list_of_images(images)
if images is not None and not valid_images(images):
raise ValueError("Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor")
validate_preprocess_arguments(
rescale_factor=rescale_factor,
do_normalize=do_normalize,
image_mean=image_mean,
image_std=image_std,
do_resize=do_resize,
size=size,
resample=resample,
)
data = {}
if images is not None:
pixel_values, vision_grid_thws = [], []
for image in images:
patches, image_grid_thw = self._preprocess(
image,
do_resize=do_resize,
size=size,
resample=resample,
do_rescale=do_rescale,
rescale_factor=rescale_factor,
do_normalize=do_normalize,
image_mean=image_mean,
image_std=image_std,
patch_size=patch_size,
temporal_patch_size=temporal_patch_size,
merge_size=merge_size,
data_format=data_format,
do_convert_rgb=do_convert_rgb,
input_data_format=input_data_format,
)
pixel_values.extend(patches)
vision_grid_thws.append(image_grid_thw)
data.update(
{
"pixel_values": np.array(pixel_values),
"image_grid_thw": np.array(vision_grid_thws),
"image_merge_sizes": np.array([merge_size] * len(vision_grid_thws)),
}
)
return BatchFeature(data=data, tensor_type=return_tensors)
| VideoLlama3ImageProcessor |
python | pymupdf__PyMuPDF | src/__init__.py | {
"start": 97459,
"end": 304032
} | class ____:
def __contains__(self, loc) -> bool:
if type(loc) is int:
if loc < self.page_count:
return True
return False
if type(loc) not in (tuple, list) or len(loc) != 2:
return False
chapter, pno = loc
if (0
or not isinstance(chapter, int)
or chapter < 0
or chapter >= self.chapter_count
):
return False
if (0
or not isinstance(pno, int)
or pno < 0
or pno >= self.chapter_page_count(chapter)
):
return False
return True
def __delitem__(self, i)->None:
if not self.is_pdf:
raise ValueError("is no PDF")
if type(i) is int:
return self.delete_page(i)
if type(i) in (list, tuple, range):
return self.delete_pages(i)
if type(i) is not slice:
raise ValueError("bad argument type")
pc = self.page_count
start = i.start if i.start else 0
stop = i.stop if i.stop else pc
step = i.step if i.step else 1
while start < 0:
start += pc
if start >= pc:
raise ValueError("bad page number(s)")
while stop < 0:
stop += pc
if stop > pc:
raise ValueError("bad page number(s)")
return self.delete_pages(range(start, stop, step))
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
@typing.overload
def __getitem__(self, i: int = 0) -> Page:
...
if sys.version_info >= (3, 9):
@typing.overload
def __getitem__(self, i: slice) -> list[Page]:
...
@typing.overload
def __getitem__(self, i: tuple[int, int]) -> Page:
...
def __getitem__(self, i=0):
if isinstance(i, slice):
return [self[j] for j in range(*i.indices(len(self)))]
assert isinstance(i, int) or (isinstance(i, tuple) and len(i) == 2 and all(isinstance(x, int) for x in i)), \
f'Invalid item number: {i=}.'
if i not in self:
raise IndexError(f"page {i} not in document")
return self.load_page(i)
def __init__(self, filename=None, stream=None, filetype=None, rect=None, width=0, height=0, fontsize=11):
"""Creates a document. Use 'open' as a synonym.
Notes:
Basic usages:
open() - new PDF document
open(filename) - string or pathlib.Path, must have supported
file extension.
open(type, buffer) - type: valid extension, buffer: bytes object.
open(stream=buffer, filetype=type) - keyword version of previous.
open(filename, fileype=type) - filename with unrecognized extension.
rect, width, height, fontsize: layout reflowable document
on open (e.g. EPUB). Ignored if n/a.
"""
# We temporarily set JM_mupdf_show_errors=0 while we are constructing,
# then restore its original value in a `finally:` block.
#
global JM_mupdf_show_errors
JM_mupdf_show_errors_old = JM_mupdf_show_errors
JM_mupdf_show_errors = 0
try:
self.is_closed = False
self.is_encrypted = False
self.is_encrypted = False
self.metadata = None
self.FontInfos = []
self.Graftmaps = {}
self.ShownPages = {}
self.InsertedImages = {}
self._page_refs = weakref.WeakValueDictionary()
if isinstance(filename, mupdf.PdfDocument):
pdf_document = filename
self.this = pdf_document
self.this_is_pdf = True
return
w = width
h = height
r = JM_rect_from_py(rect)
if not mupdf.fz_is_infinite_rect(r):
w = r.x1 - r.x0
h = r.y1 - r.y0
self._name = filename
self.stream = stream
if stream is not None:
if filename is not None and filetype is None:
# 2025-05-06: Use <filename> as the filetype. This is
# reversing precedence - we used to use <filename> if both
# were set.
filetype = filename
if isinstance(stream, (bytes, memoryview)):
pass
elif isinstance(stream, bytearray):
stream = bytes(stream)
elif isinstance(stream, io.BytesIO):
stream = stream.getvalue()
else:
raise TypeError(f"bad stream: {type(stream)=}.")
self.stream = stream
assert isinstance(stream, (bytes, memoryview))
if len(stream) == 0:
# MuPDF raise an exception for this but also generates
# warnings, which is not very helpful for us. So instead we
# raise a specific exception.
raise EmptyFileError('Cannot open empty stream.')
stream2 = mupdf.fz_open_memory(mupdf.python_buffer_data(stream), len(stream))
try:
doc = mupdf.fz_open_document_with_stream(filetype if filetype else '', stream2)
except Exception as e:
if g_exceptions_verbose > 1: exception_info()
raise FileDataError('Failed to open stream') from e
elif filename:
assert not stream
if isinstance(filename, str):
pass
elif hasattr(filename, "absolute"):
filename = str(filename)
elif hasattr(filename, "name"):
filename = filename.name
else:
raise TypeError(f"bad filename: {type(filename)=} {filename=}.")
self._name = filename
# Generate our own specific exceptions. This avoids MuPDF
# generating warnings etc.
if not os.path.exists(filename):
raise FileNotFoundError(f"no such file: '{filename}'")
elif not os.path.isfile(filename):
raise FileDataError(f"'{filename}' is no file")
elif os.path.getsize(filename) == 0:
raise EmptyFileError(f'Cannot open empty file: {filename=}.')
if filetype:
# Override the type implied by <filename>. MuPDF does not
# have a way to do this directly so we open via a stream.
try:
fz_stream = mupdf.fz_open_file(filename)
doc = mupdf.fz_open_document_with_stream(filetype, fz_stream)
except Exception as e:
if g_exceptions_verbose > 1: exception_info()
raise FileDataError(f'Failed to open file {filename!r} as type {filetype!r}.') from e
else:
try:
doc = mupdf.fz_open_document(filename)
except Exception as e:
if g_exceptions_verbose > 1: exception_info()
raise FileDataError(f'Failed to open file {filename!r}.') from e
else:
pdf = mupdf.PdfDocument()
doc = mupdf.FzDocument(pdf)
if w > 0 and h > 0:
mupdf.fz_layout_document(doc, w, h, fontsize)
elif mupdf.fz_is_document_reflowable(doc):
mupdf.fz_layout_document(doc, 400, 600, 11)
self.this = doc
# fixme: not sure where self.thisown gets initialised in PyMuPDF.
#
self.thisown = True
if self.thisown:
self._graft_id = TOOLS.gen_id()
if self.needs_pass:
self.is_encrypted = True
else: # we won't init until doc is decrypted
self.init_doc()
# the following hack detects invalid/empty SVG files, which else may lead
# to interpreter crashes
if filename and filename.lower().endswith("svg") or filetype and "svg" in filetype.lower():
try:
_ = self.convert_to_pdf() # this seems to always work
except Exception as e:
if g_exceptions_verbose > 1: exception_info()
raise FileDataError("cannot open broken document") from e
if g_use_extra:
self.this_is_pdf = isinstance( self.this, mupdf.PdfDocument)
if self.this_is_pdf:
self.page_count2 = extra.page_count_pdf
else:
self.page_count2 = extra.page_count_fz
finally:
JM_mupdf_show_errors = JM_mupdf_show_errors_old
def __len__(self) -> int:
return self.page_count
def __repr__(self) -> str:
m = "closed " if self.is_closed else ""
if self.stream is None:
if self.name == "":
return m + "Document(<new PDF, doc# %i>)" % self._graft_id
return m + "Document('%s')" % (self.name,)
return m + "Document('%s', <memory, doc# %i>)" % (self.name, self._graft_id)
def _addFormFont(self, name, font):
"""Add new form font."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return
fonts = mupdf.pdf_dict_getl(
mupdf.pdf_trailer( pdf),
PDF_NAME('Root'),
PDF_NAME('AcroForm'),
PDF_NAME('DR'),
PDF_NAME('Font'),
)
if not fonts.m_internal or not mupdf.pdf_is_dict( fonts):
raise RuntimeError( "PDF has no form fonts yet")
k = mupdf.pdf_new_name( name)
v = JM_pdf_obj_from_str( pdf, font)
mupdf.pdf_dict_put( fonts, k, v)
def del_toc_item(
self,
idx: int,
) -> None:
"""Delete TOC / bookmark item by index."""
xref = self.get_outline_xrefs()[idx]
self._remove_toc_item(xref)
def _delToC(self):
"""Delete the TOC."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
xrefs = [] # create Python list
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return xrefs # not a pdf
# get the main root
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
# get the outline root
olroot = mupdf.pdf_dict_get(root, PDF_NAME('Outlines'))
if not olroot.m_internal:
return xrefs # no outlines or some problem
first = mupdf.pdf_dict_get(olroot, PDF_NAME('First')) # first outline
xrefs = JM_outline_xrefs(first, xrefs)
xref_count = len(xrefs)
olroot_xref = mupdf.pdf_to_num(olroot) # delete OL root
mupdf.pdf_delete_object(pdf, olroot_xref) # delete OL root
mupdf.pdf_dict_del(root, PDF_NAME('Outlines')) # delete OL root
for i in range(xref_count):
_, xref = JM_INT_ITEM(xrefs, i)
mupdf.pdf_delete_object(pdf, xref) # delete outline item
xrefs.append(olroot_xref)
val = xrefs
self.init_doc()
return val
def _delete_page(self, pno):
pdf = _as_pdf_document(self)
mupdf.pdf_delete_page( pdf, pno)
if pdf.m_internal.rev_page_map:
mupdf.ll_pdf_drop_page_tree( pdf.m_internal)
def _deleteObject(self, xref):
"""Delete object."""
pdf = _as_pdf_document(self)
if not _INRANGE(xref, 1, mupdf.pdf_xref_len(pdf)-1):
raise ValueError( MSG_BAD_XREF)
mupdf.pdf_delete_object(pdf, xref)
def _do_links(
doc1: 'Document',
doc2: 'Document',
from_page: int = -1,
to_page: int = -1,
start_at: int = -1,
) -> None:
"""Insert links contained in copied page range into destination PDF.
Parameter values **must** equal those of method insert_pdf(), which must
have been previously executed.
"""
#pymupdf.log( 'utils.do_links()')
# --------------------------------------------------------------------------
# internal function to create the actual "/Annots" object string
# --------------------------------------------------------------------------
def cre_annot(lnk, xref_dst, pno_src, ctm):
"""Create annotation object string for a passed-in link."""
r = lnk["from"] * ctm # rect in PDF coordinates
rect = _format_g(tuple(r))
if lnk["kind"] == LINK_GOTO:
txt = annot_skel["goto1"] # annot_goto
idx = pno_src.index(lnk["page"])
p = lnk["to"] * ctm # target point in PDF coordinates
annot = txt(xref_dst[idx], p.x, p.y, lnk["zoom"], rect)
elif lnk["kind"] == LINK_GOTOR:
if lnk["page"] >= 0:
txt = annot_skel["gotor1"] # annot_gotor
pnt = lnk.get("to", Point(0, 0)) # destination point
if type(pnt) is not Point:
pnt = Point(0, 0)
annot = txt(
lnk["page"],
pnt.x,
pnt.y,
lnk["zoom"],
lnk["file"],
lnk["file"],
rect,
)
else:
txt = annot_skel["gotor2"] # annot_gotor_n
to = get_pdf_str(lnk["to"])
to = to[1:-1]
f = lnk["file"]
annot = txt(to, f, rect)
elif lnk["kind"] == LINK_LAUNCH:
txt = annot_skel["launch"] # annot_launch
annot = txt(lnk["file"], lnk["file"], rect)
elif lnk["kind"] == LINK_URI:
txt = annot_skel["uri"] # annot_uri
annot = txt(lnk["uri"], rect)
else:
annot = ""
return annot
# --------------------------------------------------------------------------
# validate & normalize parameters
if from_page < 0:
fp = 0
elif from_page >= doc2.page_count:
fp = doc2.page_count - 1
else:
fp = from_page
if to_page < 0 or to_page >= doc2.page_count:
tp = doc2.page_count - 1
else:
tp = to_page
if start_at < 0:
raise ValueError("'start_at' must be >= 0")
sa = start_at
incr = 1 if fp <= tp else -1 # page range could be reversed
# lists of source / destination page numbers
pno_src = list(range(fp, tp + incr, incr))
pno_dst = [sa + i for i in range(len(pno_src))]
# lists of source / destination page xrefs
xref_src = []
xref_dst = []
for i in range(len(pno_src)):
p_src = pno_src[i]
p_dst = pno_dst[i]
old_xref = doc2.page_xref(p_src)
new_xref = doc1.page_xref(p_dst)
xref_src.append(old_xref)
xref_dst.append(new_xref)
# create the links for each copied page in destination PDF
for i in range(len(xref_src)):
page_src = doc2[pno_src[i]] # load source page
links = page_src.get_links() # get all its links
#log( '{pno_src=}')
#log( '{type(page_src)=}')
#log( '{page_src=}')
#log( '{=i len(links)}')
if len(links) == 0: # no links there
page_src = None
continue
ctm = ~page_src.transformation_matrix # calc page transformation matrix
page_dst = doc1[pno_dst[i]] # load destination page
link_tab = [] # store all link definitions here
for l in links:
if l["kind"] == LINK_GOTO and (l["page"] not in pno_src):
continue # GOTO link target not in copied pages
annot_text = cre_annot(l, xref_dst, pno_src, ctm)
if annot_text:
link_tab.append(annot_text)
if link_tab != []:
page_dst._addAnnot_FromString( tuple(link_tab))
#log( 'utils.do_links() returning.')
def _do_widgets(
tar: 'Document',
src: 'Document',
graftmap,
from_page: int = -1,
to_page: int = -1,
start_at: int = -1,
join_duplicates=0,
) -> None:
"""Insert widgets of copied page range into target PDF.
Parameter values **must** equal those of method insert_pdf() which
must have been previously executed.
"""
if not src.is_form_pdf: # nothing to do: source PDF has no fields
return
def clean_kid_parents(acro_fields):
""" Make sure all kids have correct "Parent" pointers."""
for i in range(acro_fields.pdf_array_len()):
parent = acro_fields.pdf_array_get(i)
kids = parent.pdf_dict_get(PDF_NAME("Kids"))
for j in range(kids.pdf_array_len()):
kid = kids.pdf_array_get(j)
kid.pdf_dict_put(PDF_NAME("Parent"), parent)
def join_widgets(pdf, acro_fields, xref1, xref2, name):
"""Called for each pair of widgets having the same name.
Args:
pdf: target MuPDF document
acro_fields: object Root/AcroForm/Fields
xref1, xref2: widget xrefs having same names
name: (str) the name
Result:
Defined or updated widget parent that points to both widgets.
"""
def re_target(pdf, acro_fields, xref1, kids1, xref2, kids2):
"""Merge widget in xref2 into "Kids" list of widget xref1.
Args:
xref1, kids1: target widget and its "Kids" array.
xref2, kids2: source wwidget and its "Kids" array (may be empty).
"""
# make indirect objects from widgets
w1_ind = mupdf.pdf_new_indirect(pdf, xref1, 0)
w2_ind = mupdf.pdf_new_indirect(pdf, xref2, 0)
# find source widget in "Fields" array
idx = acro_fields.pdf_array_find(w2_ind)
acro_fields.pdf_array_delete(idx)
if not kids2.pdf_is_array(): # source widget has no kids
widget = mupdf.pdf_load_object(pdf, xref2)
# delete name from widget and insert target as parent
widget.pdf_dict_del(PDF_NAME("T"))
widget.pdf_dict_put(PDF_NAME("Parent"), w1_ind)
# put in target Kids
kids1.pdf_array_push(w2_ind)
else: # copy source kids to target kids
for i in range(kids2.pdf_array_len()):
kid = kids2.pdf_array_get(i)
kid.pdf_dict_put(PDF_NAME("Parent"), w1_ind)
kid_ind = mupdf.pdf_new_indirect(pdf, kid.pdf_to_num(), 0)
kids1.pdf_array_push(kid_ind)
def new_target(pdf, acro_fields, xref1, w1, xref2, w2, name):
"""Make new "Parent" for two widgets with same name.
Args:
xref1, w1: first widget
xref2, w2: second widget
name: field name
Result:
Both widgets have no "Kids". We create a new object with the
name and a "Kids" array containing the widgets.
Original widgets must be removed from AcroForm/Fields.
"""
# make new "Parent" object
new = mupdf.pdf_new_dict(pdf, 5)
new.pdf_dict_put_text_string(PDF_NAME("T"), name)
kids = new.pdf_dict_put_array(PDF_NAME("Kids"), 2)
new_obj = mupdf.pdf_add_object(pdf, new)
new_obj_xref = new_obj.pdf_to_num()
new_ind = mupdf.pdf_new_indirect(pdf, new_obj_xref, 0)
# copy over some required source widget properties
ft = w1.pdf_dict_get(PDF_NAME("FT"))
w1.pdf_dict_del(PDF_NAME("FT"))
new_obj.pdf_dict_put(PDF_NAME("FT"), ft)
aa = w1.pdf_dict_get(PDF_NAME("AA"))
w1.pdf_dict_del(PDF_NAME("AA"))
new_obj.pdf_dict_put(PDF_NAME("AA"), aa)
# remove name field, insert "Parent" field in source widgets
w1.pdf_dict_del(PDF_NAME("T"))
w1.pdf_dict_put(PDF_NAME("Parent"), new_ind)
w2.pdf_dict_del(PDF_NAME("T"))
w2.pdf_dict_put(PDF_NAME("Parent"), new_ind)
# put source widgets in "kids" array
ind1 = mupdf.pdf_new_indirect(pdf, xref1, 0)
ind2 = mupdf.pdf_new_indirect(pdf, xref2, 0)
kids.pdf_array_push(ind1)
kids.pdf_array_push(ind2)
# remove source widgets from "AcroForm/Fields"
idx = acro_fields.pdf_array_find(ind1)
acro_fields.pdf_array_delete(idx)
idx = acro_fields.pdf_array_find(ind2)
acro_fields.pdf_array_delete(idx)
acro_fields.pdf_array_push(new_ind)
w1 = mupdf.pdf_load_object(pdf, xref1)
w2 = mupdf.pdf_load_object(pdf, xref2)
kids1 = w1.pdf_dict_get(PDF_NAME("Kids"))
kids2 = w2.pdf_dict_get(PDF_NAME("Kids"))
# check which widget has a suitable "Kids" array
if kids1.pdf_is_array():
re_target(pdf, acro_fields, xref1, kids1, xref2, kids2) # pylint: disable=arguments-out-of-order
elif kids2.pdf_is_array():
re_target(pdf, acro_fields, xref2, kids2, xref1, kids1) # pylint: disable=arguments-out-of-order
else:
new_target(pdf, acro_fields, xref1, w1, xref2, w2, name) # pylint: disable=arguments-out-of-order
def get_kids(parent, kids_list):
"""Return xref list of leaf kids for a parent.
Call with an empty list.
"""
kids = mupdf.pdf_dict_get(parent, PDF_NAME("Kids"))
if not kids.pdf_is_array():
return kids_list
for i in range(kids.pdf_array_len()):
kid = kids.pdf_array_get(i)
if mupdf.pdf_is_dict(mupdf.pdf_dict_get(kid, PDF_NAME("Kids"))):
kids_list = get_kids(kid, kids_list)
else:
kids_list.append(kid.pdf_to_num())
return kids_list
def kids_xrefs(widget):
"""Get the xref of top "Parent" and the list of leaf widgets."""
kids_list = []
parent = mupdf.pdf_dict_get(widget, PDF_NAME("Parent"))
parent_xref = parent.pdf_to_num()
if parent_xref == 0:
return parent_xref, kids_list
kids_list = get_kids(parent, kids_list)
return parent_xref, kids_list
def deduplicate_names(pdf, acro_fields, join_duplicates=False):
"""Handle any widget name duplicates caused by the merge."""
names = {} # key is a widget name, value a list of widgets having it.
# extract all names and widgets in "AcroForm/Fields"
for i in range(mupdf.pdf_array_len(acro_fields)):
wobject = mupdf.pdf_array_get(acro_fields, i)
xref = wobject.pdf_to_num()
# extract widget name and collect widget(s) using it
T = mupdf.pdf_dict_get_text_string(wobject, PDF_NAME("T"))
xrefs = names.get(T, [])
xrefs.append(xref)
names[T] = xrefs
for name, xrefs in names.items():
if len(xrefs) < 2:
continue
xref0, xref1 = xrefs[:2] # only exactly 2 should occur!
if join_duplicates: # combine fields with equal names
join_widgets(pdf, acro_fields, xref0, xref1, name)
else: # make field names unique
newname = name + f" [{xref1}]" # append this to the name
wobject = mupdf.pdf_load_object(pdf, xref1)
wobject.pdf_dict_put_text_string(PDF_NAME("T"), newname)
clean_kid_parents(acro_fields)
def get_acroform(doc):
"""Retrieve the AcroForm dictionary form a PDF."""
pdf = mupdf.pdf_document_from_fz_document(doc)
# AcroForm (= central form field info)
return mupdf.pdf_dict_getp(mupdf.pdf_trailer(pdf), "Root/AcroForm")
tarpdf = mupdf.pdf_document_from_fz_document(tar)
srcpdf = mupdf.pdf_document_from_fz_document(src)
if tar.is_form_pdf:
# target is a Form PDF, so use it to include source fields
acro = get_acroform(tar)
# Important arrays in AcroForm
acro_fields = acro.pdf_dict_get(PDF_NAME("Fields"))
tar_co = acro.pdf_dict_get(PDF_NAME("CO"))
if not tar_co.pdf_is_array():
tar_co = acro.pdf_dict_put_array(PDF_NAME("CO"), 5)
else:
# target is no Form PDF, so copy over source AcroForm
acro = mupdf.pdf_deep_copy_obj(get_acroform(src)) # make a copy
# Clear "Fields" and "CO" arrays: will be populated by page fields.
# This is required to avoid copying unneeded objects.
acro.pdf_dict_del(PDF_NAME("Fields"))
acro.pdf_dict_put_array(PDF_NAME("Fields"), 5)
acro.pdf_dict_del(PDF_NAME("CO"))
acro.pdf_dict_put_array(PDF_NAME("CO"), 5)
# Enrich AcroForm for copying to target
acro_graft = mupdf.pdf_graft_mapped_object(graftmap, acro)
# Insert AcroForm into target PDF
acro_tar = mupdf.pdf_add_object(tarpdf, acro_graft)
acro_fields = acro_tar.pdf_dict_get(PDF_NAME("Fields"))
tar_co = acro_tar.pdf_dict_get(PDF_NAME("CO"))
# get its xref and insert it into target catalog
tar_xref = acro_tar.pdf_to_num()
acro_tar_ind = mupdf.pdf_new_indirect(tarpdf, tar_xref, 0)
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(tarpdf), PDF_NAME("Root"))
root.pdf_dict_put(PDF_NAME("AcroForm"), acro_tar_ind)
if from_page <= to_page:
src_range = range(from_page, to_page + 1)
else:
src_range = range(from_page, to_page - 1, -1)
parents = {} # information about widget parents
# remove "P" owning page reference from all widgets of all source pages
for i in src_range:
src_page = src[i]
for xref in [
xref
for xref, wtype, _ in src_page.annot_xrefs()
if wtype == mupdf.PDF_ANNOT_WIDGET # pylint: disable=no-member
]:
w_obj = mupdf.pdf_load_object(srcpdf, xref)
w_obj.pdf_dict_del(PDF_NAME("P"))
# get the widget's parent structure
parent_xref, old_kids = kids_xrefs(w_obj)
if parent_xref:
parents[parent_xref] = {
"new_xref": 0,
"old_kids": old_kids,
"new_kids": [],
}
# Copy over Parent widgets first - they are not page-dependent
for xref in parents.keys(): # pylint: disable=consider-using-dict-items
parent = mupdf.pdf_load_object(srcpdf, xref)
parent_graft = mupdf.pdf_graft_mapped_object(graftmap, parent)
parent_tar = mupdf.pdf_add_object(tarpdf, parent_graft)
kids_xrefs_new = get_kids(parent_tar, [])
parent_xref_new = parent_tar.pdf_to_num()
parent_ind = mupdf.pdf_new_indirect(tarpdf, parent_xref_new, 0)
acro_fields.pdf_array_push(parent_ind)
parents[xref]["new_xref"] = parent_xref_new
parents[xref]["new_kids"] = kids_xrefs_new
for i in range(len(src_range)):
# read first copied over page in target
tar_page = tar[start_at + i]
# read the original page in the source PDF
src_page = src[src_range[i]]
# now walk through source page widgets and copy over
w_xrefs = [ # widget xrefs of the source page
xref
for xref, wtype, _ in src_page.annot_xrefs()
if wtype == mupdf.PDF_ANNOT_WIDGET # pylint: disable=no-member
]
if not w_xrefs: # no widgets on this source page
continue
# convert to formal PDF page
tar_page_pdf = mupdf.pdf_page_from_fz_page(tar_page)
# extract annotations array
tar_annots = mupdf.pdf_dict_get(tar_page_pdf.obj(), PDF_NAME("Annots"))
if not mupdf.pdf_is_array(tar_annots):
tar_annots = mupdf.pdf_dict_put_array(
tar_page_pdf.obj(), PDF_NAME("Annots"), 5
)
for xref in w_xrefs:
w_obj = mupdf.pdf_load_object(srcpdf, xref)
# check if field takes part in inter-field validations
is_aac = mupdf.pdf_is_dict(mupdf.pdf_dict_getp(w_obj, "AA/C"))
# check if parent of widget already in target
parent_xref = mupdf.pdf_to_num(
w_obj.pdf_dict_get(PDF_NAME("Parent"))
)
if parent_xref == 0: # parent not in target yet
try:
w_obj_graft = mupdf.pdf_graft_mapped_object(graftmap, w_obj)
except Exception as e:
message_warning(f"cannot copy widget at {xref=}: {e}")
continue
w_obj_tar = mupdf.pdf_add_object(tarpdf, w_obj_graft)
tar_xref = w_obj_tar.pdf_to_num()
w_obj_tar_ind = mupdf.pdf_new_indirect(tarpdf, tar_xref, 0)
mupdf.pdf_array_push(tar_annots, w_obj_tar_ind)
mupdf.pdf_array_push(acro_fields, w_obj_tar_ind)
else:
parent = parents[parent_xref]
idx = parent["old_kids"].index(xref) # search for xref in parent
tar_xref = parent["new_kids"][idx]
w_obj_tar_ind = mupdf.pdf_new_indirect(tarpdf, tar_xref, 0)
mupdf.pdf_array_push(tar_annots, w_obj_tar_ind)
# Into "AcroForm/CO" if a computation field.
if is_aac:
mupdf.pdf_array_push(tar_co, w_obj_tar_ind)
deduplicate_names(tarpdf, acro_fields, join_duplicates=join_duplicates)
def _embeddedFileGet(self, idx):
pdf = _as_pdf_document(self)
names = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
entry = mupdf.pdf_array_get(names, 2*idx+1)
filespec = mupdf.pdf_dict_getl(entry, PDF_NAME('EF'), PDF_NAME('F'))
buf = mupdf.pdf_load_stream(filespec)
cont = JM_BinFromBuffer(buf)
return cont
def _embeddedFileIndex(self, item: typing.Union[int, str]) -> int:
filenames = self.embfile_names()
msg = "'%s' not in EmbeddedFiles array." % str(item)
if item in filenames:
idx = filenames.index(item)
elif item in range(len(filenames)):
idx = item
else:
raise ValueError(msg)
return idx
def _embfile_add(self, name, buffer_, filename=None, ufilename=None, desc=None):
pdf = _as_pdf_document(self)
data = JM_BufferFromBytes(buffer_)
if not data.m_internal:
raise TypeError( MSG_BAD_BUFFER)
names = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
if not mupdf.pdf_is_array(names):
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
names = mupdf.pdf_new_array(pdf, 6) # an even number!
mupdf.pdf_dict_putl(
root,
names,
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
fileentry = JM_embed_file(pdf, data, filename, ufilename, desc, 1)
xref = mupdf.pdf_to_num(
mupdf.pdf_dict_getl(fileentry, PDF_NAME('EF'), PDF_NAME('F'))
)
mupdf.pdf_array_push(names, mupdf.pdf_new_text_string(name))
mupdf.pdf_array_push(names, fileentry)
return xref
def _embfile_del(self, idx):
pdf = _as_pdf_document(self)
names = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
mupdf.pdf_array_delete(names, idx + 1)
mupdf.pdf_array_delete(names, idx)
def _embfile_info(self, idx, infodict):
pdf = _as_pdf_document(self)
xref = 0
ci_xref=0
trailer = mupdf.pdf_trailer(pdf)
names = mupdf.pdf_dict_getl(
trailer,
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
o = mupdf.pdf_array_get(names, 2*idx+1)
ci = mupdf.pdf_dict_get(o, PDF_NAME('CI'))
if ci.m_internal:
ci_xref = mupdf.pdf_to_num(ci)
infodict["collection"] = ci_xref
name = mupdf.pdf_to_text_string(mupdf.pdf_dict_get(o, PDF_NAME('F')))
infodict[dictkey_filename] = JM_EscapeStrFromStr(name)
name = mupdf.pdf_to_text_string(mupdf.pdf_dict_get(o, PDF_NAME('UF')))
infodict[dictkey_ufilename] = JM_EscapeStrFromStr(name)
name = mupdf.pdf_to_text_string(mupdf.pdf_dict_get(o, PDF_NAME('Desc')))
infodict[dictkey_descr] = JM_UnicodeFromStr(name)
len_ = -1
DL = -1
fileentry = mupdf.pdf_dict_getl(o, PDF_NAME('EF'), PDF_NAME('F'))
xref = mupdf.pdf_to_num(fileentry)
o = mupdf.pdf_dict_get(fileentry, PDF_NAME('Length'))
if o.m_internal:
len_ = mupdf.pdf_to_int(o)
o = mupdf.pdf_dict_get(fileentry, PDF_NAME('DL'))
if o.m_internal:
DL = mupdf.pdf_to_int(o)
else:
o = mupdf.pdf_dict_getl(fileentry, PDF_NAME('Params'), PDF_NAME('Size'))
if o.m_internal:
DL = mupdf.pdf_to_int(o)
infodict[dictkey_size] = DL
infodict[dictkey_length] = len_
return xref
def _embfile_names(self, namelist):
"""Get list of embedded file names."""
pdf = _as_pdf_document(self)
names = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
if mupdf.pdf_is_array(names):
n = mupdf.pdf_array_len(names)
for i in range(0, n, 2):
val = JM_EscapeStrFromStr(
mupdf.pdf_to_text_string(
mupdf.pdf_array_get(names, i)
)
)
namelist.append(val)
def _embfile_upd(self, idx, buffer_=None, filename=None, ufilename=None, desc=None):
pdf = _as_pdf_document(self)
xref = 0
names = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
entry = mupdf.pdf_array_get(names, 2*idx+1)
filespec = mupdf.pdf_dict_getl(entry, PDF_NAME('EF'), PDF_NAME('F'))
if not filespec.m_internal:
RAISEPY( "bad PDF: no /EF object", JM_Exc_FileDataError)
res = JM_BufferFromBytes(buffer_)
if buffer_ and buffer_.m_internal and not res.m_internal:
raise TypeError( MSG_BAD_BUFFER)
if res.m_internal and buffer_ and buffer_.m_internal:
JM_update_stream(pdf, filespec, res, 1)
# adjust /DL and /Size parameters
len, _ = mupdf.fz_buffer_storage(res)
l = mupdf.pdf_new_int(len)
mupdf.pdf_dict_put(filespec, PDF_NAME('DL'), l)
mupdf.pdf_dict_putl(filespec, l, PDF_NAME('Params'), PDF_NAME('Size'))
xref = mupdf.pdf_to_num(filespec)
if filename:
mupdf.pdf_dict_put_text_string(entry, PDF_NAME('F'), filename)
if ufilename:
mupdf.pdf_dict_put_text_string(entry, PDF_NAME('UF'), ufilename)
if desc:
mupdf.pdf_dict_put_text_string(entry, PDF_NAME('Desc'), desc)
return xref
def _extend_toc_items(self, items):
"""Add color info to all items of an extended TOC list."""
if self.is_closed:
raise ValueError("document closed")
if g_use_extra:
return extra.Document_extend_toc_items( self.this, items)
pdf = _as_pdf_document(self)
zoom = "zoom"
bold = "bold"
italic = "italic"
collapse = "collapse"
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
if not root.m_internal:
return
olroot = mupdf.pdf_dict_get(root, PDF_NAME('Outlines'))
if not olroot.m_internal:
return
first = mupdf.pdf_dict_get(olroot, PDF_NAME('First'))
if not first.m_internal:
return
xrefs = []
xrefs = JM_outline_xrefs(first, xrefs)
n = len(xrefs)
m = len(items)
if not n:
return
if n != m:
raise IndexError( "internal error finding outline xrefs")
# update all TOC item dictionaries
for i in range(n):
xref = int(xrefs[i])
item = items[i]
itemdict = item[3]
if not isinstance(itemdict, dict):
raise ValueError( "need non-simple TOC format")
itemdict[dictkey_xref] = xrefs[i]
bm = mupdf.pdf_load_object(pdf, xref)
flags = mupdf.pdf_to_int( mupdf.pdf_dict_get(bm, PDF_NAME('F')))
if flags == 1:
itemdict[italic] = True
elif flags == 2:
itemdict[bold] = True
elif flags == 3:
itemdict[italic] = True
itemdict[bold] = True
count = mupdf.pdf_to_int( mupdf.pdf_dict_get(bm, PDF_NAME('Count')))
if count < 0:
itemdict[collapse] = True
elif count > 0:
itemdict[collapse] = False
col = mupdf.pdf_dict_get(bm, PDF_NAME('C'))
if mupdf.pdf_is_array(col) and mupdf.pdf_array_len(col) == 3:
color = (
mupdf.pdf_to_real(mupdf.pdf_array_get(col, 0)),
mupdf.pdf_to_real(mupdf.pdf_array_get(col, 1)),
mupdf.pdf_to_real(mupdf.pdf_array_get(col, 2)),
)
itemdict[dictkey_color] = color
z=0
obj = mupdf.pdf_dict_get(bm, PDF_NAME('Dest'))
if not obj.m_internal or not mupdf.pdf_is_array(obj):
obj = mupdf.pdf_dict_getl(bm, PDF_NAME('A'), PDF_NAME('D'))
if mupdf.pdf_is_array(obj) and mupdf.pdf_array_len(obj) == 5:
z = mupdf.pdf_to_real(mupdf.pdf_array_get(obj, 4))
itemdict[zoom] = float(z)
item[3] = itemdict
items[i] = item
def _forget_page(self, page: Page):
"""Remove a page from document page dict."""
pid = id(page)
if pid in self._page_refs:
#self._page_refs[pid] = None
del self._page_refs[pid]
def _get_char_widths(self, xref: int, bfname: str, ext: str, ordering: int, limit: int, idx: int = 0):
pdf = _as_pdf_document(self)
mylimit = limit
if mylimit < 256:
mylimit = 256
if ordering >= 0:
data, size, index = mupdf.fz_lookup_cjk_font(ordering)
font = mupdf.fz_new_font_from_memory(None, data, size, index, 0)
else:
data, size = mupdf.fz_lookup_base14_font(bfname)
if data:
font = mupdf.fz_new_font_from_memory(bfname, data, size, 0, 0)
else:
buf = JM_get_fontbuffer(pdf, xref)
if not buf.m_internal:
raise Exception("font at xref %d is not supported" % xref)
font = mupdf.fz_new_font_from_buffer(None, buf, idx, 0)
wlist = []
for i in range(mylimit):
glyph = mupdf.fz_encode_character(font, i)
adv = mupdf.fz_advance_glyph(font, glyph, 0)
if ordering >= 0:
glyph = i
if glyph > 0:
wlist.append( (glyph, adv))
else:
wlist.append( (glyph, 0.0))
return wlist
def _get_page_labels(self):
pdf = _as_pdf_document(self)
rc = []
pagelabels = mupdf.pdf_new_name("PageLabels")
obj = mupdf.pdf_dict_getl( mupdf.pdf_trailer(pdf), PDF_NAME('Root'), pagelabels)
if not obj.m_internal:
return rc
# simple case: direct /Nums object
nums = mupdf.pdf_resolve_indirect( mupdf.pdf_dict_get( obj, PDF_NAME('Nums')))
if nums.m_internal:
JM_get_page_labels(rc, nums)
return rc
# case: /Kids/Nums
nums = mupdf.pdf_resolve_indirect( mupdf.pdf_dict_getl(obj, PDF_NAME('Kids'), PDF_NAME('Nums')))
if nums.m_internal:
JM_get_page_labels(rc, nums)
return rc
# case: /Kids is an array of multiple /Nums
kids = mupdf.pdf_resolve_indirect( mupdf.pdf_dict_get( obj, PDF_NAME('Kids')))
if not kids.m_internal or not mupdf.pdf_is_array(kids):
return rc
n = mupdf.pdf_array_len(kids)
for i in range(n):
nums = mupdf.pdf_resolve_indirect(
mupdf.pdf_dict_get(
mupdf.pdf_array_get(kids, i),
PDF_NAME('Nums'),
)
)
JM_get_page_labels(rc, nums)
return rc
def _getMetadata(self, key):
"""Get metadata."""
try:
return mupdf.fz_lookup_metadata2( self.this, key)
except Exception:
if g_exceptions_verbose > 2: exception_info()
return ''
def _getOLRootNumber(self):
"""Get xref of Outline Root, create it if missing."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
# get main root
root = mupdf.pdf_dict_get( mupdf.pdf_trailer( pdf), PDF_NAME('Root'))
# get outline root
olroot = mupdf.pdf_dict_get( root, PDF_NAME('Outlines'))
if not olroot.m_internal:
olroot = mupdf.pdf_new_dict( pdf, 4)
mupdf.pdf_dict_put( olroot, PDF_NAME('Type'), PDF_NAME('Outlines'))
ind_obj = mupdf.pdf_add_object( pdf, olroot)
mupdf.pdf_dict_put( root, PDF_NAME('Outlines'), ind_obj)
olroot = mupdf.pdf_dict_get( root, PDF_NAME('Outlines'))
return mupdf.pdf_to_num( olroot)
def _getPDFfileid(self):
"""Get PDF file id."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return
idlist = []
identity = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('ID'))
if identity.m_internal:
n = mupdf.pdf_array_len(identity)
for i in range(n):
o = mupdf.pdf_array_get(identity, i)
text = mupdf.pdf_to_text_string(o)
hex_ = binascii.hexlify(text)
idlist.append(hex_)
return idlist
def _getPageInfo(self, pno, what):
"""List fonts, images, XObjects used on a page."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
doc = self.this
pageCount = mupdf.pdf_count_pages(doc) if isinstance(doc, mupdf.PdfDocument) else mupdf.fz_count_pages(doc)
n = pno # pno < 0 is allowed
while n < 0:
n += pageCount # make it non-negative
if n >= pageCount:
raise ValueError( MSG_BAD_PAGENO)
pdf = _as_pdf_document(self)
pageref = mupdf.pdf_lookup_page_obj(pdf, n)
rsrc = mupdf.pdf_dict_get_inheritable(pageref, mupdf.PDF_ENUM_NAME_Resources)
liste = []
tracer = []
if rsrc.m_internal:
JM_scan_resources(pdf, rsrc, liste, what, 0, tracer)
return liste
def _insert_font(self, fontfile=None, fontbuffer=None):
'''
Utility: insert font from file or binary.
'''
pdf = _as_pdf_document(self)
if not fontfile and not fontbuffer:
raise ValueError( MSG_FILE_OR_BUFFER)
value = JM_insert_font(pdf, None, fontfile, fontbuffer, 0, 0, 0, 0, 0, -1)
return value
def _loadOutline(self):
"""Load first outline."""
doc = self.this
assert isinstance( doc, mupdf.FzDocument)
try:
ol = mupdf.fz_load_outline( doc)
except Exception:
if g_exceptions_verbose > 1: exception_info()
return
return Outline( ol)
def _make_page_map(self):
"""Make an array page number -> page object."""
if self.is_closed:
raise ValueError("document closed")
assert 0, f'_make_page_map() is no-op'
def _move_copy_page(self, pno, nb, before, copy):
"""Move or copy a PDF page reference."""
pdf = _as_pdf_document(self)
same = 0
# get the two page objects -----------------------------------
# locate the /Kids arrays and indices in each
page1, parent1, i1 = pdf_lookup_page_loc( pdf, pno)
kids1 = mupdf.pdf_dict_get( parent1, PDF_NAME('Kids'))
page2, parent2, i2 = pdf_lookup_page_loc( pdf, nb)
kids2 = mupdf.pdf_dict_get( parent2, PDF_NAME('Kids'))
if before: # calc index of source page in target /Kids
pos = i2
else:
pos = i2 + 1
# same /Kids array? ------------------------------------------
same = mupdf.pdf_objcmp( kids1, kids2)
# put source page in target /Kids array ----------------------
if not copy and same != 0: # update parent in page object
mupdf.pdf_dict_put( page1, PDF_NAME('Parent'), parent2)
mupdf.pdf_array_insert( kids2, page1, pos)
if same != 0: # different /Kids arrays ----------------------
parent = parent2
while parent.m_internal: # increase /Count objects in parents
count = mupdf.pdf_dict_get_int( parent, PDF_NAME('Count'))
mupdf.pdf_dict_put_int( parent, PDF_NAME('Count'), count + 1)
parent = mupdf.pdf_dict_get( parent, PDF_NAME('Parent'))
if not copy: # delete original item
mupdf.pdf_array_delete( kids1, i1)
parent = parent1
while parent.m_internal: # decrease /Count objects in parents
count = mupdf.pdf_dict_get_int( parent, PDF_NAME('Count'))
mupdf.pdf_dict_put_int( parent, PDF_NAME('Count'), count - 1)
parent = mupdf.pdf_dict_get( parent, PDF_NAME('Parent'))
else: # same /Kids array
if copy: # source page is copied
parent = parent2
while parent.m_internal: # increase /Count object in parents
count = mupdf.pdf_dict_get_int( parent, PDF_NAME('Count'))
mupdf.pdf_dict_put_int( parent, PDF_NAME('Count'), count + 1)
parent = mupdf.pdf_dict_get( parent, PDF_NAME('Parent'))
else:
if i1 < pos:
mupdf.pdf_array_delete( kids1, i1)
else:
mupdf.pdf_array_delete( kids1, i1 + 1)
if pdf.m_internal.rev_page_map: # page map no longer valid: drop it
mupdf.ll_pdf_drop_page_tree( pdf.m_internal)
self._reset_page_refs()
def _newPage(self, pno=-1, width=595, height=842):
"""Make a new PDF page."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if g_use_extra:
extra._newPage( self.this, pno, width, height)
else:
pdf = _as_pdf_document(self)
mediabox = mupdf.FzRect(mupdf.FzRect.Fixed_UNIT)
mediabox.x1 = width
mediabox.y1 = height
contents = mupdf.FzBuffer()
if pno < -1:
raise ValueError( MSG_BAD_PAGENO)
# create /Resources and /Contents objects
#resources = pdf.add_object(pdf.new_dict(1))
resources = mupdf.pdf_add_new_dict(pdf, 1)
page_obj = mupdf.pdf_add_page( pdf, mediabox, 0, resources, contents)
mupdf.pdf_insert_page( pdf, pno, page_obj)
# fixme: pdf->dirty = 1;
self._reset_page_refs()
return self[pno]
def _remove_links_to(self, numbers):
pdf = _as_pdf_document(self)
_remove_dest_range(pdf, numbers)
def _remove_toc_item(self, xref):
# "remove" bookmark by letting it point to nowhere
pdf = _as_pdf_document(self)
item = mupdf.pdf_new_indirect(pdf, xref, 0)
mupdf.pdf_dict_del( item, PDF_NAME('Dest'))
mupdf.pdf_dict_del( item, PDF_NAME('A'))
color = mupdf.pdf_new_array( pdf, 3)
for i in range(3):
mupdf.pdf_array_push_real( color, 0.8)
mupdf.pdf_dict_put( item, PDF_NAME('C'), color)
def _reset_page_refs(self):
"""Invalidate all pages in document dictionary."""
if getattr(self, "is_closed", True):
return
pages = [p for p in self._page_refs.values()]
for page in pages:
if page:
page._erase()
page = None
self._page_refs.clear()
def _set_page_labels(self, labels):
pdf = _as_pdf_document(self)
pagelabels = mupdf.pdf_new_name("PageLabels")
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
mupdf.pdf_dict_del(root, pagelabels)
mupdf.pdf_dict_putl(root, mupdf.pdf_new_array(pdf, 0), pagelabels, PDF_NAME('Nums'))
xref = self.pdf_catalog()
text = self.xref_object(xref, compressed=True)
text = text.replace("/Nums[]", "/Nums[%s]" % labels)
self.update_object(xref, text)
def _update_toc_item(self, xref, action=None, title=None, flags=0, collapse=None, color=None):
'''
"update" bookmark by letting it point to nowhere
'''
pdf = _as_pdf_document(self)
item = mupdf.pdf_new_indirect( pdf, xref, 0)
if title:
mupdf.pdf_dict_put_text_string( item, PDF_NAME('Title'), title)
if action:
mupdf.pdf_dict_del( item, PDF_NAME('Dest'))
obj = JM_pdf_obj_from_str( pdf, action)
mupdf.pdf_dict_put( item, PDF_NAME('A'), obj)
mupdf.pdf_dict_put_int( item, PDF_NAME('F'), flags)
if color:
c = mupdf.pdf_new_array( pdf, 3)
for i in range(3):
f = color[i]
mupdf.pdf_array_push_real( c, f)
mupdf.pdf_dict_put( item, PDF_NAME('C'), c)
elif color is not None:
mupdf.pdf_dict_del( item, PDF_NAME('C'))
if collapse is not None:
if mupdf.pdf_dict_get( item, PDF_NAME('Count')).m_internal:
i = mupdf.pdf_dict_get_int( item, PDF_NAME('Count'))
if (i < 0 and collapse is False) or (i > 0 and collapse is True):
i = i * (-1)
mupdf.pdf_dict_put_int( item, PDF_NAME('Count'), i)
@property
def FormFonts(self):
"""Get list of field font resource names."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return
fonts = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('AcroForm'),
PDF_NAME('DR'),
PDF_NAME('Font'),
)
liste = list()
if fonts.m_internal and mupdf.pdf_is_dict(fonts): # fonts exist
n = mupdf.pdf_dict_len(fonts)
for i in range(n):
f = mupdf.pdf_dict_get_key(fonts, i)
liste.append(JM_UnicodeFromStr(mupdf.pdf_to_name(f)))
return liste
def add_layer(self, name, creator=None, on=None):
"""Add a new OC layer."""
pdf = _as_pdf_document(self)
JM_add_layer_config( pdf, name, creator, on)
mupdf.ll_pdf_read_ocg( pdf.m_internal)
def add_ocg(self, name, config=-1, on=1, intent=None, usage=None):
"""Add new optional content group."""
xref = 0
pdf = _as_pdf_document(self)
# make the OCG
ocg = mupdf.pdf_add_new_dict(pdf, 3)
mupdf.pdf_dict_put(ocg, PDF_NAME('Type'), PDF_NAME('OCG'))
mupdf.pdf_dict_put_text_string(ocg, PDF_NAME('Name'), name)
intents = mupdf.pdf_dict_put_array(ocg, PDF_NAME('Intent'), 2)
if not intent:
mupdf.pdf_array_push(intents, PDF_NAME('View'))
elif not isinstance(intent, str):
assert 0, f'fixme: intent is not a str. {type(intent)=} {type=}'
#n = len(intent)
#for i in range(n):
# item = intent[i]
# c = JM_StrAsChar(item);
# if (c) {
# pdf_array_push(gctx, intents, pdf_new_name(gctx, c));
# }
# Py_DECREF(item);
#}
else:
mupdf.pdf_array_push(intents, mupdf.pdf_new_name(intent))
use_for = mupdf.pdf_dict_put_dict(ocg, PDF_NAME('Usage'), 3)
ci_name = mupdf.pdf_new_name("CreatorInfo")
cre_info = mupdf.pdf_dict_put_dict(use_for, ci_name, 2)
mupdf.pdf_dict_put_text_string(cre_info, PDF_NAME('Creator'), "PyMuPDF")
if usage:
mupdf.pdf_dict_put_name(cre_info, PDF_NAME('Subtype'), usage)
else:
mupdf.pdf_dict_put_name(cre_info, PDF_NAME('Subtype'), "Artwork")
indocg = mupdf.pdf_add_object(pdf, ocg)
# Insert OCG in the right config
ocp = JM_ensure_ocproperties(pdf)
obj = mupdf.pdf_dict_get(ocp, PDF_NAME('OCGs'))
mupdf.pdf_array_push(obj, indocg)
if config > -1:
obj = mupdf.pdf_dict_get(ocp, PDF_NAME('Configs'))
if not mupdf.pdf_is_array(obj):
raise ValueError( MSG_BAD_OC_CONFIG)
cfg = mupdf.pdf_array_get(obj, config)
if not cfg.m_internal:
raise ValueError( MSG_BAD_OC_CONFIG)
else:
cfg = mupdf.pdf_dict_get(ocp, PDF_NAME('D'))
obj = mupdf.pdf_dict_get(cfg, PDF_NAME('Order'))
if not obj.m_internal:
obj = mupdf.pdf_dict_put_array(cfg, PDF_NAME('Order'), 1)
mupdf.pdf_array_push(obj, indocg)
if on:
obj = mupdf.pdf_dict_get(cfg, PDF_NAME('ON'))
if not obj.m_internal:
obj = mupdf.pdf_dict_put_array(cfg, PDF_NAME('ON'), 1)
else:
obj =mupdf.pdf_dict_get(cfg, PDF_NAME('OFF'))
if not obj.m_internal:
obj =mupdf.pdf_dict_put_array(cfg, PDF_NAME('OFF'), 1)
mupdf.pdf_array_push(obj, indocg)
# let MuPDF take note: re-read OCProperties
mupdf.ll_pdf_read_ocg(pdf.m_internal)
xref = mupdf.pdf_to_num(indocg)
return xref
def authenticate(self, password):
"""Decrypt document."""
if self.is_closed:
raise ValueError("document closed")
val = mupdf.fz_authenticate_password(self.this, password)
if val: # the doc is decrypted successfully and we init the outline
self.is_encrypted = False
self.is_encrypted = False
self.init_doc()
self.thisown = True
return val
def can_save_incrementally(self):
"""Check whether incremental saves are possible."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return False
return mupdf.pdf_can_be_saved_incrementally(pdf)
def bake(self, *, annots: bool = True, widgets: bool = True) -> None:
"""Convert annotations or fields to permanent content.
Notes:
Converts annotations or widgets to permanent page content, like
text and vector graphics, as appropriate.
After execution, pages will still look the same, but no longer
have annotations, respectively no fields.
If widgets are selected the PDF will no longer be a Form PDF.
Args:
annots: convert annotations
widgets: convert form fields
"""
pdf = _as_pdf_document(self)
mupdf.pdf_bake_document(pdf, int(annots), int(widgets))
@property
def chapter_count(self):
"""Number of chapters."""
if self.is_closed:
raise ValueError("document closed")
return mupdf.fz_count_chapters( self.this)
def chapter_page_count(self, chapter):
"""Page count of chapter."""
if self.is_closed:
raise ValueError("document closed")
chapters = mupdf.fz_count_chapters( self.this)
if chapter < 0 or chapter >= chapters:
raise ValueError( "bad chapter number")
pages = mupdf.fz_count_chapter_pages( self.this, chapter)
return pages
def close(self):
"""Close document."""
if getattr(self, "is_closed", True):
raise ValueError("document closed")
# self._cleanup()
if hasattr(self, "_outline") and self._outline:
self._outline = None
self._reset_page_refs()
#self.metadata = None
#self.stream = None
self.is_closed = True
#self.FontInfos = []
self.Graftmaps = {} # Fixes test_3140().
#self.ShownPages = {}
#self.InsertedImages = {}
#self.this = None
self.this = None
def convert_to_pdf(self, from_page=0, to_page=-1, rotate=0):
"""Convert document to a PDF, selecting page range and optional rotation. Output bytes object."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
fz_doc = self.this
fp = from_page
tp = to_page
srcCount = mupdf.fz_count_pages(fz_doc)
if fp < 0:
fp = 0
if fp > srcCount - 1:
fp = srcCount - 1
if tp < 0:
tp = srcCount - 1
if tp > srcCount - 1:
tp = srcCount - 1
len0 = len(JM_mupdf_warnings_store)
doc = JM_convert_to_pdf(fz_doc, fp, tp, rotate)
len1 = len(JM_mupdf_warnings_store)
for i in range(len0, len1):
message(f'{JM_mupdf_warnings_store[i]}')
return doc
def copy_page(self, pno: int, to: int =-1):
"""Copy a page within a PDF document.
This will only create another reference of the same page object.
Args:
pno: source page number
to: put before this page, '-1' means after last page.
"""
if self.is_closed:
raise ValueError("document closed")
page_count = len(self)
if (
pno not in range(page_count)
or to not in range(-1, page_count)
):
raise ValueError("bad page number(s)")
before = 1
copy = 1
if to == -1:
to = page_count - 1
before = 0
return self._move_copy_page(pno, to, before, copy)
def del_xml_metadata(self):
"""Delete XML metadata."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
root = mupdf.pdf_dict_get( mupdf.pdf_trailer( pdf), PDF_NAME('Root'))
if root.m_internal:
mupdf.pdf_dict_del( root, PDF_NAME('Metadata'))
def delete_page(self, pno: int =-1):
""" Delete one page from a PDF.
"""
return self.delete_pages(pno)
def delete_pages(self, *args, **kw):
"""Delete pages from a PDF.
Args:
Either keywords 'from_page'/'to_page', or two integers to
specify the first/last page to delete.
Or a list/tuple/range object, which can contain arbitrary
page numbers.
Or a single integer page number.
"""
if not self.is_pdf:
raise ValueError("is no PDF")
if self.is_closed:
raise ValueError("document closed")
page_count = self.page_count # page count of document
f = t = -1
if kw: # check if keywords were used
if args: # then no positional args are allowed
raise ValueError("cannot mix keyword and positional argument")
f = kw.get("from_page", -1) # first page to delete
t = kw.get("to_page", -1) # last page to delete
while f < 0:
f += page_count
while t < 0:
t += page_count
if not f <= t < page_count:
raise ValueError("bad page number(s)")
numbers = tuple(range(f, t + 1))
else:
if len(args) > 2 or args == []:
raise ValueError("need 1 or 2 positional arguments")
if len(args) == 2:
f, t = args
if not (type(f) is int and type(t) is int):
raise ValueError("both arguments must be int")
if f > t:
f, t = t, f
if not f <= t < page_count:
raise ValueError("bad page number(s)")
numbers = tuple(range(f, t + 1))
elif isinstance(args[0], int):
pno = args[0]
while pno < 0:
pno += page_count
numbers = (pno,)
else:
numbers = tuple(args[0])
numbers = list(map(int, set(numbers))) # ensure unique integers
if numbers == []:
message("nothing to delete")
return
numbers.sort()
if numbers[0] < 0 or numbers[-1] >= page_count:
raise ValueError("bad page number(s)")
frozen_numbers = frozenset(numbers)
toc = self.get_toc()
for i, xref in enumerate(self.get_outline_xrefs()):
if toc[i][2] - 1 in frozen_numbers:
self._remove_toc_item(xref) # remove target in PDF object
self._remove_links_to(frozen_numbers)
for i in reversed(numbers): # delete pages, last to first
self._delete_page(i)
self._reset_page_refs()
def embfile_add(self,
name: str,
buffer_: ByteString,
filename: OptStr =None,
ufilename: OptStr =None,
desc: OptStr =None,
) -> None:
"""Add an item to the EmbeddedFiles array.
Args:
name: name of the new item, must not already exist.
buffer_: (binary data) the file content.
filename: (str) the file name, default: the name
ufilename: (unicode) the file name, default: filename
desc: (str) the description.
"""
filenames = self.embfile_names()
msg = "Name '%s' already exists." % str(name)
if name in filenames:
raise ValueError(msg)
if filename is None:
filename = name
if ufilename is None:
ufilename = filename
if desc is None:
desc = name
xref = self._embfile_add(
name,
buffer_=buffer_,
filename=filename,
ufilename=ufilename,
desc=desc,
)
date = get_pdf_now()
self.xref_set_key(xref, "Type", "/EmbeddedFile")
self.xref_set_key(xref, "Params/CreationDate", get_pdf_str(date))
self.xref_set_key(xref, "Params/ModDate", get_pdf_str(date))
return xref
def embfile_count(self) -> int:
"""Get number of EmbeddedFiles."""
return len(self.embfile_names())
def embfile_del(self, item: typing.Union[int, str]):
"""Delete an entry from EmbeddedFiles.
Notes:
The argument must be name or index of an EmbeddedFiles item.
Physical deletion of data will happen on save to a new
file with appropriate garbage option.
Args:
item: name or number of item.
Returns:
None
"""
idx = self._embeddedFileIndex(item)
return self._embfile_del(idx)
def embfile_get(self, item: typing.Union[int, str]) -> bytes:
"""Get the content of an item in the EmbeddedFiles array.
Args:
item: number or name of item.
Returns:
(bytes) The file content.
"""
idx = self._embeddedFileIndex(item)
return self._embeddedFileGet(idx)
def embfile_info(self, item: typing.Union[int, str]) -> dict:
"""Get information of an item in the EmbeddedFiles array.
Args:
item: number or name of item.
Returns:
Information dictionary.
"""
idx = self._embeddedFileIndex(item)
infodict = {"name": self.embfile_names()[idx]}
xref = self._embfile_info(idx, infodict)
t, date = self.xref_get_key(xref, "Params/CreationDate")
if t != "null":
infodict["creationDate"] = date
t, date = self.xref_get_key(xref, "Params/ModDate")
if t != "null":
infodict["modDate"] = date
t, md5 = self.xref_get_key(xref, "Params/CheckSum")
if t != "null":
infodict["checksum"] = binascii.hexlify(md5.encode()).decode()
return infodict
def embfile_names(self) -> list:
"""Get list of names of EmbeddedFiles."""
filenames = []
self._embfile_names(filenames)
return filenames
def embfile_upd(self,
item: typing.Union[int, str],
buffer_: OptBytes =None,
filename: OptStr =None,
ufilename: OptStr =None,
desc: OptStr =None,
) -> None:
"""Change an item of the EmbeddedFiles array.
Notes:
Only provided parameters are changed. If all are omitted,
the method is a no-op.
Args:
item: number or name of item.
buffer_: (binary data) the new file content.
filename: (str) the new file name.
ufilename: (unicode) the new filen ame.
desc: (str) the new description.
"""
idx = self._embeddedFileIndex(item)
xref = self._embfile_upd(
idx,
buffer_=buffer_,
filename=filename,
ufilename=ufilename,
desc=desc,
)
date = get_pdf_now()
self.xref_set_key(xref, "Params/ModDate", get_pdf_str(date))
return xref
def extract_font(self, xref=0, info_only=0, named=None):
'''
Get a font by xref. Returns a tuple or dictionary.
'''
#log( '{=xref info_only}')
pdf = _as_pdf_document(self)
obj = mupdf.pdf_load_object(pdf, xref)
type_ = mupdf.pdf_dict_get(obj, PDF_NAME('Type'))
subtype = mupdf.pdf_dict_get(obj, PDF_NAME('Subtype'))
if (mupdf.pdf_name_eq(type_, PDF_NAME('Font'))
and not mupdf.pdf_to_name( subtype).startswith('CIDFontType')
):
basefont = mupdf.pdf_dict_get(obj, PDF_NAME('BaseFont'))
if not basefont.m_internal or mupdf.pdf_is_null(basefont):
bname = mupdf.pdf_dict_get(obj, PDF_NAME('Name'))
else:
bname = basefont
ext = JM_get_fontextension(pdf, xref)
if ext != 'n/a' and not info_only:
buffer_ = JM_get_fontbuffer(pdf, xref)
bytes_ = JM_BinFromBuffer(buffer_)
else:
bytes_ = b''
if not named:
rc = (
JM_EscapeStrFromStr(mupdf.pdf_to_name(bname)),
JM_UnicodeFromStr(ext),
JM_UnicodeFromStr(mupdf.pdf_to_name(subtype)),
bytes_,
)
else:
rc = {
dictkey_name: JM_EscapeStrFromStr(mupdf.pdf_to_name(bname)),
dictkey_ext: JM_UnicodeFromStr(ext),
dictkey_type: JM_UnicodeFromStr(mupdf.pdf_to_name(subtype)),
dictkey_content: bytes_,
}
else:
if not named:
rc = '', '', '', b''
else:
rc = {
dictkey_name: '',
dictkey_ext: '',
dictkey_type: '',
dictkey_content: b'',
}
return rc
def extract_image(self, xref):
"""Get image by xref. Returns a dictionary."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
if not _INRANGE(xref, 1, mupdf.pdf_xref_len(pdf)-1):
raise ValueError( MSG_BAD_XREF)
obj = mupdf.pdf_new_indirect(pdf, xref, 0)
subtype = mupdf.pdf_dict_get(obj, PDF_NAME('Subtype'))
if not mupdf.pdf_name_eq(subtype, PDF_NAME('Image')):
raise ValueError( "not an image")
o = mupdf.pdf_dict_geta(obj, PDF_NAME('SMask'), PDF_NAME('Mask'))
if o.m_internal:
smask = mupdf.pdf_to_num(o)
else:
smask = 0
# load the image
img = mupdf.pdf_load_image(pdf, obj)
rc = dict()
_make_image_dict(img, rc)
rc[dictkey_smask] = smask
rc[dictkey_cs_name] = mupdf.fz_colorspace_name(img.colorspace())
return rc
def ez_save(
self,
filename,
garbage=3,
clean=False,
deflate=True,
deflate_images=True,
deflate_fonts=True,
incremental=False,
ascii=False,
expand=False,
linear=False,
pretty=False,
encryption=1,
permissions=4095,
owner_pw=None,
user_pw=None,
no_new_id=True,
preserve_metadata=1,
use_objstms=1,
compression_effort=0,
):
'''
Save PDF using some different defaults
'''
return self.save(
filename,
garbage=garbage,
clean=clean,
deflate=deflate,
deflate_images=deflate_images,
deflate_fonts=deflate_fonts,
incremental=incremental,
ascii=ascii,
expand=expand,
linear=linear,
pretty=pretty,
encryption=encryption,
permissions=permissions,
owner_pw=owner_pw,
user_pw=user_pw,
no_new_id=no_new_id,
preserve_metadata=preserve_metadata,
use_objstms=use_objstms,
compression_effort=compression_effort,
)
def find_bookmark(self, bm):
"""Find new location after layouting a document."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
location = mupdf.fz_lookup_bookmark2( self.this, bm)
return location.chapter, location.page
def fullcopy_page(self, pno, to=-1):
"""Make a full page duplicate."""
pdf = _as_pdf_document(self)
page_count = mupdf.pdf_count_pages( pdf)
try:
if (not _INRANGE(pno, 0, page_count - 1)
or not _INRANGE(to, -1, page_count - 1)
):
raise ValueError( MSG_BAD_PAGENO)
page1 = mupdf.pdf_resolve_indirect( mupdf.pdf_lookup_page_obj( pdf, pno))
page2 = mupdf.pdf_deep_copy_obj( page1)
old_annots = mupdf.pdf_dict_get( page2, PDF_NAME('Annots'))
# copy annotations, but remove Popup and IRT types
if old_annots.m_internal:
n = mupdf.pdf_array_len( old_annots)
new_annots = mupdf.pdf_new_array( pdf, n)
for i in range(n):
o = mupdf.pdf_array_get( old_annots, i)
subtype = mupdf.pdf_dict_get( o, PDF_NAME('Subtype'))
if mupdf.pdf_name_eq( subtype, PDF_NAME('Popup')):
continue
if mupdf.pdf_dict_gets( o, "IRT").m_internal:
continue
copy_o = mupdf.pdf_deep_copy_obj( mupdf.pdf_resolve_indirect( o))
xref = mupdf.pdf_create_object( pdf)
mupdf.pdf_update_object( pdf, xref, copy_o)
copy_o = mupdf.pdf_new_indirect( pdf, xref, 0)
mupdf.pdf_dict_del( copy_o, PDF_NAME('Popup'))
mupdf.pdf_dict_del( copy_o, PDF_NAME('P'))
mupdf.pdf_array_push( new_annots, copy_o)
mupdf.pdf_dict_put( page2, PDF_NAME('Annots'), new_annots)
# copy the old contents stream(s)
res = JM_read_contents( page1)
# create new /Contents object for page2
if res and res.m_internal:
#contents = mupdf.pdf_add_stream( pdf, mupdf.fz_new_buffer_from_copied_data( b" ", 1), NULL, 0)
contents = mupdf.pdf_add_stream( pdf, mupdf.fz_new_buffer_from_copied_data( b" "), mupdf.PdfObj(), 0)
JM_update_stream( pdf, contents, res, 1)
mupdf.pdf_dict_put( page2, PDF_NAME('Contents'), contents)
# now insert target page, making sure it is an indirect object
xref = mupdf.pdf_create_object( pdf) # get new xref
mupdf.pdf_update_object( pdf, xref, page2) # store new page
page2 = mupdf.pdf_new_indirect( pdf, xref, 0) # reread object
mupdf.pdf_insert_page( pdf, to, page2) # and store the page
finally:
mupdf.ll_pdf_drop_page_tree( pdf.m_internal)
self._reset_page_refs()
def get_char_widths(
doc: 'Document',
xref: int,
limit: int = 256,
idx: int = 0,
fontdict: OptDict = None,
) -> list:
"""Get list of glyph information of a font.
Notes:
Must be provided by its XREF number. If we already dealt with the
font, it will be recorded in doc.FontInfos. Otherwise we insert an
entry there.
Finally we return the glyphs for the font. This is a list of
(glyph, width) where glyph is an integer controlling the char
appearance, and width is a float controlling the char's spacing:
width * fontsize is the actual space.
For 'simple' fonts, glyph == ord(char) will usually be true.
Exceptions are 'Symbol' and 'ZapfDingbats'. We are providing data for these directly here.
"""
fontinfo = CheckFontInfo(doc, xref)
if fontinfo is None: # not recorded yet: create it
if fontdict is None:
name, ext, stype, asc, dsc = utils._get_font_properties(doc, xref)
fontdict = {
"name": name,
"type": stype,
"ext": ext,
"ascender": asc,
"descender": dsc,
}
else:
name = fontdict["name"]
ext = fontdict["ext"]
stype = fontdict["type"]
ordering = fontdict["ordering"]
simple = fontdict["simple"]
if ext == "":
raise ValueError("xref is not a font")
# check for 'simple' fonts
if stype in ("Type1", "MMType1", "TrueType"):
simple = True
else:
simple = False
# check for CJK fonts
if name in ("Fangti", "Ming"):
ordering = 0
elif name in ("Heiti", "Song"):
ordering = 1
elif name in ("Gothic", "Mincho"):
ordering = 2
elif name in ("Dotum", "Batang"):
ordering = 3
else:
ordering = -1
fontdict["simple"] = simple
if name == "ZapfDingbats":
glyphs = zapf_glyphs
elif name == "Symbol":
glyphs = symbol_glyphs
else:
glyphs = None
fontdict["glyphs"] = glyphs
fontdict["ordering"] = ordering
fontinfo = [xref, fontdict]
doc.FontInfos.append(fontinfo)
else:
fontdict = fontinfo[1]
glyphs = fontdict["glyphs"]
simple = fontdict["simple"]
ordering = fontdict["ordering"]
if glyphs is None:
oldlimit = 0
else:
oldlimit = len(glyphs)
mylimit = max(256, limit)
if mylimit <= oldlimit:
return glyphs
if ordering < 0: # not a CJK font
glyphs = doc._get_char_widths(
xref, fontdict["name"], fontdict["ext"], fontdict["ordering"], mylimit, idx
)
else: # CJK fonts use char codes and width = 1
glyphs = None
fontdict["glyphs"] = glyphs
fontinfo[1] = fontdict
UpdateFontInfo(doc, fontinfo)
return glyphs
def get_layer(self, config=-1):
"""Content of ON, OFF, RBGroups of an OC layer."""
pdf = _as_pdf_document(self)
ocp = mupdf.pdf_dict_getl(
mupdf.pdf_trailer( pdf),
PDF_NAME('Root'),
PDF_NAME('OCProperties'),
)
if not ocp.m_internal:
return
if config == -1:
obj = mupdf.pdf_dict_get( ocp, PDF_NAME('D'))
else:
obj = mupdf.pdf_array_get(
mupdf.pdf_dict_get( ocp, PDF_NAME('Configs')),
config,
)
if not obj.m_internal:
raise ValueError( MSG_BAD_OC_CONFIG)
rc = JM_get_ocg_arrays( obj)
return rc
def get_layers(self):
"""Show optional OC layers."""
pdf = _as_pdf_document(self)
n = mupdf.pdf_count_layer_configs( pdf)
if n == 1:
obj = mupdf.pdf_dict_getl(
mupdf.pdf_trailer( pdf),
PDF_NAME('Root'),
PDF_NAME('OCProperties'),
PDF_NAME('Configs'),
)
if not mupdf.pdf_is_array( obj):
n = 0
rc = []
info = mupdf.PdfLayerConfig()
for i in range(n):
mupdf.pdf_layer_config_info( pdf, i, info)
item = {
"number": i,
"name": info.name,
"creator": info.creator,
}
rc.append( item)
return rc
def get_new_xref(self):
"""Make new xref."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
xref = 0
ENSURE_OPERATION(pdf)
xref = mupdf.pdf_create_object(pdf)
return xref
def get_oc(doc: 'Document', xref: int) -> int:
"""Return optional content object xref for an image or form xobject.
Args:
xref: (int) xref number of an image or form xobject.
"""
if doc.is_closed or doc.is_encrypted:
raise ValueError("document close or encrypted")
t, name = doc.xref_get_key(xref, "Subtype")
if t != "name" or name not in ("/Image", "/Form"):
raise ValueError("bad object type at xref %i" % xref)
t, oc = doc.xref_get_key(xref, "OC")
if t != "xref":
return 0
rc = int(oc.replace("0 R", ""))
return rc
def get_ocgs(self):
"""Show existing optional content groups."""
ci = mupdf.pdf_new_name( "CreatorInfo")
pdf = _as_pdf_document(self)
ocgs = mupdf.pdf_dict_getl(
mupdf.pdf_dict_get( mupdf.pdf_trailer( pdf), PDF_NAME('Root')),
PDF_NAME('OCProperties'),
PDF_NAME('OCGs'),
)
rc = dict()
if not mupdf.pdf_is_array( ocgs):
return rc
n = mupdf.pdf_array_len( ocgs)
for i in range(n):
ocg = mupdf.pdf_array_get( ocgs, i)
xref = mupdf.pdf_to_num( ocg)
name = mupdf.pdf_to_text_string( mupdf.pdf_dict_get( ocg, PDF_NAME('Name')))
obj = mupdf.pdf_dict_getl( ocg, PDF_NAME('Usage'), ci, PDF_NAME('Subtype'))
usage = None
if obj.m_internal:
usage = mupdf.pdf_to_name( obj)
intents = list()
intent = mupdf.pdf_dict_get( ocg, PDF_NAME('Intent'))
if intent.m_internal:
if mupdf.pdf_is_name( intent):
intents.append( mupdf.pdf_to_name( intent))
elif mupdf.pdf_is_array( intent):
m = mupdf.pdf_array_len( intent)
for j in range(m):
o = mupdf.pdf_array_get( intent, j)
if mupdf.pdf_is_name( o):
intents.append( mupdf.pdf_to_name( o))
if mupdf_version_tuple >= (1, 26, 11):
resource_stack = mupdf.PdfResourceStack()
hidden = mupdf.pdf_is_ocg_hidden( pdf, resource_stack, usage, ocg)
else:
hidden = mupdf.pdf_is_ocg_hidden( pdf, mupdf.PdfObj(), usage, ocg)
item = {
"name": name,
"intent": intents,
"on": not hidden,
"usage": usage,
}
temp = xref
rc[ temp] = item
return rc
def get_ocmd(doc: 'Document', xref: int) -> dict:
"""Return the definition of an OCMD (optional content membership dictionary).
Recognizes PDF dict keys /OCGs (PDF array of OCGs), /P (policy string) and
/VE (visibility expression, PDF array). Via string manipulation, this
info is converted to a Python dictionary with keys "xref", "ocgs", "policy"
and "ve" - ready to recycle as input for 'set_ocmd()'.
"""
if xref not in range(doc.xref_length()):
raise ValueError("bad xref")
text = doc.xref_object(xref, compressed=True)
if "/Type/OCMD" not in text:
raise ValueError("bad object type")
textlen = len(text)
p0 = text.find("/OCGs[") # look for /OCGs key
p1 = text.find("]", p0)
if p0 < 0 or p1 < 0: # no OCGs found
ocgs = None
else:
ocgs = text[p0 + 6 : p1].replace("0 R", " ").split()
ocgs = list(map(int, ocgs))
p0 = text.find("/P/") # look for /P policy key
if p0 < 0:
policy = None
else:
p1 = text.find("ff", p0)
if p1 < 0:
p1 = text.find("on", p0)
if p1 < 0: # some irregular syntax
raise ValueError("bad object at xref")
else:
policy = text[p0 + 3 : p1 + 2]
p0 = text.find("/VE[") # look for /VE visibility expression key
if p0 < 0: # no visibility expression found
ve = None
else:
lp = rp = 0 # find end of /VE by finding last ']'.
p1 = p0
while lp < 1 or lp != rp:
p1 += 1
if not p1 < textlen: # some irregular syntax
raise ValueError("bad object at xref")
if text[p1] == "[":
lp += 1
if text[p1] == "]":
rp += 1
# p1 now positioned at the last "]"
ve = text[p0 + 3 : p1 + 1] # the PDF /VE array
ve = (
ve.replace("/And", '"and",')
.replace("/Not", '"not",')
.replace("/Or", '"or",')
)
ve = ve.replace(" 0 R]", "]").replace(" 0 R", ",").replace("][", "],[")
import json
try:
ve = json.loads(ve)
except Exception:
exception_info()
message(f"bad /VE key: {ve!r}")
raise
return {"xref": xref, "ocgs": ocgs, "policy": policy, "ve": ve}
def get_outline_xrefs(self):
"""Get list of outline xref numbers."""
xrefs = []
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return xrefs
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
if not root.m_internal:
return xrefs
olroot = mupdf.pdf_dict_get(root, PDF_NAME('Outlines'))
if not olroot.m_internal:
return xrefs
first = mupdf.pdf_dict_get(olroot, PDF_NAME('First'))
if not first.m_internal:
return xrefs
xrefs = JM_outline_xrefs(first, xrefs)
return xrefs
def get_page_fonts(self, pno: int, full: bool =False) -> list:
"""Retrieve a list of fonts used on a page.
"""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if not self.is_pdf:
return ()
if type(pno) is not int:
try:
pno = pno.number
except Exception:
exception_info()
raise ValueError("need a Page or page number")
val = self._getPageInfo(pno, 1)
if not full:
return [v[:-1] for v in val]
return val
def get_page_images(self, pno: int, full: bool =False) -> list:
"""Retrieve a list of images used on a page.
"""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if not self.is_pdf:
return ()
val = self._getPageInfo(pno, 2)
if not full:
return [v[:-1] for v in val]
return val
def get_page_labels(self):
"""Return page label definitions in PDF document.
Returns:
A list of dictionaries with the following format:
{'startpage': int, 'prefix': str, 'style': str, 'firstpagenum': int}.
"""
# Jorj McKie, 2021-01-10
return [utils.rule_dict(item) for item in self._get_page_labels()]
def get_page_numbers(doc, label, only_one=False):
"""Return a list of page numbers with the given label.
Args:
doc: PDF document object (resp. 'self').
label: (str) label.
only_one: (bool) stop searching after first hit.
Returns:
List of page numbers having this label.
"""
# Jorj McKie, 2021-01-06
numbers = []
if not label:
return numbers
labels = doc._get_page_labels()
if labels == []:
return numbers
for i in range(doc.page_count):
plabel = utils.get_label_pno(i, labels)
if plabel == label:
numbers.append(i)
if only_one:
break
return numbers
def get_page_pixmap(
doc: 'Document',
pno: int,
*,
matrix: matrix_like = None,
dpi=None,
colorspace: Colorspace = None,
clip: rect_like = None,
alpha: bool = False,
annots: bool = True,
) -> 'Pixmap':
"""Create pixmap of document page by page number.
Notes:
Convenience function calling page.get_pixmap.
Args:
pno: (int) page number
matrix: pymupdf.Matrix for transformation (default: pymupdf.Identity).
colorspace: (str,pymupdf.Colorspace) rgb, rgb, gray - case ignored, default csRGB.
clip: (irect-like) restrict rendering to this area.
alpha: (bool) include alpha channel
annots: (bool) also render annotations
"""
if matrix is None:
matrix = Identity
if colorspace is None:
colorspace = csRGB
return doc[pno].get_pixmap(
matrix=matrix,
dpi=dpi, colorspace=colorspace,
clip=clip,
alpha=alpha,
annots=annots
)
def get_page_text(
doc: 'Document',
pno: int,
option: str = "text",
clip: rect_like = None,
flags: OptInt = None,
textpage: 'TextPage' = None,
sort: bool = False,
) -> typing.Any:
"""Extract a document page's text by page number.
Notes:
Convenience function calling page.get_text().
Args:
pno: page number
option: (str) text, words, blocks, html, dict, json, rawdict, xhtml or xml.
Returns:
output from page.TextPage().
"""
return doc[pno].get_text(option, clip=clip, flags=flags, sort=sort)
def get_page_xobjects(self, pno: int) -> list:
"""Retrieve a list of XObjects used on a page.
"""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if not self.is_pdf:
return ()
val = self._getPageInfo(pno, 3)
return val
def get_sigflags(self):
"""Get the /SigFlags value."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return -1 # not a PDF
sigflags = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('AcroForm'),
PDF_NAME('SigFlags'),
)
sigflag = -1
if sigflags.m_internal:
sigflag = mupdf.pdf_to_int(sigflags)
return sigflag
def get_toc(
doc: 'Document',
simple: bool = True,
) -> list:
"""Create a table of contents.
Args:
simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation.
"""
def recurse(olItem, liste, lvl):
"""Recursively follow the outline item chain and record item information in a list."""
while olItem and olItem.this.m_internal:
if olItem.title:
title = olItem.title
else:
title = " "
if not olItem.is_external:
if olItem.uri:
if olItem.page == -1:
resolve = doc.resolve_link(olItem.uri)
page = resolve[0] + 1
else:
page = olItem.page + 1
else:
page = -1
else:
page = -1
if not simple:
link = utils.getLinkDict(olItem, doc)
liste.append([lvl, title, page, link])
else:
liste.append([lvl, title, page])
if olItem.down:
liste = recurse(olItem.down, liste, lvl + 1)
olItem = olItem.next
return liste
# ensure document is open
if doc.is_closed:
raise ValueError("document closed")
doc.init_doc()
olItem = doc.outline
if not olItem:
return []
lvl = 1
liste = []
toc = recurse(olItem, liste, lvl)
if doc.is_pdf and not simple:
doc._extend_toc_items(toc)
return toc
def get_xml_metadata(self):
"""Get document XML metadata."""
xml = None
pdf = _as_pdf_document(self, required=0)
if pdf.m_internal:
xml = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Metadata'),
)
if xml is not None and xml.m_internal:
buff = mupdf.pdf_load_stream(xml)
rc = JM_UnicodeFromBuffer(buff)
else:
rc = ''
return rc
def has_annots(doc: 'Document') -> bool:
"""Check whether there are annotations on any page."""
if doc.is_closed:
raise ValueError("document closed")
if not doc.is_pdf:
raise ValueError("is no PDF")
for i in range(doc.page_count):
for item in doc.page_annot_xrefs(i):
# pylint: disable=no-member
if not (item[1] == mupdf.PDF_ANNOT_LINK or item[1] == mupdf.PDF_ANNOT_WIDGET): # pylint: disable=no-member
return True
return False
def has_links(doc: 'Document') -> bool:
"""Check whether there are links on any page."""
if doc.is_closed:
raise ValueError("document closed")
if not doc.is_pdf:
raise ValueError("is no PDF")
for i in range(doc.page_count):
for item in doc.page_annot_xrefs(i):
if item[1] == mupdf.PDF_ANNOT_LINK: # pylint: disable=no-member
return True
return False
def init_doc(self):
if self.is_encrypted:
raise ValueError("cannot initialize - document still encrypted")
self._outline = self._loadOutline()
self.metadata = dict(
[
(k,self._getMetadata(v)) for k,v in {
'format':'format',
'title':'info:Title',
'author':'info:Author',
'subject':'info:Subject',
'keywords':'info:Keywords',
'creator':'info:Creator',
'producer':'info:Producer',
'creationDate':'info:CreationDate',
'modDate':'info:ModDate',
'trapped':'info:Trapped'
}.items()
]
)
self.metadata['encryption'] = None if self._getMetadata('encryption')=='None' else self._getMetadata('encryption')
def insert_file(self,
infile,
from_page=-1,
to_page=-1,
start_at=-1,
rotate=-1,
links=True,
annots=True,
show_progress=0,
final=1,
):
'''
Insert an arbitrary supported document to an existing PDF.
The infile may be given as a filename, a Document or a Pixmap. Other
parameters - where applicable - equal those of insert_pdf().
'''
src = None
if isinstance(infile, Pixmap):
if infile.colorspace.n > 3:
infile = Pixmap(csRGB, infile)
src = Document("png", infile.tobytes())
elif isinstance(infile, Document):
src = infile
else:
src = Document(infile)
if not src:
raise ValueError("bad infile parameter")
if not src.is_pdf:
pdfbytes = src.convert_to_pdf()
src = Document("pdf", pdfbytes)
return self.insert_pdf(
src,
from_page=from_page,
to_page=to_page,
start_at=start_at,
rotate=rotate,
links=links,
annots=annots,
show_progress=show_progress,
final=final,
)
def insert_page(
doc: 'Document',
pno: int,
text: typing.Union[str, list, None] = None,
fontsize: float = 11,
width: float = 595,
height: float = 842,
fontname: str = "helv",
fontfile: OptStr = None,
color: OptSeq = (0,),
) -> int:
"""Create a new PDF page and insert some text.
Notes:
Function combining pymupdf.Document.new_page() and pymupdf.Page.insert_text().
For parameter details see these methods.
"""
page = doc.new_page(pno=pno, width=width, height=height)
if not bool(text):
return 0
rc = page.insert_text(
(50, 72),
text,
fontsize=fontsize,
fontname=fontname,
fontfile=fontfile,
color=color,
)
return rc
def insert_pdf(
self,
docsrc,
*,
from_page=-1,
to_page=-1,
start_at=-1,
rotate=-1,
links=1,
annots=1,
widgets=1,
join_duplicates=0,
show_progress=0,
final=1,
_gmap=None,
):
"""Insert a page range from another PDF.
Args:
docsrc: PDF to copy from. Must be different object, but may be same file.
from_page: (int) first source page to copy, 0-based, default 0.
to_page: (int) last source page to copy, 0-based, default last page.
start_at: (int) from_page will become this page number in target.
rotate: (int) rotate copied pages, default -1 is no change.
links: (int/bool) whether to also copy links.
annots: (int/bool) whether to also copy annotations.
widgets: (int/bool) whether to also copy form fields.
join_duplicates: (int/bool) join or rename duplicate widget names.
show_progress: (int) progress message interval, 0 is no messages.
final: (bool) indicates last insertion from this source PDF.
_gmap: internal use only
Copy sequence reversed if from_page > to_page."""
# Insert pages from a source PDF into this PDF.
# For reconstructing the links (_do_links method), we must save the
# insertion point (start_at) if it was specified as -1.
#log( 'insert_pdf(): start')
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if self._graft_id == docsrc._graft_id:
raise ValueError("source and target cannot be same object")
sa = start_at
if sa < 0:
sa = self.page_count
outCount = self.page_count
srcCount = docsrc.page_count
# local copies of page numbers
fp = from_page
tp = to_page
sa = start_at
# normalize page numbers
fp = max(fp, 0) # -1 = first page
fp = min(fp, srcCount - 1) # but do not exceed last page
if tp < 0:
tp = srcCount - 1 # -1 = last page
tp = min(tp, srcCount - 1) # but do not exceed last page
if sa < 0:
sa = outCount # -1 = behind last page
sa = min(sa, outCount) # but that is also the limit
if len(docsrc) > show_progress > 0:
inname = os.path.basename(docsrc.name)
if not inname:
inname = "memory PDF"
outname = os.path.basename(self.name)
if not outname:
outname = "memory PDF"
message("Inserting '%s' at '%s'" % (inname, outname))
# retrieve / make a Graftmap to avoid duplicate objects
#log( 'insert_pdf(): Graftmaps')
isrt = docsrc._graft_id
_gmap = self.Graftmaps.get(isrt, None)
if _gmap is None:
#log( 'insert_pdf(): Graftmaps2')
_gmap = Graftmap(self)
self.Graftmaps[isrt] = _gmap
if g_use_extra:
#log( 'insert_pdf(): calling extra_FzDocument_insert_pdf()')
extra_FzDocument_insert_pdf(
self.this,
docsrc.this,
from_page,
to_page,
start_at,
rotate,
links,
annots,
show_progress,
final,
_gmap,
)
#log( 'insert_pdf(): extra_FzDocument_insert_pdf() returned.')
else:
pdfout = _as_pdf_document(self)
pdfsrc = _as_pdf_document(docsrc)
if not pdfout.m_internal or not pdfsrc.m_internal:
raise TypeError( "source or target not a PDF")
ENSURE_OPERATION(pdfout)
JM_merge_range(pdfout, pdfsrc, fp, tp, sa, rotate, links, annots, show_progress, _gmap)
#log( 'insert_pdf(): calling self._reset_page_refs()')
self._reset_page_refs()
if links:
#log( 'insert_pdf(): calling self._do_links()')
self._do_links(docsrc, from_page=fp, to_page=tp, start_at=sa)
if widgets:
self._do_widgets(docsrc, _gmap, from_page=fp, to_page=tp, start_at=sa, join_duplicates=join_duplicates)
if final == 1:
self.Graftmaps[isrt] = None
#log( 'insert_pdf(): returning')
@property
def is_dirty(self):
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return False
r = mupdf.pdf_has_unsaved_changes(pdf)
return True if r else False
@property
def is_fast_webaccess(self):
'''
Check whether we have a linearized PDF.
'''
pdf = _as_pdf_document(self, required=0)
if pdf.m_internal:
return mupdf.pdf_doc_was_linearized(pdf)
return False # gracefully handle non-PDF
@property
def is_form_pdf(self):
"""Either False or PDF field count."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return False
count = -1
try:
fields = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
mupdf.PDF_ENUM_NAME_Root,
mupdf.PDF_ENUM_NAME_AcroForm,
mupdf.PDF_ENUM_NAME_Fields,
)
if mupdf.pdf_is_array(fields):
count = mupdf.pdf_array_len(fields)
except Exception:
if g_exceptions_verbose: exception_info()
return False
if count >= 0:
return count
return False
@property
def is_pdf(self):
"""Check for PDF."""
if isinstance(self.this, mupdf.PdfDocument):
return True
# Avoid calling smupdf.pdf_specifics because it will end up creating
# a new PdfDocument which will call pdf_create_document(), which is ok
# but a little unnecessary.
#
if mupdf.ll_pdf_specifics(self.this.m_internal):
ret = True
else:
ret = False
return ret
@property
def is_reflowable(self):
"""Check if document is layoutable."""
if self.is_closed:
raise ValueError("document closed")
return bool(mupdf.fz_is_document_reflowable(self))
@property
def is_repaired(self):
"""Check whether PDF was repaired."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return False
r = mupdf.pdf_was_repaired(pdf)
if r:
return True
return False
def journal_can_do(self):
"""Show if undo and / or redo are possible."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
undo=0
redo=0
pdf = _as_pdf_document(self)
undo = mupdf.pdf_can_undo(pdf)
redo = mupdf.pdf_can_redo(pdf)
return {'undo': bool(undo), 'redo': bool(redo)}
def journal_enable(self):
"""Activate document journalling."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
mupdf.pdf_enable_journal(pdf)
def journal_is_enabled(self):
"""Check if journalling is enabled."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
enabled = pdf.m_internal and pdf.m_internal.journal
return enabled
def journal_load(self, filename):
"""Load a journal from a file."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
if isinstance(filename, str):
mupdf.pdf_load_journal(pdf, filename)
else:
res = JM_BufferFromBytes(filename)
stm = mupdf.fz_open_buffer(res)
mupdf.pdf_deserialise_journal(pdf, stm)
if not pdf.m_internal.journal:
RAISEPY( "Journal and document do not match", JM_Exc_FileDataError)
def journal_op_name(self, step):
"""Show operation name for given step."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
name = mupdf.pdf_undoredo_step(pdf, step)
return name
def journal_position(self):
"""Show journalling state."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
steps=0
pdf = _as_pdf_document(self)
rc, steps = mupdf.pdf_undoredo_state(pdf)
return rc, steps
def journal_redo(self):
"""Move forward in the journal."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
mupdf.pdf_redo(pdf)
return True
def journal_save(self, filename):
"""Save journal to a file."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
if isinstance(filename, str):
mupdf.pdf_save_journal(pdf, filename)
else:
out = JM_new_output_fileptr(filename)
mupdf.pdf_write_journal(pdf, out)
out.fz_close_output()
def journal_start_op(self, name=None):
"""Begin a journalling operation."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
if not pdf.m_internal.journal:
raise RuntimeError( "Journalling not enabled")
if name:
mupdf.pdf_begin_operation(pdf, name)
else:
mupdf.pdf_begin_implicit_operation(pdf)
def journal_stop_op(self):
"""End a journalling operation."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
mupdf.pdf_end_operation(pdf)
def journal_undo(self):
"""Move backwards in the journal."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
mupdf.pdf_undo(pdf)
return True
@property
def language(self):
"""Document language."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return
lang = mupdf.pdf_document_language(pdf)
if lang == mupdf.FZ_LANG_UNSET:
return
return mupdf.fz_string_from_text_language2(lang)
@property
def last_location(self):
"""Id (chapter, page) of last page."""
if self.is_closed:
raise ValueError("document closed")
last_loc = mupdf.fz_last_page(self.this)
return last_loc.chapter, last_loc.page
def layer_ui_configs(self):
"""Show OC visibility status modifiable by user."""
pdf = _as_pdf_document(self)
info = mupdf.PdfLayerConfigUi()
n = mupdf.pdf_count_layer_config_ui( pdf)
rc = []
for i in range(n):
mupdf.pdf_layer_config_ui_info( pdf, i, info)
if info.type == 1:
type_ = "checkbox"
elif info.type == 2:
type_ = "radiobox"
else:
type_ = "label"
item = {
"number": i,
"text": info.text,
"depth": info.depth,
"type": type_,
"on": info.selected,
"locked": info.locked,
}
rc.append(item)
return rc
def layout(self, rect=None, width=0, height=0, fontsize=11):
"""Re-layout a reflowable document."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
doc = self.this
if not mupdf.fz_is_document_reflowable( doc):
return
w = width
h = height
r = JM_rect_from_py(rect)
if not mupdf.fz_is_infinite_rect(r):
w = r.x1 - r.x0
h = r.y1 - r.y0
if w <= 0.0 or h <= 0.0:
raise ValueError( "bad page size")
mupdf.fz_layout_document( doc, w, h, fontsize)
self._reset_page_refs()
self.init_doc()
def load_page(self, page_id):
"""Load a page.
'page_id' is either a 0-based page number or a tuple (chapter, pno),
with chapter number and page number within that chapter.
"""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if page_id is None:
page_id = 0
if page_id not in self:
raise ValueError("page not in document")
if type(page_id) is int and page_id < 0:
np = self.page_count
while page_id < 0:
page_id += np
if isinstance(page_id, int):
page = mupdf.fz_load_page(self.this, page_id)
else:
chapter, pagenum = page_id
page = mupdf.fz_load_chapter_page(self.this, chapter, pagenum)
val = Page(page, self)
val.thisown = True
val.parent = self
self._page_refs[id(val)] = val
val._annot_refs = weakref.WeakValueDictionary()
val.number = page_id
return val
def location_from_page_number(self, pno):
"""Convert pno to (chapter, page)."""
if self.is_closed:
raise ValueError("document closed")
this_doc = self.this
loc = mupdf.fz_make_location(-1, -1)
page_count = mupdf.fz_count_pages(this_doc)
while pno < 0:
pno += page_count
if pno >= page_count:
raise ValueError( MSG_BAD_PAGENO)
loc = mupdf.fz_location_from_page_number(this_doc, pno)
return loc.chapter, loc.page
def make_bookmark(self, loc):
"""Make a page pointer before layouting document."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
loc = mupdf.FzLocation(*loc)
mark = mupdf.ll_fz_make_bookmark2( self.this.m_internal, loc.internal())
return mark
@property
def markinfo(self) -> dict:
"""Return the PDF MarkInfo value."""
xref = self.pdf_catalog()
if xref == 0:
return None
rc = self.xref_get_key(xref, "MarkInfo")
if rc[0] == "null":
return {}
if rc[0] == "xref":
xref = int(rc[1].split()[0])
val = self.xref_object(xref, compressed=True)
elif rc[0] == "dict":
val = rc[1]
else:
val = None
if val is None or not (val[:2] == "<<" and val[-2:] == ">>"):
return {}
valid = {"Marked": False, "UserProperties": False, "Suspects": False}
val = val[2:-2].split("/")
for v in val[1:]:
try:
key, value = v.split()
except Exception:
if g_exceptions_verbose > 1: exception_info()
return valid
if value == "true":
valid[key] = True
return valid
def move_page(self, pno: int, to: int =-1):
"""Move a page within a PDF document.
Args:
pno: source page number.
to: put before this page, '-1' means after last page.
"""
if self.is_closed:
raise ValueError("document closed")
page_count = len(self)
if (pno not in range(page_count) or to not in range(-1, page_count)):
raise ValueError("bad page number(s)")
before = 1
copy = 0
if to == -1:
to = page_count - 1
before = 0
return self._move_copy_page(pno, to, before, copy)
@property
def name(self):
return self._name
def need_appearances(self, value=None):
"""Get/set the NeedAppearances value."""
if not self.is_form_pdf:
return None
pdf = _as_pdf_document(self)
oldval = -1
appkey = "NeedAppearances"
form = mupdf.pdf_dict_getp(
mupdf.pdf_trailer(pdf),
"Root/AcroForm",
)
app = mupdf.pdf_dict_gets(form, appkey)
if mupdf.pdf_is_bool(app):
oldval = mupdf.pdf_to_bool(app)
if value:
mupdf.pdf_dict_puts(form, appkey, mupdf.PDF_TRUE)
else:
mupdf.pdf_dict_puts(form, appkey, mupdf.PDF_FALSE)
if value is None:
return oldval >= 0
return value
@property
def needs_pass(self):
"""Indicate password required."""
if self.is_closed:
raise ValueError("document closed")
document = self.this if isinstance(self.this, mupdf.FzDocument) else self.this.super()
ret = mupdf.fz_needs_password( document)
return ret
def new_page(
doc: 'Document',
pno: int = -1,
width: float = 595,
height: float = 842,
) -> Page:
"""Create and return a new page object.
Args:
pno: (int) insert before this page. Default: after last page.
width: (float) page width in points. Default: 595 (ISO A4 width).
height: (float) page height in points. Default 842 (ISO A4 height).
Returns:
A pymupdf.Page object.
"""
doc._newPage(pno, width=width, height=height)
return doc[pno]
def next_location(self, page_id):
"""Get (chapter, page) of next page."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if type(page_id) is int:
page_id = (0, page_id)
if page_id not in self:
raise ValueError("page id not in document")
if tuple(page_id) == self.last_location:
return ()
this_doc = _as_fz_document(self)
val = page_id[ 0]
if not isinstance(val, int):
RAISEPY(MSG_BAD_PAGEID, PyExc_ValueError)
chapter = val
val = page_id[ 1]
pno = val
loc = mupdf.fz_make_location(chapter, pno)
next_loc = mupdf.fz_next_page( this_doc, loc)
return next_loc.chapter, next_loc.page
def page_annot_xrefs(self, n):
if g_use_extra:
return extra.page_annot_xrefs( self.this, n)
if isinstance(self.this, mupdf.PdfDocument):
page_count = mupdf.pdf_count_pages(self.this)
pdf_document = self.this
else:
page_count = mupdf.fz_count_pages(self.this)
pdf_document = _as_pdf_document(self)
while n < 0:
n += page_count
if n > page_count:
raise ValueError( MSG_BAD_PAGENO)
page_obj = mupdf.pdf_lookup_page_obj(pdf_document, n)
annots = JM_get_annot_xref_list(page_obj)
return annots
@property
def page_count(self):
"""Number of pages."""
if self.is_closed:
raise ValueError('document closed')
if g_use_extra:
return self.page_count2(self)
if isinstance( self.this, mupdf.FzDocument):
return mupdf.fz_count_pages( self.this)
else:
return mupdf.pdf_count_pages( self.this)
def page_cropbox(self, pno):
"""Get CropBox of page number (without loading page)."""
if self.is_closed:
raise ValueError("document closed")
this_doc = self.this
page_count = mupdf.fz_count_pages( this_doc)
n = pno
while n < 0:
n += page_count
pdf = _as_pdf_document(self)
if n >= page_count:
raise ValueError( MSG_BAD_PAGENO)
pageref = mupdf.pdf_lookup_page_obj( pdf, n)
cropbox = JM_cropbox(pageref)
val = JM_py_from_rect(cropbox)
val = Rect(val)
return val
def page_number_from_location(self, page_id):
"""Convert (chapter, pno) to page number."""
if type(page_id) is int:
np = self.page_count
while page_id < 0:
page_id += np
page_id = (0, page_id)
if page_id not in self:
raise ValueError("page id not in document")
chapter, pno = page_id
loc = mupdf.fz_make_location( chapter, pno)
page_n = mupdf.fz_page_number_from_location( self.this, loc)
return page_n
def page_xref(self, pno):
"""Get xref of page number."""
if g_use_extra:
return extra.page_xref( self.this, pno)
if self.is_closed:
raise ValueError("document closed")
page_count = mupdf.fz_count_pages(self.this)
n = pno
while n < 0:
n += page_count
pdf = _as_pdf_document(self)
xref = 0
if n >= page_count:
raise ValueError( MSG_BAD_PAGENO)
xref = mupdf.pdf_to_num(mupdf.pdf_lookup_page_obj(pdf, n))
return xref
@property
def pagelayout(self) -> str:
"""Return the PDF PageLayout value.
"""
xref = self.pdf_catalog()
if xref == 0:
return None
rc = self.xref_get_key(xref, "PageLayout")
if rc[0] == "null":
return "SinglePage"
if rc[0] == "name":
return rc[1][1:]
return "SinglePage"
@property
def pagemode(self) -> str:
"""Return the PDF PageMode value.
"""
xref = self.pdf_catalog()
if xref == 0:
return None
rc = self.xref_get_key(xref, "PageMode")
if rc[0] == "null":
return "UseNone"
if rc[0] == "name":
return rc[1][1:]
return "UseNone"
if sys.implementation.version < (3, 9):
# Appending `[Page]` causes `TypeError: 'ABCMeta' object is not subscriptable`.
_pages_ret = collections.abc.Iterable
else:
_pages_ret = collections.abc.Iterable[Page]
def pages(self, start: OptInt =None, stop: OptInt =None, step: OptInt =None) -> _pages_ret:
"""Return a generator iterator over a page range.
Arguments have the same meaning as for the range() built-in.
"""
if not self.page_count:
return
# set the start value
start = start or 0
while start < 0:
start += self.page_count
if start not in range(self.page_count):
raise ValueError("bad start page number")
# set the stop value
stop = stop if stop is not None and stop <= self.page_count else self.page_count
# set the step value
if step == 0:
raise ValueError("arg 3 must not be zero")
if step is None:
if start > stop:
step = -1
else:
step = 1
for pno in range(start, stop, step):
yield (self.load_page(pno))
def pdf_catalog(self):
"""Get xref of PDF catalog."""
pdf = _as_pdf_document(self, required=0)
xref = 0
if not pdf.m_internal:
return xref
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
xref = mupdf.pdf_to_num(root)
return xref
def pdf_trailer(self, compressed=0, ascii=0):
"""Get PDF trailer as a string."""
return self.xref_object(-1, compressed=compressed, ascii=ascii)
@property
def permissions(self):
"""Document permissions."""
if self.is_encrypted:
return 0
doc =self.this
pdf = mupdf.pdf_document_from_fz_document(doc)
# for PDF return result of standard function
if pdf.m_internal:
return mupdf.pdf_document_permissions(pdf)
# otherwise simulate the PDF return value
perm = 0xFFFFFFFC # all permissions granted
# now switch off where needed
if not mupdf.fz_has_permission(doc, mupdf.FZ_PERMISSION_PRINT):
perm = perm ^ mupdf.PDF_PERM_PRINT
if not mupdf.fz_has_permission(doc, mupdf.FZ_PERMISSION_EDIT):
perm = perm ^ mupdf.PDF_PERM_MODIFY
if not mupdf.fz_has_permission(doc, mupdf.FZ_PERMISSION_COPY):
perm = perm ^ mupdf.PDF_PERM_COPY
if not mupdf.fz_has_permission(doc, mupdf.FZ_PERMISSION_ANNOTATE):
perm = perm ^ mupdf.PDF_PERM_ANNOTATE
return perm
def prev_location(self, page_id):
"""Get (chapter, page) of previous page."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if type(page_id) is int:
page_id = (0, page_id)
if page_id not in self:
raise ValueError("page id not in document")
if page_id == (0, 0):
return ()
chapter, pno = page_id
loc = mupdf.fz_make_location(chapter, pno)
prev_loc = mupdf.fz_previous_page(self.this, loc)
return prev_loc.chapter, prev_loc.page
def reload_page(self, page: Page) -> Page:
"""Make a fresh copy of a page."""
old_annots = {} # copy annot references to here
pno = page.number # save the page number
for k, v in page._annot_refs.items(): # save the annot dictionary
old_annots[k] = v
# When we call `self.load_page()` below, it will end up in
# fz_load_chapter_page(), which will return any matching page in the
# document's list of non-ref-counted loaded pages, instead of actually
# reloading the page.
#
# We want to assert that we have actually reloaded the fz_page, and not
# simply returned the same `fz_page*` pointer from the document's list
# of non-ref-counted loaded pages.
#
# So we first remove our reference to the `fz_page*`. This will
# decrement .refs, and if .refs was 1, this is guaranteed to free the
# `fz_page*` and remove it from the document's list if it was there. So
# we are guaranteed that our returned `fz_page*` is from a genuine
# reload, even if it happens to reuse the original block of memory.
#
# However if the original .refs is greater than one, there must be
# other references to the `fz_page` somewhere, and we require that
# these other references are not keeping the page in the document's
# list. We check that we are returning a newly loaded page by
# asserting that our returned `fz_page*` is different from the original
# `fz_page*` - the original was not freed, so a new `fz_page` cannot
# reuse the same block of memory.
#
refs_old = page.this.m_internal.refs
m_internal_old = page.this.m_internal_value()
page.this = None
page._erase() # remove the page
page = None
TOOLS.store_shrink(100)
page = self.load_page(pno) # reload the page
# copy annot refs over to the new dictionary
#page_proxy = weakref.proxy(page)
for k, v in old_annots.items():
annot = old_annots[k]
#annot.parent = page_proxy # refresh parent to new page
page._annot_refs[k] = annot
if refs_old == 1:
# We know that `page.this = None` will have decremented the ref
# count to zero so we are guaranteed that the new `fz_page` is a
# new page even if it happens to have reused the same block of
# memory.
pass
else:
# Check that the new `fz_page*` is different from the original.
m_internal_new = page.this.m_internal_value()
assert m_internal_new != m_internal_old, \
f'{refs_old=} {m_internal_old=:#x} {m_internal_new=:#x}'
return page
def resolve_link(self, uri=None, chapters=0):
"""Calculate internal link destination.
Args:
uri: (str) some Link.uri
chapters: (bool) whether to use (chapter, page) format
Returns:
(page_id, x, y) where x, y are point coordinates on the page.
page_id is either page number (if chapters=0), or (chapter, pno).
"""
if not uri:
if chapters:
return (-1, -1), 0, 0
return -1, 0, 0
try:
loc, xp, yp = mupdf.fz_resolve_link(self.this, uri)
except Exception:
if g_exceptions_verbose: exception_info()
if chapters:
return (-1, -1), 0, 0
return -1, 0, 0
if chapters:
return (loc.chapter, loc.page), xp, yp
pno = mupdf.fz_page_number_from_location(self.this, loc)
return pno, xp, yp
def rewrite_images(
self,
dpi_threshold=None,
dpi_target=0,
quality=0,
lossy=True,
lossless=True,
bitonal=True,
color=True,
gray=True,
set_to_gray=False,
options=None,
):
"""Rewrite images in a PDF document.
The typical use case is to reduce the size of the PDF by recompressing
images. Default parameters will convert all images to JPEG where
possible, using the specified resolutions and quality. Exclude
undesired images by setting parameters to False.
Args:
dpi_threshold: look at images with a larger DPI only.
dpi_target: change eligible images to this DPI.
quality: Quality of the recompressed images (0-100).
lossy: process lossy image types (e.g. JPEG).
lossless: process lossless image types (e.g. PNG).
bitonal: process black-and-white images (e.g. FAX)
color: process colored images.
gray: process gray images.
set_to_gray: whether to change the PDF to gray at process start.
options: (PdfImageRewriterOptions) Custom options for image
rewriting (optional). Expert use only. If provided, other
parameters are ignored, except set_to_gray.
"""
quality_str = str(quality)
if not dpi_threshold:
dpi_threshold = dpi_target = 0
if dpi_target > 0 and dpi_target >= dpi_threshold:
raise ValueError("{dpi_target=} must be less than {dpi_threshold=}")
template_opts = mupdf.PdfImageRewriterOptions()
dir1 = set(dir(template_opts)) # for checking that only existing options are set
if not options:
opts = mupdf.PdfImageRewriterOptions()
if bitonal:
opts.bitonal_image_recompress_method = mupdf.FZ_RECOMPRESS_FAX
opts.bitonal_image_subsample_method = mupdf.FZ_SUBSAMPLE_AVERAGE
opts.bitonal_image_subsample_to = dpi_target
opts.bitonal_image_recompress_quality = quality_str
opts.bitonal_image_subsample_threshold = dpi_threshold
if color:
if lossless:
opts.color_lossless_image_recompress_method = mupdf.FZ_RECOMPRESS_JPEG
opts.color_lossless_image_subsample_method = mupdf.FZ_SUBSAMPLE_AVERAGE
opts.color_lossless_image_subsample_to = dpi_target
opts.color_lossless_image_subsample_threshold = dpi_threshold
opts.color_lossless_image_recompress_quality = quality_str
if lossy:
opts.color_lossy_image_recompress_method = mupdf.FZ_RECOMPRESS_JPEG
opts.color_lossy_image_subsample_method = mupdf.FZ_SUBSAMPLE_AVERAGE
opts.color_lossy_image_subsample_threshold = dpi_threshold
opts.color_lossy_image_subsample_to = dpi_target
opts.color_lossy_image_recompress_quality = quality_str
if gray:
if lossless:
opts.gray_lossless_image_recompress_method = mupdf.FZ_RECOMPRESS_JPEG
opts.gray_lossless_image_subsample_method = mupdf.FZ_SUBSAMPLE_AVERAGE
opts.gray_lossless_image_subsample_to = dpi_target
opts.gray_lossless_image_subsample_threshold = dpi_threshold
opts.gray_lossless_image_recompress_quality = quality_str
if lossy:
opts.gray_lossy_image_recompress_method = mupdf.FZ_RECOMPRESS_JPEG
opts.gray_lossy_image_subsample_method = mupdf.FZ_SUBSAMPLE_AVERAGE
opts.gray_lossy_image_subsample_threshold = dpi_threshold
opts.gray_lossy_image_subsample_to = dpi_target
opts.gray_lossy_image_recompress_quality = quality_str
else:
opts = options
dir2 = set(dir(opts)) # checking that only possible options were used
invalid_options = dir2 - dir1
if invalid_options:
raise ValueError(f"Invalid options: {invalid_options}")
if set_to_gray:
self.recolor(1)
pdf = _as_pdf_document(self)
mupdf.pdf_rewrite_images(pdf, opts)
def recolor(self, components=1):
"""Change the color component count on all pages.
Args:
components: (int) desired color component count, one of 1, 3, 4.
Invokes the same-named method for all pages.
"""
if not self.is_pdf:
raise ValueError("is no PDF")
for i in range(self.page_count):
self.load_page(i).recolor(components)
def resolve_names(self):
"""Convert the PDF's destination names into a Python dict.
The only parameter is the pymupdf.Document.
All names found in the catalog under keys "/Dests" and "/Names/Dests" are
being included.
Returns:
A dcitionary with the following layout:
- key: (str) the name
- value: (dict) with the following layout:
* "page": target page number (0-based). If no page number found -1.
* "to": (x, y) target point on page - currently in PDF coordinates,
i.e. point (0,0) is the bottom-left of the page.
* "zoom": (float) the zoom factor
* "dest": (str) only occurs if the target location on the page has
not been provided as "/XYZ" or if no page number was found.
Examples:
{'__bookmark_1': {'page': 0, 'to': (0.0, 541.0), 'zoom': 0.0},
'__bookmark_2': {'page': 0, 'to': (0.0, 481.45), 'zoom': 0.0}}
or
'21154a7c20684ceb91f9c9adc3b677c40': {'page': -1, 'dest': '/XYZ 15.75 1486 0'}, ...
"""
if hasattr(self, "_resolved_names"): # do not execute multiple times!
return self._resolved_names
# this is a backward listing of page xref to page number
page_xrefs = {self.page_xref(i): i for i in range(self.page_count)}
def obj_string(obj):
"""Return string version of a PDF object definition."""
buffer = mupdf.fz_new_buffer(512)
output = mupdf.FzOutput(buffer)
mupdf.pdf_print_obj(output, obj, 1, 0)
output.fz_close_output()
return JM_UnicodeFromBuffer(buffer)
def get_array(val):
"""Generate value of one item of the names dictionary."""
templ_dict = {"page": -1, "dest": ""} # value template
if val.pdf_is_indirect():
val = mupdf.pdf_resolve_indirect(val)
if val.pdf_is_array():
array = obj_string(val)
elif val.pdf_is_dict():
array = obj_string(mupdf.pdf_dict_gets(val, "D"))
else: # if all fails return the empty template
return templ_dict
# replace PDF "null" by zero, omit the square brackets
array = array.replace("null", "0")[1:-1]
# find stuff before first "/"
idx = array.find("/")
if idx < 1: # this has no target page spec
templ_dict["dest"] = array # return the orig. string
return templ_dict
subval = array[:idx].strip() # stuff before "/"
array = array[idx:] # stuff from "/" onwards
templ_dict["dest"] = array
# if we start with /XYZ: extract x, y, zoom
# 1, 2 or 3 of these values may actually be supplied
if array.startswith("/XYZ"):
del templ_dict["dest"] # don't return orig string in this case
# make a list of the 3 tokens following "/XYZ"
array_list = array.split()[1:4] # omit "/XYZ"
# fill up missing tokens with "0" strings
while len(array_list) < 3: # fill up if too short
array_list.append("0") # add missing values
# make list of 3 floats: x, y and zoom
t = list(map(float, array_list)) # the resulting x, y, z values
templ_dict["to"] = (t[0], t[1])
templ_dict["zoom"] = t[2]
# extract page number
if subval.endswith("0 R"): # page xref given?
templ_dict["page"] = page_xrefs.get(int(subval.split()[0]),-1)
else: # naked page number given
templ_dict["page"] = int(subval)
return templ_dict
def fill_dict(dest_dict, pdf_dict):
"""Generate name resolution items for pdf_dict.
This may be either "/Names/Dests" or just "/Dests"
"""
# length of the PDF dictionary
name_count = mupdf.pdf_dict_len(pdf_dict)
# extract key-val of each dict item
for i in range(name_count):
key = mupdf.pdf_dict_get_key(pdf_dict, i)
val = mupdf.pdf_dict_get_val(pdf_dict, i)
if key.pdf_is_name(): # this should always be true!
dict_key = key.pdf_to_name()
else:
message(f"key {i} is no /Name")
dict_key = None
if dict_key:
dest_dict[dict_key] = get_array(val) # store key/value in dict
# access underlying PDF document of fz Document
pdf = mupdf.pdf_document_from_fz_document(self)
# access PDF catalog
catalog = mupdf.pdf_dict_gets(mupdf.pdf_trailer(pdf), "Root")
dest_dict = {}
# make PDF_NAME(Dests)
dests = mupdf.pdf_new_name("Dests")
# extract destinations old style (PDF 1.1)
old_dests = mupdf.pdf_dict_get(catalog, dests)
if old_dests.pdf_is_dict():
fill_dict(dest_dict, old_dests)
# extract destinations new style (PDF 1.2+)
tree = mupdf.pdf_load_name_tree(pdf, dests)
if tree.pdf_is_dict():
fill_dict(dest_dict, tree)
self._resolved_names = dest_dict # store result or reuse
return dest_dict
def save(
self,
filename,
garbage=0,
clean=0,
deflate=0,
deflate_images=0,
deflate_fonts=0,
incremental=0,
ascii=0,
expand=0,
linear=0,
no_new_id=0,
appearance=0,
pretty=0,
encryption=1,
permissions=4095,
owner_pw=None,
user_pw=None,
preserve_metadata=1,
use_objstms=0,
compression_effort=0,
):
# From %pythonprepend save
#
"""Save PDF to file, pathlib.Path or file pointer."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if type(filename) is str:
pass
elif hasattr(filename, "open"): # assume: pathlib.Path
filename = str(filename)
elif hasattr(filename, "name"): # assume: file object
filename = filename.name
elif not hasattr(filename, "seek"): # assume file object
raise ValueError("filename must be str, Path or file object")
if filename == self.name and not incremental:
raise ValueError("save to original must be incremental")
if linear and use_objstms:
raise ValueError("'linear' and 'use_objstms' cannot both be requested")
if self.page_count < 1:
raise ValueError("cannot save with zero pages")
if incremental:
if self.name != filename or self.stream:
raise ValueError("incremental needs original file")
if user_pw and len(user_pw) > 40 or owner_pw and len(owner_pw) > 40:
raise ValueError("password length must not exceed 40")
pdf = _as_pdf_document(self)
opts = mupdf.PdfWriteOptions()
opts.do_incremental = incremental
opts.do_ascii = ascii
opts.do_compress = deflate
opts.do_compress_images = deflate_images
opts.do_compress_fonts = deflate_fonts
opts.do_decompress = expand
opts.do_garbage = garbage
opts.do_pretty = pretty
opts.do_linear = linear
opts.do_clean = clean
opts.do_sanitize = clean
opts.dont_regenerate_id = no_new_id
opts.do_appearance = appearance
opts.do_encrypt = encryption
opts.permissions = permissions
if owner_pw is not None:
opts.opwd_utf8_set_value(owner_pw)
elif user_pw is not None:
opts.opwd_utf8_set_value(user_pw)
if user_pw is not None:
opts.upwd_utf8_set_value(user_pw)
opts.do_preserve_metadata = preserve_metadata
opts.do_use_objstms = use_objstms
opts.compression_effort = compression_effort
out = None
pdf.m_internal.resynth_required = 0
JM_embedded_clean(pdf)
if no_new_id == 0:
JM_ensure_identity(pdf)
if isinstance(filename, str):
#log( 'calling mupdf.pdf_save_document()')
mupdf.pdf_save_document(pdf, filename, opts)
else:
out = JM_new_output_fileptr(filename)
#log( f'{type(out)=} {type(out.this)=}')
mupdf.pdf_write_document(pdf, out, opts)
out.fz_close_output()
def save_snapshot(self, filename):
"""Save a file snapshot suitable for journalling."""
if self.is_closed:
raise ValueError("doc is closed")
if type(filename) is str:
pass
elif hasattr(filename, "open"): # assume: pathlib.Path
filename = str(filename)
elif hasattr(filename, "name"): # assume: file object
filename = filename.name
else:
raise ValueError("filename must be str, Path or file object")
if filename == self.name:
raise ValueError("cannot snapshot to original")
pdf = _as_pdf_document(self)
mupdf.pdf_save_snapshot(pdf, filename)
def saveIncr(self):
""" Save PDF incrementally"""
return self.save(self.name, incremental=True, encryption=mupdf.PDF_ENCRYPT_KEEP)
# ------------------------------------------------------------------------------
# Remove potentially sensitive data from a PDF. Similar to the Adobe
# Acrobat 'sanitize' function
# ------------------------------------------------------------------------------
def scrub(
doc: 'Document',
attached_files: bool = True,
clean_pages: bool = True,
embedded_files: bool = True,
hidden_text: bool = True,
javascript: bool = True,
metadata: bool = True,
redactions: bool = True,
redact_images: int = 0,
remove_links: bool = True,
reset_fields: bool = True,
reset_responses: bool = True,
thumbnails: bool = True,
xml_metadata: bool = True,
) -> None:
def remove_hidden(cont_lines):
"""Remove hidden text from a PDF page.
Args:
cont_lines: list of lines with /Contents content. Should have status
from after page.cleanContents().
Returns:
List of /Contents lines from which hidden text has been removed.
Notes:
The input must have been created after the page's /Contents object(s)
have been cleaned with page.cleanContents(). This ensures a standard
formatting: one command per line, single spaces between operators.
This allows for drastic simplification of this code.
"""
out_lines = [] # will return this
in_text = False # indicate if within BT/ET object
suppress = False # indicate text suppression active
make_return = False
for line in cont_lines:
if line == b"BT": # start of text object
in_text = True # switch on
out_lines.append(line) # output it
continue
if line == b"ET": # end of text object
in_text = False # switch off
out_lines.append(line) # output it
continue
if line == b"3 Tr": # text suppression operator
suppress = True # switch on
make_return = True
continue
if line[-2:] == b"Tr" and line[0] != b"3":
suppress = False # text rendering changed
out_lines.append(line)
continue
if line == b"Q": # unstack command also switches off
suppress = False
out_lines.append(line)
continue
if suppress and in_text: # suppress hidden lines
continue
out_lines.append(line)
if make_return:
return out_lines
else:
return None
if not doc.is_pdf: # only works for PDF
raise ValueError("is no PDF")
if doc.is_encrypted or doc.is_closed:
raise ValueError("closed or encrypted doc")
if not clean_pages:
hidden_text = False
redactions = False
if metadata:
doc.set_metadata({}) # remove standard metadata
for page in doc:
if reset_fields:
# reset form fields (widgets)
for widget in page.widgets():
widget.reset()
if remove_links:
links = page.get_links() # list of all links on page
for link in links: # remove all links
page.delete_link(link)
found_redacts = False
for annot in page.annots():
if annot.type[0] == mupdf.PDF_ANNOT_FILE_ATTACHMENT and attached_files:
annot.update_file(buffer_=b" ") # set file content to empty
if reset_responses:
annot.delete_responses()
if annot.type[0] == mupdf.PDF_ANNOT_REDACT: # pylint: disable=no-member
found_redacts = True
if redactions and found_redacts:
page.apply_redactions(images=redact_images)
if not (clean_pages or hidden_text):
continue # done with the page
page.clean_contents()
if not page.get_contents():
continue
if hidden_text:
xrefs = page.get_contents()
assert len(xrefs) == 1 # only one because of cleaning.
xref = xrefs[0]
cont = doc.xref_stream(xref)
cont_lines = remove_hidden(cont.splitlines()) # remove hidden text
if cont_lines: # something was actually removed
cont = b"\n".join(cont_lines)
doc.update_stream(xref, cont) # rewrite the page /Contents
if thumbnails: # remove page thumbnails?
if doc.xref_get_key(page.xref, "Thumb")[0] != "null":
doc.xref_set_key(page.xref, "Thumb", "null")
# pages are scrubbed, now perform document-wide scrubbing
# remove embedded files
if embedded_files:
for name in doc.embfile_names():
doc.embfile_del(name)
if xml_metadata:
doc.del_xml_metadata()
if not (xml_metadata or javascript):
xref_limit = 0
else:
xref_limit = doc.xref_length()
for xref in range(1, xref_limit):
if not doc.xref_object(xref):
msg = "bad xref %i - clean PDF before scrubbing" % xref
raise ValueError(msg)
if javascript and doc.xref_get_key(xref, "S")[1] == "/JavaScript":
# a /JavaScript action object
obj = "<</S/JavaScript/JS()>>" # replace with a null JavaScript
doc.update_object(xref, obj) # update this object
continue # no further handling
if not xml_metadata:
continue
if doc.xref_get_key(xref, "Type")[1] == "/Metadata":
# delete any metadata object directly
doc.update_object(xref, "<<>>")
doc.update_stream(xref, b"deleted", new=True)
continue
if doc.xref_get_key(xref, "Metadata")[0] != "null":
doc.xref_set_key(xref, "Metadata", "null")
def search_page_for(
doc: 'Document',
pno: int,
text: str,
quads: bool = False,
clip: rect_like = None,
flags: int = None,
textpage: 'TextPage' = None,
) -> list:
"""Search for a string on a page.
Args:
pno: page number
text: string to be searched for
clip: restrict search to this rectangle
quads: (bool) return quads instead of rectangles
flags: bit switches, default: join hyphened words
textpage: reuse a prepared textpage
Returns:
a list of rectangles or quads, each containing an occurrence.
"""
if flags is None:
flags = (0
| TEXT_DEHYPHENATE
| TEXT_PRESERVE_LIGATURES
| TEXT_PRESERVE_WHITESPACE
| TEXT_MEDIABOX_CLIP
)
return doc[pno].search_for(
text,
quads=quads,
clip=clip,
flags=flags,
textpage=textpage,
)
def select(self, pyliste):
"""Build sub-pdf with page numbers in the list."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if not self.is_pdf:
raise ValueError("is no PDF")
if not hasattr(pyliste, "__getitem__"):
raise ValueError("sequence required")
valid_range = range(len(self))
if (len(pyliste) == 0
or min(pyliste) not in valid_range
or max(pyliste) not in valid_range
):
raise ValueError("bad page number(s)")
# get underlying pdf document,
pdf = _as_pdf_document(self)
# create page sub-pdf via pdf_rearrange_pages2().
#
if mupdf_version_tuple >= (1, 25, 3):
# We use PDF_CLEAN_STRUCTURE_KEEP otherwise we lose structure tree
# which, for example, breaks test_3705.
mupdf.pdf_rearrange_pages2(pdf, pyliste, mupdf.PDF_CLEAN_STRUCTURE_KEEP)
else:
mupdf.pdf_rearrange_pages2(pdf, pyliste)
# remove any existing pages with their kids
self._reset_page_refs()
def set_language(self, language=None):
pdf = _as_pdf_document(self)
if not language:
lang = mupdf.FZ_LANG_UNSET
else:
lang = mupdf.fz_text_language_from_string(language)
mupdf.pdf_set_document_language(pdf, lang)
return True
def set_layer(self, config, basestate=None, on=None, off=None, rbgroups=None, locked=None):
"""Set the PDF keys /ON, /OFF, /RBGroups of an OC layer."""
if self.is_closed:
raise ValueError("document closed")
ocgs = set(self.get_ocgs().keys())
if ocgs == set():
raise ValueError("document has no optional content")
if on:
if type(on) not in (list, tuple):
raise ValueError("bad type: 'on'")
s = set(on).difference(ocgs)
if s != set():
raise ValueError("bad OCGs in 'on': %s" % s)
if off:
if type(off) not in (list, tuple):
raise ValueError("bad type: 'off'")
s = set(off).difference(ocgs)
if s != set():
raise ValueError("bad OCGs in 'off': %s" % s)
if locked:
if type(locked) not in (list, tuple):
raise ValueError("bad type: 'locked'")
s = set(locked).difference(ocgs)
if s != set():
raise ValueError("bad OCGs in 'locked': %s" % s)
if rbgroups:
if type(rbgroups) not in (list, tuple):
raise ValueError("bad type: 'rbgroups'")
for x in rbgroups:
if not type(x) in (list, tuple):
raise ValueError("bad RBGroup '%s'" % x)
s = set(x).difference(ocgs)
if s != set():
raise ValueError("bad OCGs in RBGroup: %s" % s)
if basestate:
basestate = str(basestate).upper()
if basestate == "UNCHANGED":
basestate = "Unchanged"
if basestate not in ("ON", "OFF", "Unchanged"):
raise ValueError("bad 'basestate'")
pdf = _as_pdf_document(self)
ocp = mupdf.pdf_dict_getl(
mupdf.pdf_trailer( pdf),
PDF_NAME('Root'),
PDF_NAME('OCProperties'),
)
if not ocp.m_internal:
return
if config == -1:
obj = mupdf.pdf_dict_get( ocp, PDF_NAME('D'))
else:
obj = mupdf.pdf_array_get(
mupdf.pdf_dict_get( ocp, PDF_NAME('Configs')),
config,
)
if not obj.m_internal:
raise ValueError( MSG_BAD_OC_CONFIG)
JM_set_ocg_arrays( obj, basestate, on, off, rbgroups, locked)
mupdf.ll_pdf_read_ocg( pdf.m_internal)
def set_layer_ui_config(self, number, action=0):
"""Set / unset OC intent configuration."""
# The user might have given the name instead of sequence number,
# so select by that name and continue with corresp. number
if isinstance(number, str):
select = [ui["number"] for ui in self.layer_ui_configs() if ui["text"] == number]
if select == []:
raise ValueError(f"bad OCG '{number}'.")
number = select[0] # this is the number for the name
pdf = _as_pdf_document(self)
if action == 1:
mupdf.pdf_toggle_layer_config_ui(pdf, number)
elif action == 2:
mupdf.pdf_deselect_layer_config_ui(pdf, number)
else:
mupdf.pdf_select_layer_config_ui(pdf, number)
def set_markinfo(self, markinfo: dict) -> bool:
"""Set the PDF MarkInfo values."""
xref = self.pdf_catalog()
if xref == 0:
raise ValueError("not a PDF")
if not markinfo or not isinstance(markinfo, dict):
return False
valid = {"Marked": False, "UserProperties": False, "Suspects": False}
if not set(valid.keys()).issuperset(markinfo.keys()):
badkeys = f"bad MarkInfo key(s): {set(markinfo.keys()).difference(valid.keys())}"
raise ValueError(badkeys)
pdfdict = "<<"
valid.update(markinfo)
for key, value in valid.items():
value=str(value).lower()
if value not in ("true", "false"):
raise ValueError(f"bad key value '{key}': '{value}'")
pdfdict += f"/{key} {value}"
pdfdict += ">>"
self.xref_set_key(xref, "MarkInfo", pdfdict)
return True
def set_metadata(doc: 'Document', m: dict = None) -> None:
"""Update the PDF /Info object.
Args:
m: a dictionary like doc.metadata.
"""
if not doc.is_pdf:
raise ValueError("is no PDF")
if doc.is_closed or doc.is_encrypted:
raise ValueError("document closed or encrypted")
if m is None:
m = {}
elif type(m) is not dict:
raise ValueError("bad metadata")
keymap = {
"author": "Author",
"producer": "Producer",
"creator": "Creator",
"title": "Title",
"format": None,
"encryption": None,
"creationDate": "CreationDate",
"modDate": "ModDate",
"subject": "Subject",
"keywords": "Keywords",
"trapped": "Trapped",
}
valid_keys = set(keymap.keys())
diff_set = set(m.keys()).difference(valid_keys)
if diff_set != set():
msg = "bad dict key(s): %s" % diff_set
raise ValueError(msg)
t, temp = doc.xref_get_key(-1, "Info")
if t != "xref":
info_xref = 0
else:
info_xref = int(temp.replace("0 R", ""))
if m == {} and info_xref == 0: # nothing to do
return
if info_xref == 0: # no prev metadata: get new xref
info_xref = doc.get_new_xref()
doc.update_object(info_xref, "<<>>") # fill it with empty object
doc.xref_set_key(-1, "Info", "%i 0 R" % info_xref)
elif m == {}: # remove existing metadata
doc.xref_set_key(-1, "Info", "null")
doc.init_doc()
return
for key, val in [(k, v) for k, v in m.items() if keymap[k] is not None]:
pdf_key = keymap[key]
if not bool(val) or val in ("none", "null"):
val = "null"
else:
val = get_pdf_str(val)
doc.xref_set_key(info_xref, pdf_key, val)
doc.init_doc()
return
def set_oc(doc: 'Document', xref: int, oc: int) -> None:
"""Attach optional content object to image or form xobject.
Args:
xref: (int) xref number of an image or form xobject
oc: (int) xref number of an OCG or OCMD
"""
if doc.is_closed or doc.is_encrypted:
raise ValueError("document close or encrypted")
t, name = doc.xref_get_key(xref, "Subtype")
if t != "name" or name not in ("/Image", "/Form"):
raise ValueError("bad object type at xref %i" % xref)
if oc > 0:
t, name = doc.xref_get_key(oc, "Type")
if t != "name" or name not in ("/OCG", "/OCMD"):
raise ValueError("bad object type at xref %i" % oc)
if oc == 0 and "OC" in doc.xref_get_keys(xref):
doc.xref_set_key(xref, "OC", "null")
return None
doc.xref_set_key(xref, "OC", "%i 0 R" % oc)
return None
def set_ocmd(
doc: 'Document',
xref: int = 0,
ocgs: typing.Union[list, None] = None,
policy: OptStr = None,
ve: typing.Union[list, None] = None,
) -> int:
"""Create or update an OCMD object in a PDF document.
Args:
xref: (int) 0 for creating a new object, otherwise update existing one.
ocgs: (list) OCG xref numbers, which shall be subject to 'policy'.
policy: one of 'AllOn', 'AllOff', 'AnyOn', 'AnyOff' (any casing).
ve: (list) visibility expression. Use instead of 'ocgs' with 'policy'.
Returns:
Xref of the created or updated OCMD.
"""
all_ocgs = set(doc.get_ocgs().keys())
def ve_maker(ve):
if type(ve) not in (list, tuple) or len(ve) < 2:
raise ValueError("bad 've' format: %s" % ve)
if ve[0].lower() not in ("and", "or", "not"):
raise ValueError("bad operand: %s" % ve[0])
if ve[0].lower() == "not" and len(ve) != 2:
raise ValueError("bad 've' format: %s" % ve)
item = "[/%s" % ve[0].title()
for x in ve[1:]:
if type(x) is int:
if x not in all_ocgs:
raise ValueError("bad OCG %i" % x)
item += " %i 0 R" % x
else:
item += " %s" % ve_maker(x)
item += "]"
return item
text = "<</Type/OCMD"
if ocgs and type(ocgs) in (list, tuple): # some OCGs are provided
s = set(ocgs).difference(all_ocgs) # contains illegal xrefs
if s != set():
msg = "bad OCGs: %s" % s
raise ValueError(msg)
text += "/OCGs[" + " ".join(map(lambda x: "%i 0 R" % x, ocgs)) + "]"
if policy:
policy = str(policy).lower()
pols = {
"anyon": "AnyOn",
"allon": "AllOn",
"anyoff": "AnyOff",
"alloff": "AllOff",
}
if policy not in ("anyon", "allon", "anyoff", "alloff"):
raise ValueError("bad policy: %s" % policy)
text += "/P/%s" % pols[policy]
if ve:
text += "/VE%s" % ve_maker(ve)
text += ">>"
# make new object or replace old OCMD (check type first)
if xref == 0:
xref = doc.get_new_xref()
elif "/Type/OCMD" not in doc.xref_object(xref, compressed=True):
raise ValueError("bad xref or not an OCMD")
doc.update_object(xref, text)
return xref
def set_pagelayout(self, pagelayout: str):
"""Set the PDF PageLayout value."""
valid = ("SinglePage", "OneColumn", "TwoColumnLeft", "TwoColumnRight", "TwoPageLeft", "TwoPageRight")
xref = self.pdf_catalog()
if xref == 0:
raise ValueError("not a PDF")
if not pagelayout:
raise ValueError("bad PageLayout value")
if pagelayout[0] == "/":
pagelayout = pagelayout[1:]
for v in valid:
if pagelayout.lower() == v.lower():
self.xref_set_key(xref, "PageLayout", f"/{v}")
return True
raise ValueError("bad PageLayout value")
def set_pagemode(self, pagemode: str):
"""Set the PDF PageMode value."""
valid = ("UseNone", "UseOutlines", "UseThumbs", "FullScreen", "UseOC", "UseAttachments")
xref = self.pdf_catalog()
if xref == 0:
raise ValueError("not a PDF")
if not pagemode:
raise ValueError("bad PageMode value")
if pagemode[0] == "/":
pagemode = pagemode[1:]
for v in valid:
if pagemode.lower() == v.lower():
self.xref_set_key(xref, "PageMode", f"/{v}")
return True
raise ValueError("bad PageMode value")
def set_page_labels(doc, labels):
"""Add / replace page label definitions in PDF document.
Args:
doc: PDF document (resp. 'self').
labels: list of label dictionaries like:
{'startpage': int, 'prefix': str, 'style': str, 'firstpagenum': int},
as returned by get_page_labels().
"""
# William Chapman, 2021-01-06
def create_label_str(label):
"""Convert Python label dict to corresponding PDF rule string.
Args:
label: (dict) build rule for the label.
Returns:
PDF label rule string wrapped in "<<", ">>".
"""
s = "%i<<" % label["startpage"]
if label.get("prefix", "") != "":
s += "/P(%s)" % label["prefix"]
if label.get("style", "") != "":
s += "/S/%s" % label["style"]
if label.get("firstpagenum", 1) > 1:
s += "/St %i" % label["firstpagenum"]
s += ">>"
return s
def create_nums(labels):
"""Return concatenated string of all labels rules.
Args:
labels: (list) dictionaries as created by function 'rule_dict'.
Returns:
PDF compatible string for page label definitions, ready to be
enclosed in PDF array 'Nums[...]'.
"""
labels.sort(key=lambda x: x["startpage"])
s = "".join([create_label_str(label) for label in labels])
return s
doc._set_page_labels(create_nums(labels))
def set_toc(
doc: 'Document',
toc: list,
collapse: int = 1,
) -> int:
"""Create new outline tree (table of contents, TOC).
Args:
toc: (list, tuple) each entry must contain level, title, page and
optionally top margin on the page. None or '()' remove the TOC.
collapse: (int) collapses entries beyond this level. Zero or None
shows all entries unfolded.
Returns:
the number of inserted items, or the number of removed items respectively.
"""
if doc.is_closed or doc.is_encrypted:
raise ValueError("document closed or encrypted")
if not doc.is_pdf:
raise ValueError("is no PDF")
if not toc: # remove all entries
return len(doc._delToC())
# validity checks --------------------------------------------------------
if type(toc) not in (list, tuple):
raise ValueError("'toc' must be list or tuple")
toclen = len(toc)
page_count = doc.page_count
t0 = toc[0]
if type(t0) not in (list, tuple):
raise ValueError("items must be sequences of 3 or 4 items")
if t0[0] != 1:
raise ValueError("hierarchy level of item 0 must be 1")
for i in list(range(toclen - 1)):
t1 = toc[i]
t2 = toc[i + 1]
if not -1 <= t1[2] <= page_count:
raise ValueError("row %i: page number out of range" % i)
if (type(t2) not in (list, tuple)) or len(t2) not in (3, 4):
raise ValueError("bad row %i" % (i + 1))
if (type(t2[0]) is not int) or t2[0] < 1:
raise ValueError("bad hierarchy level in row %i" % (i + 1))
if t2[0] > t1[0] + 1:
raise ValueError("bad hierarchy level in row %i" % (i + 1))
# no formal errors in toc --------------------------------------------------
# --------------------------------------------------------------------------
# make a list of xref numbers, which we can use for our TOC entries
# --------------------------------------------------------------------------
old_xrefs = doc._delToC() # del old outlines, get their xref numbers
# prepare table of xrefs for new bookmarks
old_xrefs = []
xref = [0] + old_xrefs
xref[0] = doc._getOLRootNumber() # entry zero is outline root xref number
if toclen > len(old_xrefs): # too few old xrefs?
for i in range((toclen - len(old_xrefs))):
xref.append(doc.get_new_xref()) # acquire new ones
lvltab = {0: 0} # to store last entry per hierarchy level
# ------------------------------------------------------------------------------
# contains new outline objects as strings - first one is the outline root
# ------------------------------------------------------------------------------
olitems = [{"count": 0, "first": -1, "last": -1, "xref": xref[0]}]
# ------------------------------------------------------------------------------
# build olitems as a list of PDF-like connected dictionaries
# ------------------------------------------------------------------------------
for i in range(toclen):
o = toc[i]
lvl = o[0] # level
title = get_pdf_str(o[1]) # title
pno = min(doc.page_count - 1, max(0, o[2] - 1)) # page number
page_xref = doc.page_xref(pno)
page_height = doc.page_cropbox(pno).height
top = Point(72, page_height - 36)
dest_dict = {"to": top, "kind": LINK_GOTO} # fall back target
if o[2] < 0:
dest_dict["kind"] = LINK_NONE
if len(o) > 3: # some target is specified
if type(o[3]) in (int, float): # convert a number to a point
dest_dict["to"] = Point(72, page_height - o[3])
else: # if something else, make sure we have a dict
# We make a copy of o[3] to avoid modifying our caller's data.
dest_dict = o[3].copy() if type(o[3]) is dict else dest_dict
if "to" not in dest_dict: # target point not in dict?
dest_dict["to"] = top # put default in
else: # transform target to PDF coordinates
page = doc[pno]
point = Point(dest_dict["to"])
point.y = page.cropbox.height - point.y
point = point * page.rotation_matrix
dest_dict["to"] = (point.x, point.y)
d = {}
d["first"] = -1
d["count"] = 0
d["last"] = -1
d["prev"] = -1
d["next"] = -1
d["dest"] = utils.getDestStr(page_xref, dest_dict)
d["top"] = dest_dict["to"]
d["title"] = title
d["parent"] = lvltab[lvl - 1]
d["xref"] = xref[i + 1]
d["color"] = dest_dict.get("color")
d["flags"] = dest_dict.get("italic", 0) + 2 * dest_dict.get("bold", 0)
lvltab[lvl] = i + 1
parent = olitems[lvltab[lvl - 1]] # the parent entry
if (
dest_dict.get("collapse") or collapse and lvl > collapse
): # suppress expansion
parent["count"] -= 1 # make /Count negative
else:
parent["count"] += 1 # positive /Count
if parent["first"] == -1:
parent["first"] = i + 1
parent["last"] = i + 1
else:
d["prev"] = parent["last"]
prev = olitems[parent["last"]]
prev["next"] = i + 1
parent["last"] = i + 1
olitems.append(d)
# ------------------------------------------------------------------------------
# now create each outline item as a string and insert it in the PDF
# ------------------------------------------------------------------------------
for i, ol in enumerate(olitems):
txt = "<<"
if ol["count"] != 0:
txt += "/Count %i" % ol["count"]
try:
txt += ol["dest"]
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose >= 2: exception_info()
pass
try:
if ol["first"] > -1:
txt += "/First %i 0 R" % xref[ol["first"]]
except Exception:
if g_exceptions_verbose >= 2: exception_info()
pass
try:
if ol["last"] > -1:
txt += "/Last %i 0 R" % xref[ol["last"]]
except Exception:
if g_exceptions_verbose >= 2: exception_info()
pass
try:
if ol["next"] > -1:
txt += "/Next %i 0 R" % xref[ol["next"]]
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose >= 2: exception_info()
pass
try:
if ol["parent"] > -1:
txt += "/Parent %i 0 R" % xref[ol["parent"]]
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose >= 2: exception_info()
pass
try:
if ol["prev"] > -1:
txt += "/Prev %i 0 R" % xref[ol["prev"]]
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose >= 2: exception_info()
pass
try:
txt += "/Title" + ol["title"]
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose >= 2: exception_info()
pass
if ol.get("color") and len(ol["color"]) == 3:
txt += f"/C[ {_format_g(tuple(ol['color']))}]"
if ol.get("flags", 0) > 0:
txt += "/F %i" % ol["flags"]
if i == 0: # special: this is the outline root
txt += "/Type/Outlines" # so add the /Type entry
txt += ">>"
doc.update_object(xref[i], txt) # insert the PDF object
doc.init_doc()
return toclen
def set_toc_item(
doc: 'Document',
idx: int,
dest_dict: OptDict = None,
kind: OptInt = None,
pno: OptInt = None,
uri: OptStr = None,
title: OptStr = None,
to: point_like = None,
filename: OptStr = None,
zoom: float = 0,
) -> None:
"""Update TOC item by index.
It allows changing the item's title and link destination.
Args:
idx:
(int) desired index of the TOC list, as created by get_toc.
dest_dict:
(dict) destination dictionary as created by get_toc(False).
Outrules all other parameters. If None, the remaining parameters
are used to make a dest dictionary.
kind:
(int) kind of link (pymupdf.LINK_GOTO, etc.). If None, then only
the title will be updated. If pymupdf.LINK_NONE, the TOC item will
be deleted.
pno:
(int) page number (1-based like in get_toc). Required if
pymupdf.LINK_GOTO.
uri:
(str) the URL, required if pymupdf.LINK_URI.
title:
(str) the new title. No change if None.
to:
(point-like) destination on the target page. If omitted, (72, 36)
will be used as target coordinates.
filename:
(str) destination filename, required for pymupdf.LINK_GOTOR and
pymupdf.LINK_LAUNCH.
name:
(str) a destination name for pymupdf.LINK_NAMED.
zoom:
(float) a zoom factor for the target location (pymupdf.LINK_GOTO).
"""
xref = doc.get_outline_xrefs()[idx]
page_xref = 0
if type(dest_dict) is dict:
if dest_dict["kind"] == LINK_GOTO:
pno = dest_dict["page"]
page_xref = doc.page_xref(pno)
page_height = doc.page_cropbox(pno).height
to = dest_dict.get('to', Point(72, 36))
to.y = page_height - to.y
dest_dict["to"] = to
action = utils.getDestStr(page_xref, dest_dict)
if not action.startswith("/A"):
raise ValueError("bad bookmark dest")
color = dest_dict.get("color")
if color:
color = list(map(float, color))
if len(color) != 3 or min(color) < 0 or max(color) > 1:
raise ValueError("bad color value")
bold = dest_dict.get("bold", False)
italic = dest_dict.get("italic", False)
flags = italic + 2 * bold
collapse = dest_dict.get("collapse")
return doc._update_toc_item(
xref,
action=action[2:],
title=title,
color=color,
flags=flags,
collapse=collapse,
)
if kind == LINK_NONE: # delete bookmark item
return doc.del_toc_item(idx)
if kind is None and title is None: # treat as no-op
return None
if kind is None: # only update title text
return doc._update_toc_item(xref, action=None, title=title)
if kind == LINK_GOTO:
if pno is None or pno not in range(1, doc.page_count + 1):
raise ValueError("bad page number")
page_xref = doc.page_xref(pno - 1)
page_height = doc.page_cropbox(pno - 1).height
if to is None:
to = Point(72, page_height - 36)
else:
to = Point(to)
to.y = page_height - to.y
ddict = {
"kind": kind,
"to": to,
"uri": uri,
"page": pno,
"file": filename,
"zoom": zoom,
}
action = utils.getDestStr(page_xref, ddict)
if action == "" or not action.startswith("/A"):
raise ValueError("bad bookmark dest")
return doc._update_toc_item(xref, action=action[2:], title=title)
def set_xml_metadata(self, metadata):
"""Store XML document level metadata."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
root = mupdf.pdf_dict_get( mupdf.pdf_trailer( pdf), PDF_NAME('Root'))
if not root.m_internal:
RAISEPY( MSG_BAD_PDFROOT, JM_Exc_FileDataError)
res = mupdf.fz_new_buffer_from_copied_data( metadata.encode('utf-8'))
xml = mupdf.pdf_dict_get( root, PDF_NAME('Metadata'))
if xml.m_internal:
JM_update_stream( pdf, xml, res, 0)
else:
xml = mupdf.pdf_add_stream( pdf, res, mupdf.PdfObj(), 0)
mupdf.pdf_dict_put( xml, PDF_NAME('Type'), PDF_NAME('Metadata'))
mupdf.pdf_dict_put( xml, PDF_NAME('Subtype'), PDF_NAME('XML'))
mupdf.pdf_dict_put( root, PDF_NAME('Metadata'), xml)
def subset_fonts(doc: 'Document', verbose: bool = False, fallback: bool = False) -> OptInt:
"""Build font subsets in a PDF.
Eligible fonts are potentially replaced by smaller versions. Page text is
NOT rewritten and thus should retain properties like being hidden or
controlled by optional content.
This method by default uses MuPDF's own internal feature to create subset
fonts. As this is a new function, errors may still occur. In this case,
please fall back to using the previous version by using "fallback=True".
Fallback mode requires the external package 'fontTools'.
Args:
fallback: use the older deprecated implementation.
verbose: only used by fallback mode.
Returns:
The new MuPDF-based code returns None. The deprecated fallback
mode returns 0 if there are no fonts to subset. Otherwise, it
returns the decrease in fontsize (the difference in fontsize),
measured in bytes.
"""
# Font binaries: - "buffer" -> (names, xrefs, (unicodes, glyphs))
# An embedded font is uniquely defined by its fontbuffer only. It may have
# multiple names and xrefs.
# Once the sets of used unicodes and glyphs are known, we compute a
# smaller version of the buffer user package fontTools.
if not fallback: # by default use MuPDF function
pdf = mupdf.pdf_document_from_fz_document(doc)
mupdf.pdf_subset_fonts2(pdf, list(range(doc.page_count)))
return
font_buffers = {}
def get_old_widths(xref):
"""Retrieve old font '/W' and '/DW' values."""
df = doc.xref_get_key(xref, "DescendantFonts")
if df[0] != "array": # only handle xref specifications
return None, None
df_xref = int(df[1][1:-1].replace("0 R", ""))
widths = doc.xref_get_key(df_xref, "W")
if widths[0] != "array": # no widths key found
widths = None
else:
widths = widths[1]
dwidths = doc.xref_get_key(df_xref, "DW")
if dwidths[0] != "int":
dwidths = None
else:
dwidths = dwidths[1]
return widths, dwidths
def set_old_widths(xref, widths, dwidths):
"""Restore the old '/W' and '/DW' in subsetted font.
If either parameter is None or evaluates to False, the corresponding
dictionary key will be set to null.
"""
df = doc.xref_get_key(xref, "DescendantFonts")
if df[0] != "array": # only handle xref specs
return None
df_xref = int(df[1][1:-1].replace("0 R", ""))
if (type(widths) is not str or not widths) and doc.xref_get_key(df_xref, "W")[
0
] != "null":
doc.xref_set_key(df_xref, "W", "null")
else:
doc.xref_set_key(df_xref, "W", widths)
if (type(dwidths) is not str or not dwidths) and doc.xref_get_key(
df_xref, "DW"
)[0] != "null":
doc.xref_set_key(df_xref, "DW", "null")
else:
doc.xref_set_key(df_xref, "DW", dwidths)
return None
def set_subset_fontname(new_xref):
"""Generate a name prefix to tag a font as subset.
We use a random generator to select 6 upper case ASCII characters.
The prefixed name must be put in the font xref as the "/BaseFont" value
and in the FontDescriptor object as the '/FontName' value.
"""
# The following generates a prefix like 'ABCDEF+'
import random
import string
prefix = "".join(random.choices(tuple(string.ascii_uppercase), k=6)) + "+"
font_str = doc.xref_object(new_xref, compressed=True)
font_str = font_str.replace("/BaseFont/", "/BaseFont/" + prefix)
df = doc.xref_get_key(new_xref, "DescendantFonts")
if df[0] == "array":
df_xref = int(df[1][1:-1].replace("0 R", ""))
fd = doc.xref_get_key(df_xref, "FontDescriptor")
if fd[0] == "xref":
fd_xref = int(fd[1].replace("0 R", ""))
fd_str = doc.xref_object(fd_xref, compressed=True)
fd_str = fd_str.replace("/FontName/", "/FontName/" + prefix)
doc.update_object(fd_xref, fd_str)
doc.update_object(new_xref, font_str)
def build_subset(buffer, unc_set, gid_set):
"""Build font subset using fontTools.
Args:
buffer: (bytes) the font given as a binary buffer.
unc_set: (set) required glyph ids.
Returns:
Either None if subsetting is unsuccessful or the subset font buffer.
"""
try:
import fontTools.subset as fts
except ImportError:
if g_exceptions_verbose: exception_info()
message("This method requires fontTools to be installed.")
raise
import tempfile
with tempfile.TemporaryDirectory() as tmp_dir:
oldfont_path = f"{tmp_dir}/oldfont.ttf"
newfont_path = f"{tmp_dir}/newfont.ttf"
uncfile_path = f"{tmp_dir}/uncfile.txt"
args = [
oldfont_path,
"--retain-gids",
f"--output-file={newfont_path}",
"--layout-features=*",
"--passthrough-tables",
"--ignore-missing-glyphs",
"--ignore-missing-unicodes",
"--symbol-cmap",
]
# store glyph ids or unicodes as file
with io.open(f"{tmp_dir}/uncfile.txt", "w", encoding='utf8') as unc_file:
if 0xFFFD in unc_set: # error unicode exists -> use glyphs
args.append(f"--gids-file={uncfile_path}")
gid_set.add(189)
unc_list = list(gid_set)
for unc in unc_list:
unc_file.write("%i\n" % unc)
else:
args.append(f"--unicodes-file={uncfile_path}")
unc_set.add(255)
unc_list = list(unc_set)
for unc in unc_list:
unc_file.write("%04x\n" % unc)
# store fontbuffer as a file
with io.open(oldfont_path, "wb") as fontfile:
fontfile.write(buffer)
try:
os.remove(newfont_path) # remove old file
except Exception:
pass
try: # invoke fontTools subsetter
fts.main(args)
font = Font(fontfile=newfont_path)
new_buffer = font.buffer # subset font binary
if font.glyph_count == 0: # intercept empty font
new_buffer = None
except Exception:
exception_info()
new_buffer = None
return new_buffer
def repl_fontnames(doc):
"""Populate 'font_buffers'.
For each font candidate, store its xref and the list of names
by which PDF text may refer to it (there may be multiple).
"""
def norm_name(name):
"""Recreate font name that contains PDF hex codes.
E.g. #20 -> space, chr(32)
"""
while "#" in name:
p = name.find("#")
c = int(name[p + 1 : p + 3], 16)
name = name.replace(name[p : p + 3], chr(c))
return name
def get_fontnames(doc, item):
"""Return a list of fontnames for an item of page.get_fonts().
There may be multiple names e.g. for Type0 fonts.
"""
fontname = item[3]
names = [fontname]
fontname = doc.xref_get_key(item[0], "BaseFont")[1][1:]
fontname = norm_name(fontname)
if fontname not in names:
names.append(fontname)
descendents = doc.xref_get_key(item[0], "DescendantFonts")
if descendents[0] != "array":
return names
descendents = descendents[1][1:-1]
if descendents.endswith(" 0 R"):
xref = int(descendents[:-4])
descendents = doc.xref_object(xref, compressed=True)
p1 = descendents.find("/BaseFont")
if p1 >= 0:
p2 = descendents.find("/", p1 + 1)
p1 = min(descendents.find("/", p2 + 1), descendents.find(">>", p2 + 1))
fontname = descendents[p2 + 1 : p1]
fontname = norm_name(fontname)
if fontname not in names:
names.append(fontname)
return names
for i in range(doc.page_count):
for f in doc.get_page_fonts(i, full=True):
font_xref = f[0] # font xref
font_ext = f[1] # font file extension
basename = f[3] # font basename
if font_ext not in ( # skip if not supported by fontTools
"otf",
"ttf",
"woff",
"woff2",
):
continue
# skip fonts which already are subsets
if len(basename) > 6 and basename[6] == "+":
continue
extr = doc.extract_font(font_xref)
fontbuffer = extr[-1]
names = get_fontnames(doc, f)
name_set, xref_set, subsets = font_buffers.get(
fontbuffer, (set(), set(), (set(), set()))
)
xref_set.add(font_xref)
for name in names:
name_set.add(name)
font = Font(fontbuffer=fontbuffer)
name_set.add(font.name)
del font
font_buffers[fontbuffer] = (name_set, xref_set, subsets)
def find_buffer_by_name(name):
for buffer, (name_set, _, _) in font_buffers.items():
if name in name_set:
return buffer
return None
# -----------------
# main function
# -----------------
repl_fontnames(doc) # populate font information
if not font_buffers: # nothing found to do
if verbose:
message(f'No fonts to subset.')
return 0
old_fontsize = 0
new_fontsize = 0
for fontbuffer in font_buffers.keys():
old_fontsize += len(fontbuffer)
# Scan page text for usage of subsettable fonts
for page in doc:
# go through the text and extend set of used glyphs by font
# we use a modified MuPDF trace device, which delivers us glyph ids.
for span in page.get_texttrace():
if type(span) is not dict: # skip useless information
continue
fontname = span["font"][:33] # fontname for the span
buffer = find_buffer_by_name(fontname)
if buffer is None:
continue
name_set, xref_set, (set_ucs, set_gid) = font_buffers[buffer]
for c in span["chars"]:
set_ucs.add(c[0]) # unicode
set_gid.add(c[1]) # glyph id
font_buffers[buffer] = (name_set, xref_set, (set_ucs, set_gid))
# build the font subsets
for old_buffer, (name_set, xref_set, subsets) in font_buffers.items():
new_buffer = build_subset(old_buffer, subsets[0], subsets[1])
fontname = list(name_set)[0]
if new_buffer is None or len(new_buffer) >= len(old_buffer):
# subset was not created or did not get smaller
if verbose:
message(f'Cannot subset {fontname!r}.')
continue
if verbose:
message(f"Built subset of font {fontname!r}.")
val = doc._insert_font(fontbuffer=new_buffer) # store subset font in PDF
new_xref = val[0] # get its xref
set_subset_fontname(new_xref) # tag fontname as subset font
font_str = doc.xref_object( # get its object definition
new_xref,
compressed=True,
)
# walk through the original font xrefs and replace each by the subset def
for font_xref in xref_set:
# we need the original '/W' and '/DW' width values
width_table, def_width = get_old_widths(font_xref)
# ... and replace original font definition at xref with it
doc.update_object(font_xref, font_str)
# now copy over old '/W' and '/DW' values
if width_table or def_width:
set_old_widths(font_xref, width_table, def_width)
# 'new_xref' remains unused in the PDF and must be removed
# by garbage collection.
new_fontsize += len(new_buffer)
return old_fontsize - new_fontsize
def switch_layer(self, config, as_default=0):
"""Activate an OC layer."""
pdf = _as_pdf_document(self)
cfgs = mupdf.pdf_dict_getl(
mupdf.pdf_trailer( pdf),
PDF_NAME('Root'),
PDF_NAME('OCProperties'),
PDF_NAME('Configs')
)
if not mupdf.pdf_is_array( cfgs) or not mupdf.pdf_array_len( cfgs):
if config < 1:
return
raise ValueError( MSG_BAD_OC_LAYER)
if config < 0:
return
mupdf.pdf_select_layer_config( pdf, config)
if as_default:
mupdf.pdf_set_layer_config_as_default( pdf)
mupdf.ll_pdf_read_ocg( pdf.m_internal)
def update_object(self, xref, text, page=None):
"""Replace object definition source."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len(pdf)
if not _INRANGE(xref, 1, xreflen-1):
RAISEPY("bad xref", MSG_BAD_XREF)
ENSURE_OPERATION(pdf)
# create new object with passed-in string
new_obj = JM_pdf_obj_from_str(pdf, text)
mupdf.pdf_update_object(pdf, xref, new_obj)
if page:
JM_refresh_links( _as_pdf_page(page))
def update_stream(self, xref=0, stream=None, new=1, compress=1):
"""Replace xref stream part."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len(pdf)
if xref < 1 or xref > xreflen:
raise ValueError( MSG_BAD_XREF)
# get the object
obj = mupdf.pdf_new_indirect(pdf, xref, 0)
if not mupdf.pdf_is_dict(obj):
raise ValueError( MSG_IS_NO_DICT)
res = JM_BufferFromBytes(stream)
if not res.m_internal:
raise TypeError( MSG_BAD_BUFFER)
JM_update_stream(pdf, obj, res, compress)
pdf.dirty = 1
@property
def version_count(self):
'''
Count versions of PDF document.
'''
pdf = _as_pdf_document(self, required=0)
if pdf.m_internal:
return mupdf.pdf_count_versions(pdf)
return 0
def write(
self,
garbage=False,
clean=False,
deflate=False,
deflate_images=False,
deflate_fonts=False,
incremental=False,
ascii=False,
expand=False,
linear=False,
no_new_id=False,
appearance=False,
pretty=False,
encryption=1,
permissions=4095,
owner_pw=None,
user_pw=None,
preserve_metadata=1,
use_objstms=0,
compression_effort=0,
):
from io import BytesIO
bio = BytesIO()
self.save(
bio,
garbage=garbage,
clean=clean,
no_new_id=no_new_id,
appearance=appearance,
deflate=deflate,
deflate_images=deflate_images,
deflate_fonts=deflate_fonts,
incremental=incremental,
ascii=ascii,
expand=expand,
linear=linear,
pretty=pretty,
encryption=encryption,
permissions=permissions,
owner_pw=owner_pw,
user_pw=user_pw,
preserve_metadata=preserve_metadata,
use_objstms=use_objstms,
compression_effort=compression_effort,
)
return bio.getvalue()
def tobytes(self, *args, **kwargs):
return self.write(*args, **kwargs)
@property
def xref(self):
"""PDF xref number of page."""
CheckParent(self)
return self.parent.page_xref(self.number)
def xref_copy(doc: 'Document', source: int, target: int, *, keep: list = None) -> None:
"""Copy a PDF dictionary object to another one given their xref numbers.
Args:
doc: PDF document object
source: source xref number
target: target xref number, the xref must already exist
keep: an optional list of 1st level keys in target that should not be
removed before copying.
Notes:
This works similar to the copy() method of dictionaries in Python. The
source may be a stream object.
"""
if doc.xref_is_stream(source):
# read new xref stream, maintaining compression
stream = doc.xref_stream_raw(source)
doc.update_stream(
target,
stream,
compress=False, # keeps source compression
new=True, # in case target is no stream
)
# empty the target completely, observe exceptions
if keep is None:
keep = []
for key in doc.xref_get_keys(target):
if key in keep:
continue
doc.xref_set_key(target, key, "null")
# copy over all source dict items
for key in doc.xref_get_keys(source):
item = doc.xref_get_key(source, key)
doc.xref_set_key(target, key, item[1])
def xref_get_key(self, xref, key):
"""Get PDF dict key value of object at 'xref'."""
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len(pdf)
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref > 0:
obj = mupdf.pdf_load_object(pdf, xref)
else:
obj = mupdf.pdf_trailer(pdf)
if not obj.m_internal:
return ("null", "null")
subobj = mupdf.pdf_dict_getp(obj, key)
if not subobj.m_internal:
return ("null", "null")
text = None
if mupdf.pdf_is_indirect(subobj):
type = "xref"
text = "%i 0 R" % mupdf.pdf_to_num(subobj)
elif mupdf.pdf_is_array(subobj):
type = "array"
elif mupdf.pdf_is_dict(subobj):
type = "dict"
elif mupdf.pdf_is_int(subobj):
type = "int"
text = "%i" % mupdf.pdf_to_int(subobj)
elif mupdf.pdf_is_real(subobj):
type = "float"
elif mupdf.pdf_is_null(subobj):
type = "null"
text = "null"
elif mupdf.pdf_is_bool(subobj):
type = "bool"
if mupdf.pdf_to_bool(subobj):
text = "true"
else:
text = "false"
elif mupdf.pdf_is_name(subobj):
type = "name"
text = "/%s" % mupdf.pdf_to_name(subobj)
elif mupdf.pdf_is_string(subobj):
type = "string"
text = JM_UnicodeFromStr(mupdf.pdf_to_text_string(subobj))
else:
type = "unknown"
if text is None:
res = JM_object_to_buffer(subobj, 1, 0)
text = JM_UnicodeFromBuffer(res)
return (type, text)
def xref_get_keys(self, xref):
"""Get the keys of PDF dict object at 'xref'. Use -1 for the PDF trailer."""
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len( pdf)
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref > 0:
obj = mupdf.pdf_load_object( pdf, xref)
else:
obj = mupdf.pdf_trailer( pdf)
n = mupdf.pdf_dict_len( obj)
rc = []
if n == 0:
return rc
for i in range(n):
key = mupdf.pdf_to_name( mupdf.pdf_dict_get_key( obj, i))
rc.append(key)
return rc
def xref_is_font(self, xref):
"""Check if xref is a font object."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if self.xref_get_key(xref, "Type")[1] == "/Font":
return True
return False
def xref_is_image(self, xref):
"""Check if xref is an image object."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if self.xref_get_key(xref, "Subtype")[1] == "/Image":
return True
return False
def xref_is_stream(self, xref=0):
"""Check if xref is a stream object."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return False # not a PDF
return bool(mupdf.pdf_obj_num_is_stream(pdf, xref))
def xref_is_xobject(self, xref):
"""Check if xref is a form xobject."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if self.xref_get_key(xref, "Subtype")[1] == "/Form":
return True
return False
def xref_length(self):
"""Get length of xref table."""
xreflen = 0
pdf = _as_pdf_document(self, required=0)
if pdf.m_internal:
xreflen = mupdf.pdf_xref_len(pdf)
return xreflen
def xref_object(self, xref, compressed=0, ascii=0):
"""Get xref object source as a string."""
if self.is_closed:
raise ValueError("document closed")
if g_use_extra:
ret = extra.xref_object( self.this, xref, compressed, ascii)
return ret
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len(pdf)
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref > 0:
obj = mupdf.pdf_load_object(pdf, xref)
else:
obj = mupdf.pdf_trailer(pdf)
res = JM_object_to_buffer(mupdf.pdf_resolve_indirect(obj), compressed, ascii)
text = JM_EscapeStrFromBuffer(res)
return text
def xref_set_key(self, xref, key, value):
"""Set the value of a PDF dictionary key."""
if self.is_closed:
raise ValueError("document closed")
if not key or not isinstance(key, str) or INVALID_NAME_CHARS.intersection(key) not in (set(), {"/"}):
raise ValueError("bad 'key'")
if not isinstance(value, str) or not value or value[0] == "/" and INVALID_NAME_CHARS.intersection(value[1:]) != set():
raise ValueError("bad 'value'")
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len(pdf)
#if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
# THROWMSG("bad xref")
#if len(value) == 0:
# THROWMSG("bad 'value'")
#if len(key) == 0:
# THROWMSG("bad 'key'")
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref != -1:
obj = mupdf.pdf_load_object(pdf, xref)
else:
obj = mupdf.pdf_trailer(pdf)
new_obj = JM_set_object_value(obj, key, value)
if not new_obj.m_internal:
return # did not work: skip update
if xref != -1:
mupdf.pdf_update_object(pdf, xref, new_obj)
else:
n = mupdf.pdf_dict_len(new_obj)
for i in range(n):
mupdf.pdf_dict_put(
obj,
mupdf.pdf_dict_get_key(new_obj, i),
mupdf.pdf_dict_get_val(new_obj, i),
)
def xref_stream(self, xref):
"""Get decompressed xref stream."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len( pdf)
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref >= 0:
obj = mupdf.pdf_new_indirect( pdf, xref, 0)
else:
obj = mupdf.pdf_trailer( pdf)
r = None
if mupdf.pdf_is_stream( obj):
res = mupdf.pdf_load_stream_number( pdf, xref)
r = JM_BinFromBuffer( res)
return r
def xref_stream_raw(self, xref):
"""Get xref stream without decompression."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len( pdf)
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref >= 0:
obj = mupdf.pdf_new_indirect( pdf, xref, 0)
else:
obj = mupdf.pdf_trailer( pdf)
r = None
if mupdf.pdf_is_stream( obj):
res = mupdf.pdf_load_raw_stream_number( pdf, xref)
r = JM_BinFromBuffer( res)
return r
def xref_xml_metadata(self):
"""Get xref of document XML metadata."""
pdf = _as_pdf_document(self)
root = mupdf.pdf_dict_get( mupdf.pdf_trailer( pdf), PDF_NAME('Root'))
if not root.m_internal:
RAISEPY( MSG_BAD_PDFROOT, JM_Exc_FileDataError)
xml = mupdf.pdf_dict_get( root, PDF_NAME('Metadata'))
xref = 0
if xml.m_internal:
xref = mupdf.pdf_to_num( xml)
return xref
__slots__ = ('this', 'page_count2', 'this_is_pdf', '__dict__')
outline = property(lambda self: self._outline)
is_stream = xref_is_stream
open = Document
| Document |
python | kamyu104__LeetCode-Solutions | Python/check-if-string-is-a-prefix-of-array.py | {
"start": 29,
"end": 461
} | class ____(object):
def isPrefixString(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: bool
"""
i = j = 0
for c in s:
if i == len(words) or words[i][j] != c:
return False
j += 1
if j == len(words[i]):
i += 1
j = 0
return j == 0
# Time: O(n)
# Space: O(1)
| Solution |
python | sympy__sympy | sympy/functions/elementary/complexes.py | {
"start": 32363,
"end": 36345
} | class ____(DefinedFunction):
r"""
Represent the argument on a quotient of the Riemann surface of the
logarithm. That is, given a period $P$, always return a value in
$(-P/2, P/2]$, by using $\exp(PI) = 1$.
Examples
========
>>> from sympy import exp_polar, periodic_argument
>>> from sympy import I, pi
>>> periodic_argument(exp_polar(10*I*pi), 2*pi)
0
>>> periodic_argument(exp_polar(5*I*pi), 4*pi)
pi
>>> from sympy import exp_polar, periodic_argument
>>> from sympy import I, pi
>>> periodic_argument(exp_polar(5*I*pi), 2*pi)
pi
>>> periodic_argument(exp_polar(5*I*pi), 3*pi)
-pi
>>> periodic_argument(exp_polar(5*I*pi), pi)
0
Parameters
==========
ar : Expr
A polar number.
period : Expr
The period $P$.
See Also
========
sympy.functions.elementary.exponential.exp_polar
polar_lift : Lift argument to the Riemann surface of the logarithm
principal_branch
"""
@classmethod
def _getunbranched(cls, ar):
from sympy.functions.elementary.exponential import exp_polar, log
if ar.is_Mul:
args = ar.args
else:
args = [ar]
unbranched = 0
for a in args:
if not a.is_polar:
unbranched += arg(a)
elif isinstance(a, exp_polar):
unbranched += a.exp.as_real_imag()[1]
elif a.is_Pow:
re, im = a.exp.as_real_imag()
unbranched += re*unbranched_argument(
a.base) + im*log(abs(a.base))
elif isinstance(a, polar_lift):
unbranched += arg(a.args[0])
else:
return None
return unbranched
@classmethod
def eval(cls, ar, period):
# Our strategy is to evaluate the argument on the Riemann surface of the
# logarithm, and then reduce.
# NOTE evidently this means it is a rather bad idea to use this with
# period != 2*pi and non-polar numbers.
if not period.is_extended_positive:
return None
if period == oo and isinstance(ar, principal_branch):
return periodic_argument(*ar.args)
if isinstance(ar, polar_lift) and period >= 2*pi:
return periodic_argument(ar.args[0], period)
if ar.is_Mul:
newargs = [x for x in ar.args if not x.is_positive]
if len(newargs) != len(ar.args):
return periodic_argument(Mul(*newargs), period)
unbranched = cls._getunbranched(ar)
if unbranched is None:
return None
from sympy.functions.elementary.trigonometric import atan, atan2
if unbranched.has(periodic_argument, atan2, atan):
return None
if period == oo:
return unbranched
if period != oo:
from sympy.functions.elementary.integers import ceiling
n = ceiling(unbranched/period - S.Half)*period
if not n.has(ceiling):
return unbranched - n
def _eval_evalf(self, prec):
z, period = self.args
if period == oo:
unbranched = periodic_argument._getunbranched(z)
if unbranched is None:
return self
return unbranched._eval_evalf(prec)
ub = periodic_argument(z, oo)._eval_evalf(prec)
from sympy.functions.elementary.integers import ceiling
return (ub - ceiling(ub/period - S.Half)*period)._eval_evalf(prec)
def unbranched_argument(arg):
'''
Returns periodic argument of arg with period as infinity.
Examples
========
>>> from sympy import exp_polar, unbranched_argument
>>> from sympy import I, pi
>>> unbranched_argument(exp_polar(15*I*pi))
15*pi
>>> unbranched_argument(exp_polar(7*I*pi))
7*pi
See also
========
periodic_argument
'''
return periodic_argument(arg, oo)
| periodic_argument |
python | pytorch__pytorch | torch/distributed/elastic/multiprocessing/errors/__init__.py | {
"start": 7798,
"end": 14707
} | class ____(Exception):
"""
Special exception type that can be raised from a function annotated with the
``@record`` decorator to have the child process' (root exception) propagate
up the stack as-is (e.g. without being wrapped in the parent's traceback).
Useful in cases where the parent is a simple nanny process
and the child (worker) processes are actually doing meaningful compute.
In this case, errors typically occur on the child process as the parent
is not doing anything non-trivial, and child errors should be propagated
to the scheduler for accurate root cause diagnostics.
.. note:: The propagation relies on error files rather than exception handling to
support both function and binary launches.
Example:
::
# process tree on a host (container)
0: scheduler-init-process:
|- 1: torchelastic_agent:
|- 2: trainer_0 (ok)
|- 3: trainer_1 (fail) -> error.json
|- ...
|- n+2: trainer_n (ok)
|- n+3: other processes
|- ...
In the example above, trainer 1's failure (written into error.json) is
the root cause and should be reported to the scheduler's init process.
The torchelastic agent raises a ``ChildFailedError("trainer", {1: "trainer_1/error.json"})``
upon detecting trainer 1's failure which would propagate the contents
of trainer 1's error file to the scheduler's init process.
"""
def __init__(self, name: str, failures: dict[GlobalRank, ProcessFailure]):
self.name = name
self.failures = failures
assert (
self.failures
) # does not make sense to create a ChildFaileError with no failures
super().__init__(self.format_msg())
def get_first_failure(self) -> tuple[GlobalRank, ProcessFailure]:
rank = min(self.failures.keys(), key=lambda r: self.failures[r].timestamp)
return rank, self.failures[rank]
def format_msg(self, boarder_delim="=", section_delim="-"):
title = f"{self.name} FAILED"
root_rank, _root_failure = self.get_first_failure()
root_failure_fmt: str = ""
other_failures_fmt: list[str] = []
width = len(title)
for idx, (rank, failure) in enumerate(self.failures.items()):
fmt, w = self._format_failure(idx, rank, failure)
width = max(width, w)
if rank == root_rank:
root_failure_fmt = fmt
else:
other_failures_fmt.append(fmt)
# upper boundary on width
width = min(width, 60)
return Template(_MSG_FORMAT_TEMPLATE).substitute(
boarder=boarder_delim * width,
title=title,
section=section_delim * width,
root_failure=root_failure_fmt,
other_failures="\n".join(other_failures_fmt or [" <NO_OTHER_FAILURES>"]),
)
def _format_failure(
self, idx: int, rank: int, failure: ProcessFailure
) -> tuple[str, int]:
# failure.message is either a str (when the failure does not generate a traceback - e.g. signals)
# or a dict (json) of the form
# {"message": $ERROR_MSG, "extraInfo": {"py_callstack": $TRACEBACK, timestamp: $TS}}
# so the display logic is:
# 1. if failure.message is not a dict (it is a str) just show it as is
# 2. else try to get the traceback (py_callstack)
# 3. if the traceback is not there, use the message
# 4. if the message is not there show <N/A>
msg = failure.message
if isinstance(failure.message, dict):
msg = (
failure.message.get("extraInfo", {})
.get("py_callstack", failure.message.get("message", "<N/A>"))
.replace("\n", "\n ") # to properly indent the traceback
)
fmt = Template(_FAILURE_FORMAT_TEMPLATE).substitute(
idx=idx,
time=failure.timestamp_isoformat(),
hostname=socket.getfqdn(),
rank=rank,
local_rank=failure.local_rank,
exitcode=failure.exitcode,
pid=failure.pid,
error_file=failure.error_file,
message=msg,
)
width = 0
for line in fmt.split("\n"):
width = max(width, len(line))
return fmt, width
def record(
fn: Callable[_P, _R], error_handler: ErrorHandler | None = None
) -> Callable[_P, _R | None]:
"""
Syntactic sugar to record errors/exceptions that happened in the decorated
function using the provided ``error_handler``.
Using this decorator is equivalent to:
::
error_handler = get_error_handler()
error_handler.initialize()
try:
foobar()
except ChildFailedError as e:
_, failure = e.get_first_failure()
error_handler.dump_error_file(failure.error_file, failure.exitcode)
raise
except Exception as e:
error_handler.record_exception(e)
raise
.. important:: use this decorator once per process at the top level method,
typically this is the main method.
Example
::
@record
def main():
pass
if __name__ == "__main__":
main()
"""
if not error_handler:
error_handler = get_error_handler()
def wrap(f: Callable[_P, _R]) -> Callable[_P, _R | None]:
@wraps(f)
def wrapper(*args: _P.args, **kwargs: _P.kwargs):
assert error_handler is not None # assertion for mypy type checker
error_handler.initialize()
try:
return f(*args, **kwargs)
except SystemExit as se:
# For run_path based entrypoints, SystemExit with code = 0 will never exit.
# Handling it here by returning a value:
if se.code == 0:
return None
else:
raise
except ChildFailedError as e:
rank, failure = e.get_first_failure()
if failure.error_file != _NOT_AVAILABLE:
error_handler.dump_error_file(failure.error_file, failure.exitcode)
else:
logger.info(
(
"local_rank %s FAILED with no error file."
" Decorate your entrypoint fn with @record for traceback info."
" See: https://pytorch.org/docs/stable/elastic/errors.html",
rank,
)
)
raise
except Exception as e:
error_handler.record_exception(e)
raise
return wrapper
return wrap(fn)
| ChildFailedError |
python | ansible__ansible | lib/ansible/module_utils/errors.py | {
"start": 3153,
"end": 3250
} | class ____(AnsibleValidationError):
"""Incorrect type for subparameter"""
| SubParameterTypeError |
python | viewflow__viewflow | viewflow/workflow/flow/views/dashboard.py | {
"start": 600,
"end": 3213
} | class ____(
mixins.StoreRequestPathMixin,
mixins.ProcessViewTemplateNames,
generic.TemplateView,
):
"""Kanban-like process dashboard view."""
viewset = None
flow_class = None
template_filename = "process_dashboard.html"
MAX_ROWS = 26
# TODO queryset from viewset
# @viewprop
# def queryset(self):
# if self.viewset is not None and hasattr(self.viewset, 'get_task_queryset'):
# return self.viewset.get_queryset(self.request)
# return self.flow_class.task_class._default_manager
def get_context_data(self, **kwargs):
sorted_nodes, _ = chart.topsort(self.flow_class)
nodes = [
node
for node in sorted_nodes
if node.task_type in ["HUMAN", "JOB", "SUBPROCESS"]
]
start_nodes = [
{"node": node, "can_execute": node.can_execute(self.request.user)}
for node in self.flow_class.instance.get_start_nodes()
]
end_nodes = [node for node in sorted_nodes if node.task_type in ["END"]]
columns = []
for node in nodes:
columns.append(
{
"node": node,
"node_ref": get_task_ref(node),
"tasks": self.flow_class.task_class._default_manager.filter_available(
[self.flow_class], self.request.user
).filter(
Q(finished__isnull=True) | Q(status=STATUS.ERROR),
flow_task=node,
)[
: self.MAX_ROWS
],
}
)
finished = self.flow_class.task_class._default_manager.filter_available(
[self.flow_class], self.request.user
).filter(finished__isnull=False, flow_task__in=end_nodes)[: self.MAX_ROWS]
return super().get_context_data(
columns=columns,
start_nodes=start_nodes,
end_nodes=end_nodes,
finished=finished,
**kwargs,
)
def has_view_permission(self, user, obj=None):
if self.viewset is not None:
return self.viewset.has_view_permission(user, obj=obj)
else:
return has_object_perm(
user, "view", self.model, obj=obj
) or has_object_perm(user, "change", self.model, obj=obj)
def dispatch(self, request, *args, **kwargs):
if not self.has_view_permission(self.request.user):
raise PermissionDenied
return super().dispatch(request, *args, **kwargs)
| DashboardView |
python | huggingface__transformers | src/transformers/models/lfm2/configuration_lfm2.py | {
"start": 739,
"end": 8323
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Lfm2Model`]. It is used to instantiate a LFM2
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the LFM2-1.2B model.
e.g. [LiquidAI/LFM2-1.2B](https://huggingface.co/LiquidAI/LFM2-1.2B)
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 65536):
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`Lfm2Model`]
hidden_size (`int`, *optional*, defaults to 2560):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 12288):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 32):
Number of hidden layers in the Transformer decoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer decoder.
num_key_value_heads (`int`, *optional*, defaults to 8):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details, check out [this
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
`num_attention_heads`.
max_position_embeddings (`int`, *optional*, defaults to 128000):
The maximum sequence length that this model might ever be used with. Lfm2 1 supports up to 2048 tokens,
Lfm2 2 up to 4096, CodeLfm2 up to 16384.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the rms normalization layers.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
pad_token_id (`int`, *optional*, defaults to 0):
Padding token id.
bos_token_id (`int`, *optional*, defaults to 1):
Beginning of stream token id.
eos_token_id (`int`, *optional*, defaults to 2):
End of stream token id.
tie_word_embeddings (`bool`, *optional*, defaults to `True`):
Whether to tie weight embeddings
rope_parameters (`RopeParameters`, *optional*):
Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
with longer `max_position_embeddings`.
conv_bias (`bool`, *optional*, defaults to `False`):
Whether to use bias in the conv layers.
conv_L_cache (`int`, *optional*, defaults to 3):
L_cache dim in the conv layers.
block_multiple_of (`int`, *optional*, defaults to 256):
Multiple for the `intermediate_size`.
block_ffn_dim_multiplier (`float`, *optional*, defaults to 1.0):
Multiplier for the `intermediate_size`.
block_auto_adjust_ff_dim (`bool`, *optional*, defaults to `True`):
Whether to adjust the dim of the `intermediate_size`.
full_attn_idxs (`Optional`, *optional*):
Index of the layers which use attention.
layer_types (`Optional`, *optional*):
Type of each layers.
```python
>>> from transformers import Lfm2Model, Lfm2Config
>>> # Initializing a LFM2 model
>>> configuration = Lfm2Config()
>>> # Initializing a model from the LFM2-1.2B style configuration
>>> model = Lfm2Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "lfm2"
keys_to_ignore_at_inference = ["past_key_values"]
default_theta = 1000000.0
def __init__(
self,
vocab_size: Optional[int] = 65536,
hidden_size: Optional[int] = 2560,
intermediate_size: Optional[int] = 12288,
num_hidden_layers: Optional[int] = 32,
num_attention_heads: Optional[int] = 32,
num_key_value_heads: Optional[int] = 8,
max_position_embeddings: Optional[int] = 128_000,
initializer_range: Optional[float] = 0.02,
norm_eps: Optional[float] = 0.00001,
use_cache: Optional[bool] = True,
pad_token_id: Optional[int] = 0,
bos_token_id: Optional[int] = 1,
eos_token_id: Optional[int] = 2,
tie_word_embeddings: Optional[bool] = True,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
conv_bias: Optional[bool] = False,
conv_L_cache: Optional[int] = 3,
block_multiple_of: Optional[int] = 256,
block_ffn_dim_multiplier: Optional[float] = 1.0,
block_auto_adjust_ff_dim: Optional[bool] = True,
full_attn_idxs: Optional[list[int]] = None,
layer_types: Optional[list[str]] = None,
**kwargs,
):
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.max_position_embeddings = max_position_embeddings
self.use_cache = use_cache
self.norm_eps = norm_eps
self.initializer_range = initializer_range
# attn operator config
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
# custom operator config
self.conv_bias = conv_bias
self.conv_L_cache = conv_L_cache
# MLP config
self.intermediate_size = kwargs.get("block_ff_dim", intermediate_size) # to fit original config keys
self.block_multiple_of = block_multiple_of
self.block_ffn_dim_multiplier = block_ffn_dim_multiplier
self.block_auto_adjust_ff_dim = block_auto_adjust_ff_dim
self.layer_types = layer_types
if self.layer_types is None:
full_attn_idxs = full_attn_idxs if full_attn_idxs is not None else list(range(num_hidden_layers))
self.layer_types = ["full_attention" if i in full_attn_idxs else "conv" for i in range(num_hidden_layers)]
self.rope_parameters = rope_parameters
tie_word_embeddings = kwargs.get("tie_embedding", tie_word_embeddings) # to fit original config keys
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
__all__ = ["Lfm2Config"]
| Lfm2Config |
python | spack__spack | lib/spack/spack/llnl/util/filesystem.py | {
"start": 70100,
"end": 76581
} | class ____(FileList):
"""Sequence of absolute paths to headers.
Provides a few convenience methods to manipulate header paths and get
commonly used compiler flags or names.
"""
# Make sure to only match complete words, otherwise path components such
# as "xinclude" will cause false matches.
# Avoid matching paths such as <prefix>/include/something/detail/include,
# e.g. in the CUDA Toolkit which ships internal libc++ headers.
include_regex = re.compile(r"(.*?)(\binclude\b)(.*)")
def __init__(self, files):
super().__init__(files)
self._macro_definitions = []
self._directories = None
@property
def directories(self) -> List[str]:
"""Directories to be searched for header files."""
values = self._directories
if values is None:
values = self._default_directories()
return list(dedupe(values))
@directories.setter
def directories(self, value):
value = value or []
# Accept a single directory as input
if isinstance(value, str):
value = [value]
self._directories = [path_to_os_path(os.path.normpath(x))[0] for x in value]
def _default_directories(self):
"""Default computation of directories based on the list of
header files.
"""
dir_list = super().directories
values = []
for d in dir_list:
# If the path contains a subdirectory named 'include' then stop
# there and don't add anything else to the path.
m = self.include_regex.match(d)
value = os.path.join(*m.group(1, 2)) if m else d
values.append(value)
return values
@property
def headers(self) -> List[str]:
"""Stable de-duplication of the headers.
Returns:
A list of header files
"""
return self.files
@property
def names(self) -> List[str]:
"""Stable de-duplication of header names in the list without extensions
>>> h = HeaderList(["/dir1/a.h", "/dir2/b.h", "/dir3/a.h"])
>>> h.names
["a", "b"]
Returns:
A list of files without extensions
"""
names = []
for x in self.basenames:
name = x
# Valid extensions include: [".cuh", ".hpp", ".hh", ".h"]
for ext in [".cuh", ".hpp", ".hh", ".h"]:
i = name.rfind(ext)
if i != -1:
names.append(name[:i])
break
else:
# No valid extension, should we still include it?
names.append(name)
return list(dedupe(names))
@property
def include_flags(self) -> str:
"""Include flags
>>> h = HeaderList(["/dir1/a.h", "/dir1/b.h", "/dir2/c.h"])
>>> h.include_flags
"-I/dir1 -I/dir2"
Returns:
A joined list of include flags
"""
return " ".join(["-I" + x for x in self.directories])
@property
def macro_definitions(self) -> str:
"""Macro definitions
>>> h = HeaderList(["/dir1/a.h", "/dir1/b.h", "/dir2/c.h"])
>>> h.add_macro("-DBOOST_LIB_NAME=boost_regex")
>>> h.add_macro("-DBOOST_DYN_LINK")
>>> h.macro_definitions
"-DBOOST_LIB_NAME=boost_regex -DBOOST_DYN_LINK"
Returns:
A joined list of macro definitions
"""
return " ".join(self._macro_definitions)
@property
def cpp_flags(self) -> str:
"""Include flags + macro definitions
>>> h = HeaderList(["/dir1/a.h", "/dir1/b.h", "/dir2/c.h"])
>>> h.cpp_flags
"-I/dir1 -I/dir2"
>>> h.add_macro("-DBOOST_DYN_LINK")
>>> h.cpp_flags
"-I/dir1 -I/dir2 -DBOOST_DYN_LINK"
Returns:
A joined list of include flags and macro definitions
"""
cpp_flags = self.include_flags
if self.macro_definitions:
cpp_flags += " " + self.macro_definitions
return cpp_flags
def add_macro(self, macro: str) -> None:
"""Add a macro definition
Parameters:
macro: The macro to add
"""
self._macro_definitions.append(macro)
def find_headers(headers: Union[str, List[str]], root: str, recursive: bool = False) -> HeaderList:
"""Returns an iterable object containing a list of full paths to
headers if found.
Accepts any glob characters accepted by :py:func:`fnmatch.fnmatch`:
========== ====================================
Pattern Meaning
========== ====================================
``*`` matches one or more characters
``?`` matches any single character
``[seq]`` matches any character in ``seq``
``[!seq]`` matches any character not in ``seq``
========== ====================================
Parameters:
headers: Header name(s) to search for
root: The root directory to start searching from
recursive: if :data:`False` search only root folder,
if :data:`True` descends top-down from the root. Defaults to :data:`False`.
Returns:
The headers that have been found
"""
if isinstance(headers, str):
headers = [headers]
elif not isinstance(headers, collections.abc.Sequence):
message = "{0} expects a string or sequence of strings as the "
message += "first argument [got {1} instead]"
message = message.format(find_headers.__name__, type(headers))
raise TypeError(message)
# Construct the right suffix for the headers
suffixes = [
# C
"h",
# C++
"hpp",
"hxx",
"hh",
"H",
"txx",
"tcc",
"icc",
# Fortran
"mod",
"inc",
]
# List of headers we are searching with suffixes
headers = ["{0}.{1}".format(header, suffix) for header in headers for suffix in suffixes]
return HeaderList(find(root, headers, recursive))
@system_path_filter
def find_all_headers(root: str) -> HeaderList:
"""Convenience function that returns the list of all headers found
in the directory passed as argument.
Args:
root: directory where to look recursively for header files
Returns:
List of all headers found in ``root`` and subdirectories.
"""
return find_headers("*", root=root, recursive=True)
| HeaderList |
python | great-expectations__great_expectations | docs/docusaurus/docs/snippets/unexpected_row_expectation.py | {
"start": 1178,
"end": 2455
} | class ____(UnexpectedRowsExpectation):
unexpected_rows_query: str = """
SELECT
vendor_id, pickup_datetime
FROM
postgres_taxi_data
WHERE
trip_distance > 20
"""
description = "Trips should be less than 20 miles"
# </snippet>
# <snippet name="docs/docusaurus/docs/snippets/unexpected_row_expectation.py define_batch_definition">
batch_definition = (
context.data_sources.add_postgres(
name="pg_datasource", connection_string=PG_CONNECTION_STRING
)
.add_table_asset(name="postgres_taxi_data", table_name="postgres_taxi_data")
.add_batch_definition_daily(name="daily", column="pickup_datetime")
)
# </snippet>
# <snippet name="docs/docusaurus/docs/snippets/unexpected_row_expectation.py define_expectation_suite">
expectation = UnexpectedTripDistance()
suite = context.suites.add(ExpectationSuite("my_suite", expectations=[expectation]))
# </snippet>
# <snippet name="docs/docusaurus/docs/snippets/unexpected_row_expectation.py validate_suite">
validation_definition = ValidationDefinition(
name="my_validation", data=batch_definition, suite=suite
)
result = validation_definition.run()
# </snippet>
assert not result.success
assert len(result.results) == 1
| UnexpectedTripDistance |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 101553,
"end": 104340
} | class ____(Request):
"""
Move models to a project
:param ids: Models to move
:type ids: Sequence[str]
:param project: Target project ID. If not provided, `project_name` must be
provided.
:type project: str
:param project_name: Target project name. If provided and a project with this
name does not exist, a new project will be created. If not provided, `project`
must be provided.
:type project_name: str
"""
_service = "models"
_action = "move"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"ids": {
"description": "Models to move",
"items": {"type": "string"},
"type": "array",
},
"project": {
"description": "Target project ID. If notprovided, `project_name` must beprovided.",
"type": "string",
},
"project_name": {
"description": "Target project name. Ifprovided and a project withthis name does not exist, anew project will be created.If not provided, `project`must be provided.",
"type": "string",
},
},
"required": ["ids"],
"type": "object",
}
def __init__(
self, ids: List[str], project: Optional[str] = None, project_name: Optional[str] = None, **kwargs: Any
) -> None:
super(MoveRequest, self).__init__(**kwargs)
self.ids = ids
self.project = project
self.project_name = project_name
@schema_property("ids")
def ids(self) -> List[str]:
return self._property_ids
@ids.setter
def ids(self, value: List[str]) -> None:
if value is None:
self._property_ids = None
return
self.assert_isinstance(value, "ids", (list, tuple))
self.assert_isinstance(value, "ids", six.string_types, is_array=True)
self._property_ids = value
@schema_property("project")
def project(self) -> Optional[str]:
return self._property_project
@project.setter
def project(self, value: Optional[str]) -> None:
if value is None:
self._property_project = None
return
self.assert_isinstance(value, "project", six.string_types)
self._property_project = value
@schema_property("project_name")
def project_name(self) -> Optional[str]:
return self._property_project_name
@project_name.setter
def project_name(self, value: Optional[str]) -> None:
if value is None:
self._property_project_name = None
return
self.assert_isinstance(value, "project_name", six.string_types)
self._property_project_name = value
| MoveRequest |
python | encode__django-rest-framework | tests/test_serializer.py | {
"start": 16711,
"end": 21611
} | class ____:
def setup_method(self):
class ExampleSerializer(serializers.Serializer):
has_default = serializers.CharField(default='x')
has_default_callable = serializers.CharField(default=lambda: 'y')
no_default = serializers.CharField()
self.Serializer = ExampleSerializer
def test_default_used_for_dict(self):
"""
'default="something"' should be used if dictionary key is missing from input.
"""
serializer = self.Serializer({'no_default': 'abc'})
assert serializer.data == {'has_default': 'x', 'has_default_callable': 'y', 'no_default': 'abc'}
def test_default_used_for_object(self):
"""
'default="something"' should be used if object attribute is missing from input.
"""
instance = MockObject(no_default='abc')
serializer = self.Serializer(instance)
assert serializer.data == {'has_default': 'x', 'has_default_callable': 'y', 'no_default': 'abc'}
def test_default_not_used_when_in_dict(self):
"""
'default="something"' should not be used if dictionary key is present in input.
"""
serializer = self.Serializer({'has_default': 'def', 'has_default_callable': 'ghi', 'no_default': 'abc'})
assert serializer.data == {'has_default': 'def', 'has_default_callable': 'ghi', 'no_default': 'abc'}
def test_default_not_used_when_in_object(self):
"""
'default="something"' should not be used if object attribute is present in input.
"""
instance = MockObject(has_default='def', has_default_callable='ghi', no_default='abc')
serializer = self.Serializer(instance)
assert serializer.data == {'has_default': 'def', 'has_default_callable': 'ghi', 'no_default': 'abc'}
def test_default_for_dotted_source(self):
"""
'default="something"' should be used when a traversed attribute is missing from input.
"""
class Serializer(serializers.Serializer):
traversed = serializers.CharField(default='x', source='traversed.attr')
assert Serializer({}).data == {'traversed': 'x'}
assert Serializer({'traversed': {}}).data == {'traversed': 'x'}
assert Serializer({'traversed': None}).data == {'traversed': 'x'}
assert Serializer({'traversed': {'attr': 'abc'}}).data == {'traversed': 'abc'}
def test_default_for_multiple_dotted_source(self):
class Serializer(serializers.Serializer):
c = serializers.CharField(default='x', source='a.b.c')
assert Serializer({}).data == {'c': 'x'}
assert Serializer({'a': {}}).data == {'c': 'x'}
assert Serializer({'a': None}).data == {'c': 'x'}
assert Serializer({'a': {'b': {}}}).data == {'c': 'x'}
assert Serializer({'a': {'b': None}}).data == {'c': 'x'}
assert Serializer({'a': {'b': {'c': 'abc'}}}).data == {'c': 'abc'}
# Same test using model objects to exercise both paths in
# rest_framework.fields.get_attribute() (#5880)
class ModelSerializer(serializers.Serializer):
target = serializers.CharField(default='x', source='target.target.name')
a = NestedForeignKeySource(name="Root Object", target=None)
assert ModelSerializer(a).data == {'target': 'x'}
b = NullableForeignKeySource(name="Intermediary Object", target=None)
a.target = b
assert ModelSerializer(a).data == {'target': 'x'}
c = ForeignKeyTarget(name="Target Object")
b.target = c
assert ModelSerializer(a).data == {'target': 'Target Object'}
def test_default_for_nested_serializer(self):
class NestedSerializer(serializers.Serializer):
a = serializers.CharField(default='1')
c = serializers.CharField(default='2', source='b.c')
class Serializer(serializers.Serializer):
nested = NestedSerializer()
assert Serializer({'nested': None}).data == {'nested': None}
assert Serializer({'nested': {}}).data == {'nested': {'a': '1', 'c': '2'}}
assert Serializer({'nested': {'a': '3', 'b': {}}}).data == {'nested': {'a': '3', 'c': '2'}}
assert Serializer({'nested': {'a': '3', 'b': {'c': '4'}}}).data == {'nested': {'a': '3', 'c': '4'}}
def test_default_for_allow_null(self):
"""
Without an explicit default, allow_null implies default=None when serializing. #5518 #5708
"""
class Serializer(serializers.Serializer):
foo = serializers.CharField()
bar = serializers.CharField(source='foo.bar', allow_null=True)
optional = serializers.CharField(required=False, allow_null=True)
# allow_null=True should imply default=None when serializing:
assert Serializer({'foo': None}).data == {'foo': None, 'bar': None, 'optional': None, }
| TestDefaultOutput |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 27884,
"end": 40515
} | class ____(Generic[_T_co], ColumnOperators, TypingOnly):
__slots__ = ()
# annotations for comparison methods
# these are from operators->Operators / ColumnOperators,
# redefined with the specific types returned by ColumnElement hierarchies
if typing.TYPE_CHECKING:
@util.non_memoized_property
def _propagate_attrs(self) -> _PropagateAttrsType: ...
def operate(
self, op: OperatorType, *other: Any, **kwargs: Any
) -> ColumnElement[Any]: ...
def reverse_operate(
self, op: OperatorType, other: Any, **kwargs: Any
) -> ColumnElement[Any]: ...
@overload
def op(
self,
opstring: str,
precedence: int = ...,
is_comparison: bool = ...,
*,
return_type: _TypeEngineArgument[_OPT],
python_impl: Optional[Callable[..., Any]] = None,
operator_class: OperatorClass = ...,
visit_name: Optional[str] = ...,
) -> Callable[[Any], BinaryExpression[_OPT]]: ...
@overload
def op(
self,
opstring: str,
precedence: int = ...,
is_comparison: bool = ...,
return_type: Optional[_TypeEngineArgument[Any]] = ...,
python_impl: Optional[Callable[..., Any]] = ...,
operator_class: OperatorClass = ...,
visit_name: Optional[str] = ...,
) -> Callable[[Any], BinaryExpression[Any]]: ...
def op(
self,
opstring: str,
precedence: int = 0,
is_comparison: bool = False,
return_type: Optional[_TypeEngineArgument[Any]] = None,
python_impl: Optional[Callable[..., Any]] = None,
operator_class: OperatorClass = OperatorClass.BASE,
visit_name: Optional[str] = None,
) -> Callable[[Any], BinaryExpression[Any]]: ...
def bool_op(
self,
opstring: str,
precedence: int = 0,
python_impl: Optional[Callable[..., Any]] = None,
) -> Callable[[Any], BinaryExpression[bool]]: ...
def __and__(self, other: Any) -> BooleanClauseList: ...
def __or__(self, other: Any) -> BooleanClauseList: ...
def __invert__(self) -> ColumnElement[_T_co]: ...
def __lt__(self, other: Any) -> ColumnElement[bool]: ...
def __le__(self, other: Any) -> ColumnElement[bool]: ...
# declare also that this class has an hash method otherwise
# it may be assumed to be None by type checkers since the
# object defines __eq__ and python sets it to None in that case:
# https://docs.python.org/3/reference/datamodel.html#object.__hash__
def __hash__(self) -> int: ...
def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
...
def __ne__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
...
def is_distinct_from(self, other: Any) -> ColumnElement[bool]: ...
def is_not_distinct_from(self, other: Any) -> ColumnElement[bool]: ...
def __gt__(self, other: Any) -> ColumnElement[bool]: ...
def __ge__(self, other: Any) -> ColumnElement[bool]: ...
def __neg__(self) -> UnaryExpression[_T_co]: ...
def __contains__(self, other: Any) -> ColumnElement[bool]: ...
def __getitem__(self, index: Any) -> ColumnElement[Any]: ...
@overload
def __lshift__(self: _SQO[int], other: Any) -> ColumnElement[int]: ...
@overload
def __lshift__(self, other: Any) -> ColumnElement[Any]: ...
def __lshift__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __rlshift__(self: _SQO[int], other: Any) -> ColumnElement[int]: ...
@overload
def __rlshift__(self, other: Any) -> ColumnElement[Any]: ...
def __rlshift__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __rshift__(self: _SQO[int], other: Any) -> ColumnElement[int]: ...
@overload
def __rshift__(self, other: Any) -> ColumnElement[Any]: ...
def __rshift__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __rrshift__(self: _SQO[int], other: Any) -> ColumnElement[int]: ...
@overload
def __rrshift__(self, other: Any) -> ColumnElement[Any]: ...
def __rrshift__(self, other: Any) -> ColumnElement[Any]: ...
def __matmul__(self, other: Any) -> ColumnElement[Any]: ...
def __rmatmul__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def concat(self: _SQO[str], other: Any) -> ColumnElement[str]: ...
@overload
def concat(self, other: Any) -> ColumnElement[Any]: ...
def concat(self, other: Any) -> ColumnElement[Any]: ...
def like(
self, other: Any, escape: Optional[str] = None
) -> BinaryExpression[bool]: ...
def ilike(
self, other: Any, escape: Optional[str] = None
) -> BinaryExpression[bool]: ...
def bitwise_xor(self, other: Any) -> BinaryExpression[Any]: ...
def bitwise_or(self, other: Any) -> BinaryExpression[Any]: ...
def bitwise_and(self, other: Any) -> BinaryExpression[Any]: ...
def bitwise_not(self) -> UnaryExpression[_T_co]: ...
def bitwise_lshift(self, other: Any) -> BinaryExpression[Any]: ...
def bitwise_rshift(self, other: Any) -> BinaryExpression[Any]: ...
def in_(
self,
other: Union[
Iterable[Any], BindParameter[Any], roles.InElementRole
],
) -> BinaryExpression[bool]: ...
def not_in(
self,
other: Union[
Iterable[Any], BindParameter[Any], roles.InElementRole
],
) -> BinaryExpression[bool]: ...
def notin_(
self,
other: Union[
Iterable[Any], BindParameter[Any], roles.InElementRole
],
) -> BinaryExpression[bool]: ...
def not_like(
self, other: Any, escape: Optional[str] = None
) -> BinaryExpression[bool]: ...
def notlike(
self, other: Any, escape: Optional[str] = None
) -> BinaryExpression[bool]: ...
def not_ilike(
self, other: Any, escape: Optional[str] = None
) -> BinaryExpression[bool]: ...
def notilike(
self, other: Any, escape: Optional[str] = None
) -> BinaryExpression[bool]: ...
def is_(self, other: Any) -> BinaryExpression[bool]: ...
def is_not(self, other: Any) -> BinaryExpression[bool]: ...
def isnot(self, other: Any) -> BinaryExpression[bool]: ...
def startswith(
self,
other: Any,
escape: Optional[str] = None,
autoescape: bool = False,
) -> ColumnElement[bool]: ...
def istartswith(
self,
other: Any,
escape: Optional[str] = None,
autoescape: bool = False,
) -> ColumnElement[bool]: ...
def endswith(
self,
other: Any,
escape: Optional[str] = None,
autoescape: bool = False,
) -> ColumnElement[bool]: ...
def iendswith(
self,
other: Any,
escape: Optional[str] = None,
autoescape: bool = False,
) -> ColumnElement[bool]: ...
def contains(self, other: Any, **kw: Any) -> ColumnElement[bool]: ...
def icontains(self, other: Any, **kw: Any) -> ColumnElement[bool]: ...
def match(self, other: Any, **kwargs: Any) -> ColumnElement[bool]: ...
def regexp_match(
self, pattern: Any, flags: Optional[str] = None
) -> ColumnElement[bool]: ...
def regexp_replace(
self, pattern: Any, replacement: Any, flags: Optional[str] = None
) -> ColumnElement[str]: ...
def desc(self) -> UnaryExpression[_T_co]: ...
def asc(self) -> UnaryExpression[_T_co]: ...
def nulls_first(self) -> UnaryExpression[_T_co]: ...
def nullsfirst(self) -> UnaryExpression[_T_co]: ...
def nulls_last(self) -> UnaryExpression[_T_co]: ...
def nullslast(self) -> UnaryExpression[_T_co]: ...
def collate(self, collation: str) -> CollationClause: ...
def between(
self, cleft: Any, cright: Any, symmetric: bool = False
) -> BinaryExpression[bool]: ...
def distinct(self: _SQO[_T_co]) -> UnaryExpression[_T_co]: ...
def any_(self) -> CollectionAggregate[Any]: ...
def all_(self) -> CollectionAggregate[Any]: ...
# numeric overloads. These need more tweaking
# in particular they all need to have a variant for Optiona[_T]
# because Optional only applies to the data side, not the expression
# side
@overload
def __add__(
self: _SQO[_NMT],
other: Any,
) -> ColumnElement[_NMT]: ...
@overload
def __add__(
self: _SQO[str],
other: Any,
) -> ColumnElement[str]: ...
@overload
def __add__(self, other: Any) -> ColumnElement[Any]: ...
def __add__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __radd__(self: _SQO[_NMT], other: Any) -> ColumnElement[_NMT]: ...
@overload
def __radd__(self: _SQO[str], other: Any) -> ColumnElement[str]: ...
def __radd__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __sub__(
self: _SQO[_NMT],
other: Any,
) -> ColumnElement[_NMT]: ...
@overload
def __sub__(self, other: Any) -> ColumnElement[Any]: ...
def __sub__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __rsub__(
self: _SQO[_NMT],
other: Any,
) -> ColumnElement[_NMT]: ...
@overload
def __rsub__(self, other: Any) -> ColumnElement[Any]: ...
def __rsub__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __mul__(
self: _SQO[_NMT],
other: Any,
) -> ColumnElement[_NMT]: ...
@overload
def __mul__(self, other: Any) -> ColumnElement[Any]: ...
def __mul__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __rmul__(
self: _SQO[_NMT],
other: Any,
) -> ColumnElement[_NMT]: ...
@overload
def __rmul__(self, other: Any) -> ColumnElement[Any]: ...
def __rmul__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __mod__(self: _SQO[_NMT], other: Any) -> ColumnElement[_NMT]: ...
@overload
def __mod__(self, other: Any) -> ColumnElement[Any]: ...
def __mod__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __rmod__(self: _SQO[_NMT], other: Any) -> ColumnElement[_NMT]: ...
@overload
def __rmod__(self, other: Any) -> ColumnElement[Any]: ...
def __rmod__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __truediv__(
self: _SQO[int], other: Any
) -> ColumnElement[_NUMERIC]: ...
@overload
def __truediv__(self: _SQO[_NT], other: Any) -> ColumnElement[_NT]: ...
@overload
def __truediv__(self, other: Any) -> ColumnElement[Any]: ...
def __truediv__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __rtruediv__(
self: _SQO[_NMT], other: Any
) -> ColumnElement[_NUMERIC]: ...
@overload
def __rtruediv__(self, other: Any) -> ColumnElement[Any]: ...
def __rtruediv__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __floordiv__(
self: _SQO[_NMT], other: Any
) -> ColumnElement[_NMT]: ...
@overload
def __floordiv__(self, other: Any) -> ColumnElement[Any]: ...
def __floordiv__(self, other: Any) -> ColumnElement[Any]: ...
@overload
def __rfloordiv__(
self: _SQO[_NMT], other: Any
) -> ColumnElement[_NMT]: ...
@overload
def __rfloordiv__(self, other: Any) -> ColumnElement[Any]: ...
def __rfloordiv__(self, other: Any) -> ColumnElement[Any]: ...
| SQLCoreOperations |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_comment14.py | {
"start": 315,
"end": 954
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("comment14.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with comments."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.write("A1", "Foo")
worksheet.write_comment("B2", "Some text")
worksheet.set_column("C:C", 13)
worksheet.set_comments_author("John")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | pypa__pip | src/pip/_vendor/cachecontrol/heuristics.py | {
"start": 1850,
"end": 2478
} | class ____(BaseHeuristic):
"""
Cache the response by providing an expires 1 day in the
future.
"""
def update_headers(self, response: HTTPResponse) -> dict[str, str]:
headers = {}
if "expires" not in response.headers:
date = parsedate(response.headers["date"])
expires = expire_after(
timedelta(days=1),
date=datetime(*date[:6], tzinfo=timezone.utc), # type: ignore[index,misc]
)
headers["expires"] = datetime_to_header(expires)
headers["cache-control"] = "public"
return headers
| OneDayCache |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/cache_test.py | {
"start": 26437,
"end": 27621
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
dataset_range=[10],
repetitions=[1, 2],
seed=[None, 42],
reshuffle_each_iteration=[True, False])))
def test(
self,
dataset_range: int,
repetitions: int,
seed: Optional[int],
reshuffle_each_iteration: bool):
dataset = dataset_ops.Dataset.range(dataset_range)
dataset = dataset.cache()
dataset = dataset.prefetch(buffer_size=dataset_ops.AUTOTUNE)
if repetitions > 1:
dataset = dataset.repeat(repetitions)
dataset = global_shuffle_op._global_shuffle(
dataset, seed=seed, reshuffle_each_iteration=reshuffle_each_iteration)
expected = list(range(0, dataset_range)) * repetitions
dataset_output = self.getDatasetOutput(
dataset, requires_initialization=True)
self.assertCountEqual(dataset_output, expected)
self.assertNotEqual(dataset_output, expected)
self.assertLen(dataset_output, self.evaluate(dataset.cardinality()))
| CacheGlobalShuffleTest |
python | huggingface__transformers | src/transformers/models/falcon_h1/modeling_falcon_h1.py | {
"start": 3052,
"end": 10000
} | class ____:
"""
A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
(which has a constant shape regardless of seq_len).
This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
"""
is_compileable = False
def __init__(
self,
config: FalconH1Config,
batch_size: int,
dtype: torch.dtype = torch.float16,
devices: Optional[list[str]] = None,
):
self.seqlen_offset = 0
self.dtype = dtype
self.has_previous_state = False
self.conv_kernel_size = config.mamba_d_conv
self.intermediate_size = (
config.mamba_d_ssm if config.mamba_d_ssm is not None else int(config.mamba_expand * config.hidden_size)
)
self.conv_states = {
i: torch.zeros(
batch_size,
self.intermediate_size + 2 * config.mamba_n_groups * config.mamba_d_state,
self.conv_kernel_size,
device=devices[i],
dtype=dtype,
)
for i in range(config.num_hidden_layers)
}
self.ssm_states = {
i: torch.zeros(
batch_size,
config.mamba_n_heads,
config.mamba_d_head,
config.mamba_d_state,
device=devices[i],
dtype=dtype,
)
for i in range(config.num_hidden_layers)
}
self.transformer_layers = []
for i in range(config.num_hidden_layers):
self.transformer_layers.append(i)
self.key_cache: list[torch.Tensor] = []
self.value_cache: list[torch.Tensor] = []
def __len__(self):
return len(self.key_cache)
def __getitem__(self, layer_idx):
return self.key_cache[layer_idx], self.value_cache[layer_idx]
def update(
self,
key_states: torch.Tensor,
value_states: torch.Tensor,
layer_idx: int,
cache_kwargs: Optional[dict[str, Any]] = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
Parameters:
key_states (`torch.Tensor`):
The new key states to cache.
value_states (`torch.Tensor`):
The new value states to cache.
layer_idx (`int`):
The index of the layer to cache the states for.
cache_kwargs (`dict[str, Any]`, `optional`):
Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`.
Return:
A tuple containing the updated key and value states.
"""
# Update the cache
if len(self.key_cache) <= layer_idx:
# There may be skipped layers, fill them with empty lists
for _ in range(len(self.key_cache), layer_idx):
self.key_cache.append([])
self.value_cache.append([])
self.key_cache.append(key_states)
self.value_cache.append(value_states)
elif len(self.key_cache[layer_idx]) == 0: # fills previously skipped layers; checking for tensor causes errors
self.key_cache[layer_idx] = key_states
self.value_cache[layer_idx] = value_states
else:
self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2)
self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2)
return self.key_cache[layer_idx], self.value_cache[layer_idx]
def reorder_cache(self, beam_idx: torch.LongTensor):
"""Reorders the cache for beam search, given the selected beam indices."""
if self.get_seq_length() > 0:
for layer_idx in range(len(self.key_cache)):
device = self.key_cache[layer_idx].device
self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
device = self.value_cache[layer_idx].device
self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
device = self.conv_states[layer_idx].device
self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
device = self.ssm_states[layer_idx].device
self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]:
"""Return the length and offset of the cache, used to generate the mask"""
kv_offset = 0
query_length = cache_position.shape[0]
kv_length = self.get_seq_length(layer_idx) + query_length
return kv_length, kv_offset
def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
"""Returns the sequence length of the cached states. A layer index can be optionally passed."""
# take any layer that contains cache and not empty tensor
layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
if len(self.key_cache) <= layer_idx or self.key_cache[layer_idx].shape[-1] == 0:
return 0
return self.key_cache[layer_idx].shape[-2]
def update_conv_state(
self,
layer_idx: int,
new_conv_state: torch.Tensor,
cache_position: torch.LongTensor,
) -> torch.Tensor:
conv_state = self.conv_states[layer_idx]
cache_position = cache_position.clamp(0, self.conv_kernel_size - 1)
conv_state = conv_state.roll(shifts=-1, dims=-1)
if len(cache_position) > 1:
conv_state[:, :, :] = new_conv_state.to(conv_state.device)
else:
conv_state[:, :, -1] = new_conv_state[:, :, -1].to(conv_state.device)
self.conv_states[layer_idx].zero_()
self.conv_states[layer_idx] += conv_state
return self.conv_states[layer_idx]
def reset(self):
self.conv_states.zero_()
self.ssm_states.zero_()
| FalconHybridMambaAttentionDynamicCache |
python | openai__openai-python | src/openai/resources/batches.py | {
"start": 9845,
"end": 18928
} | class ____(AsyncAPIResource):
@cached_property
def with_raw_response(self) -> AsyncBatchesWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
"""
return AsyncBatchesWithRawResponse(self)
@cached_property
def with_streaming_response(self) -> AsyncBatchesWithStreamingResponse:
"""
An alternative to `.with_raw_response` that doesn't eagerly read the response body.
For more information, see https://www.github.com/openai/openai-python#with_streaming_response
"""
return AsyncBatchesWithStreamingResponse(self)
async def create(
self,
*,
completion_window: Literal["24h"],
endpoint: Literal[
"/v1/responses", "/v1/chat/completions", "/v1/embeddings", "/v1/completions", "/v1/moderations"
],
input_file_id: str,
metadata: Optional[Metadata] | Omit = omit,
output_expires_after: batch_create_params.OutputExpiresAfter | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Batch:
"""
Creates and executes a batch from an uploaded file of requests
Args:
completion_window: The time frame within which the batch should be processed. Currently only `24h`
is supported.
endpoint: The endpoint to be used for all requests in the batch. Currently
`/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, `/v1/completions`,
and `/v1/moderations` are supported. Note that `/v1/embeddings` batches are also
restricted to a maximum of 50,000 embedding inputs across all requests in the
batch.
input_file_id: The ID of an uploaded file that contains requests for the new batch.
See [upload file](https://platform.openai.com/docs/api-reference/files/create)
for how to upload a file.
Your input file must be formatted as a
[JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input),
and must be uploaded with the purpose `batch`. The file can contain up to 50,000
requests, and can be up to 200 MB in size.
metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful
for storing additional information about the object in a structured format, and
querying for objects via API or the dashboard.
Keys are strings with a maximum length of 64 characters. Values are strings with
a maximum length of 512 characters.
output_expires_after: The expiration policy for the output and/or error file that are generated for a
batch.
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
return await self._post(
"/batches",
body=await async_maybe_transform(
{
"completion_window": completion_window,
"endpoint": endpoint,
"input_file_id": input_file_id,
"metadata": metadata,
"output_expires_after": output_expires_after,
},
batch_create_params.BatchCreateParams,
),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=Batch,
)
async def retrieve(
self,
batch_id: str,
*,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Batch:
"""
Retrieves a batch.
Args:
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not batch_id:
raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
return await self._get(
f"/batches/{batch_id}",
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=Batch,
)
def list(
self,
*,
after: str | Omit = omit,
limit: int | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncPaginator[Batch, AsyncCursorPage[Batch]]:
"""List your organization's batches.
Args:
after: A cursor for use in pagination.
`after` is an object ID that defines your place
in the list. For instance, if you make a list request and receive 100 objects,
ending with obj_foo, your subsequent call can include after=obj_foo in order to
fetch the next page of the list.
limit: A limit on the number of objects to be returned. Limit can range between 1 and
100, and the default is 20.
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
return self._get_api_list(
"/batches",
page=AsyncCursorPage[Batch],
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
query=maybe_transform(
{
"after": after,
"limit": limit,
},
batch_list_params.BatchListParams,
),
),
model=Batch,
)
async def cancel(
self,
batch_id: str,
*,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Batch:
"""Cancels an in-progress batch.
The batch will be in status `cancelling` for up to
10 minutes, before changing to `cancelled`, where it will have partial results
(if any) available in the output file.
Args:
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not batch_id:
raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
return await self._post(
f"/batches/{batch_id}/cancel",
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=Batch,
)
| AsyncBatches |
python | pandas-dev__pandas | pandas/core/indexes/accessors.py | {
"start": 18047,
"end": 20344
} | class ____(
DatetimeProperties, TimedeltaProperties, PeriodProperties
):
"""
Accessor object for Series values' datetime-like, timedelta and period properties.
See Also
--------
DatetimeIndex : Index of datetime64 data.
Examples
--------
>>> dates = pd.Series(
... ["2024-01-01", "2024-01-15", "2024-02-5"], dtype="datetime64[ns]"
... )
>>> dates.dt.day
0 1
1 15
2 5
dtype: int32
>>> dates.dt.month
0 1
1 1
2 2
dtype: int32
>>> dates = pd.Series(
... ["2024-01-01", "2024-01-15", "2024-02-5"], dtype="datetime64[ns, UTC]"
... )
>>> dates.dt.day
0 1
1 15
2 5
dtype: int32
>>> dates.dt.month
0 1
1 1
2 2
dtype: int32
"""
def __new__(cls, data: Series): # pyright: ignore[reportInconsistentConstructor]
# CombinedDatetimelikeProperties isn't really instantiated. Instead
# we need to choose which parent (datetime or timedelta) is
# appropriate. Since we're checking the dtypes anyway, we'll just
# do all the validation here.
if not isinstance(data, ABCSeries):
raise TypeError(
f"cannot convert an object of type {type(data)} to a datetimelike index"
)
orig = data if isinstance(data.dtype, CategoricalDtype) else None
if orig is not None:
data = data._constructor(
orig.array,
name=orig.name,
copy=False,
dtype=orig._values.categories.dtype,
index=orig.index,
)
if isinstance(data.dtype, ArrowDtype) and data.dtype.kind in "Mm":
return ArrowTemporalProperties(data, orig)
if lib.is_np_dtype(data.dtype, "M"):
return DatetimeProperties(data, orig)
elif isinstance(data.dtype, DatetimeTZDtype):
return DatetimeProperties(data, orig)
elif lib.is_np_dtype(data.dtype, "m"):
return TimedeltaProperties(data, orig)
elif isinstance(data.dtype, PeriodDtype):
return PeriodProperties(data, orig)
raise AttributeError("Can only use .dt accessor with datetimelike values")
| CombinedDatetimelikeProperties |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/text_edit.py | {
"start": 1824,
"end": 2768
} | class ____(Exception):
"""
Text edits are expected to be sorted
and compressed instead of overlapping.
This error is raised when two edits
are overlapping.
"""
def apply_text_edits(doc, text_edits):
text = doc.source
sorted_edits = merge_sort_text_edits(list(map(get_well_formatted_edit, text_edits)))
last_modified_offset = 0
spans = []
for e in sorted_edits:
start_offset = doc.offset_at_position(e["range"]["start"])
if start_offset < last_modified_offset:
raise OverLappingTextEditException("overlapping edit")
if start_offset > last_modified_offset:
spans.append(text[last_modified_offset:start_offset])
if len(e["newText"]):
spans.append(e["newText"])
last_modified_offset = doc.offset_at_position(e["range"]["end"])
spans.append(text[last_modified_offset:])
return "".join(spans)
| OverLappingTextEditException |
python | weaviate__weaviate-python-client | weaviate/collections/tenants/executor.py | {
"start": 877,
"end": 23308
} | class ____(Generic[ConnectionType]):
def __init__(
self,
connection: ConnectionType,
name: str,
validate_arguments: bool = True,
) -> None:
self._connection = connection
self._name = name
self._grpc = _TenantsGRPC(
weaviate_version=connection._weaviate_version,
name=name,
)
self._validate_arguments = validate_arguments
def create(
self,
tenants: Union[TenantCreateInputType, Sequence[TenantCreateInputType]],
) -> executor.Result[None]:
"""Create the specified tenants for this collection in Weaviate.
The collection must have been created with multi-tenancy enabled.
Args:
tenants: A tenant name, `wvc.config.tenants.Tenant`, `wvc.config.tenants.TenantCreateInput` object, or a list of tenants names
and/or `wvc.config.tenants.Tenant` objects to add to the given collection.
If a string is provided, the tenant will be added with the default activity status of `HOT`.
Raises:
weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails.
weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status.
weaviate.exceptions.WeaviateInvalidInputError: If `tenants` is not a list of `wvc.Tenant` objects.
"""
if self._validate_arguments:
_validate_input(
[
_ValidateArgument(
expected=[
str,
Tenant,
TenantCreate,
Sequence[Union[str, Tenant, TenantCreate]],
],
name="tenants",
value=tenants,
)
]
)
path = "/schema/" + self._name + "/tenants"
def resp(res: Response) -> None:
return None
return executor.execute(
response_callback=resp,
method=self._connection.post,
path=path,
weaviate_object=self.__map_create_tenants(tenants),
error_msg=f"Collection tenants may not have been added properly for {self._name}",
status_codes=_ExpectedStatusCodes(
ok_in=200, error=f"Add collection tenants for {self._name}"
),
)
def remove(
self,
tenants: Union[TenantInputType, Sequence[TenantInputType]],
) -> executor.Result[None]:
"""Remove the specified tenants from this collection in Weaviate.
The collection must have been created with multi-tenancy enabled.
Args:
tenants: A tenant name, `wvc.config.tenants.Tenant` object, or a list of tenants names
and/or `wvc.config.tenants.Tenant` objects to remove from the given class.
Raises:
weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails.
weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status.
weaviate.exceptions.WeaviateInvalidInputError: If `tenants` is not a list of strings.
"""
if self._validate_arguments:
_validate_input(
[
_ValidateArgument(
expected=[
str,
Tenant,
Sequence[Union[str, Tenant]],
],
name="tenants",
value=tenants,
)
]
)
tenant_names: List[str] = []
if isinstance(tenants, str) or isinstance(tenants, Tenant):
tenant_names = [tenants.name if isinstance(tenants, Tenant) else tenants]
else:
for tenant in tenants:
tenant_names.append(tenant.name if isinstance(tenant, Tenant) else tenant)
path = "/schema/" + self._name + "/tenants"
def resp(res: Response) -> None:
return None
return executor.execute(
response_callback=resp,
method=self._connection.delete,
path=path,
weaviate_object=tenant_names,
error_msg=f"Collection tenants may not have been deleted for {self._name}",
status_codes=_ExpectedStatusCodes(
ok_in=200, error=f"Delete collection tenants for {self._name}"
),
)
def __get_with_rest(
self,
) -> executor.Result[Dict[str, TenantOutputType]]:
path = "/schema/" + self._name + "/tenants"
def resp(res: Response) -> Dict[str, TenantOutputType]:
tenant_resp: List[Dict[str, Any]] = res.json()
for tenant in tenant_resp:
tenant["activityStatusInternal"] = tenant["activityStatus"]
del tenant["activityStatus"]
return {tenant["name"]: TenantOutput(**tenant) for tenant in tenant_resp}
return executor.execute(
response_callback=resp,
method=self._connection.get,
path=path,
error_msg=f"Could not get collection tenants for {self._name}",
status_codes=_ExpectedStatusCodes(
ok_in=200, error=f"Get collection tenants for {self._name}"
),
)
def __get_with_grpc(
self, *, tenants: Optional[Sequence[TenantInputType]] = None
) -> executor.Result[Dict[str, TenantOutputType]]:
names = (
[tenant.name if isinstance(tenant, Tenant) else tenant for tenant in tenants]
if tenants is not None
else tenants
)
request = tenants_pb2.TenantsGetRequest(
collection=self._name,
names=tenants_pb2.TenantNames(values=names) if names is not None else None,
)
def resp(res: tenants_pb2.TenantsGetReply) -> Dict[str, TenantOutputType]:
return {
tenant.name: TenantOutput(
name=tenant.name,
activity_status=self._grpc.map_activity_status(tenant.activity_status),
)
for tenant in res.tenants
}
return executor.execute(
response_callback=resp,
method=self._connection.grpc_tenants_get,
request=request,
)
def __map_create_tenant(self, tenant: TenantCreateInputType) -> TenantCreate:
if isinstance(tenant, str):
return TenantCreate(name=tenant)
if isinstance(tenant, Tenant):
if tenant.activity_status not in [
TenantActivityStatus.ACTIVE,
TenantActivityStatus.INACTIVE,
]:
raise WeaviateInvalidInputError(
f"Tenant activity status must be either 'ACTIVE' or 'INACTIVE'. Other statuses are read-only and cannot be set. Tenant: {tenant.name} had status: {tenant.activity_status}"
)
activity_status = TenantCreateActivityStatus(tenant.activity_status)
return TenantCreate(name=tenant.name, activity_status=activity_status)
return tenant
def __map_update_tenant(self, tenant: TenantUpdateInputType) -> TenantUpdate:
if isinstance(tenant, Tenant):
if tenant.activity_status not in [
TenantActivityStatus.ACTIVE,
TenantActivityStatus.INACTIVE,
TenantActivityStatus.OFFLOADED,
]:
raise WeaviateInvalidInputError(
f"Tenant activity status must be one of 'ACTIVE', 'INACTIVE' or 'OFFLOADED'. Other statuses are read-only and cannot be set. Tenant: {tenant.name} had status: {tenant.activity_status}"
)
activity_status = TenantUpdateActivityStatus(tenant.activity_status)
return TenantUpdate(name=tenant.name, activity_status=activity_status)
return tenant
def __map_create_tenants(
self,
tenants: Union[TenantCreateInputType, Sequence[TenantCreateInputType]],
) -> List[dict]:
if (
isinstance(tenants, str)
or isinstance(tenants, Tenant)
or isinstance(tenants, TenantCreate)
):
return [self.__map_create_tenant(tenants).model_dump()]
else:
return [self.__map_create_tenant(tenant).model_dump() for tenant in tenants]
def __map_update_tenants(
self, tenants: Union[TenantUpdateInputType, Sequence[TenantUpdateInputType]]
) -> List[List[dict]]:
if isinstance(tenants, Tenant) or isinstance(tenants, TenantUpdate):
return [[self.__map_update_tenant(tenants).model_dump()]]
else:
batches = ceil(len(tenants) / UPDATE_TENANT_BATCH_SIZE)
return [
[
self.__map_update_tenant(tenants[i + b * UPDATE_TENANT_BATCH_SIZE]).model_dump()
for i in range(
min(
len(tenants) - b * UPDATE_TENANT_BATCH_SIZE,
UPDATE_TENANT_BATCH_SIZE,
)
)
]
for b in range(batches)
]
def get(self) -> executor.Result[Dict[str, TenantOutputType]]:
"""Return all tenants currently associated with this collection in Weaviate.
The collection must have been created with multi-tenancy enabled.
Raises:
weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails.
weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status.
"""
def resp(res: Dict[str, TenantOutputType]) -> Dict[str, TenantOutputType]:
return res
return executor.execute(
response_callback=resp,
method=(
self.__get_with_grpc
if self._connection._weaviate_version.supports_tenants_get_grpc
else self.__get_with_rest
),
)
def get_by_names(
self, tenants: Sequence[TenantInputType]
) -> executor.Result[Dict[str, TenantOutputType]]:
"""Return named tenants currently associated with this collection in Weaviate.
If the tenant does not exist, it will not be included in the response.
If no names are provided, all tenants will be returned.
The collection must have been created with multi-tenancy enabled.
Args:
tenants: Sequence of tenant names of wvc.tenants.Tenant objects to retrieve. To retrieve all tenants, use the `get` method.
Raises:
weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails.
weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status.
"""
self._connection._weaviate_version.check_is_at_least_1_25_0("The 'get_by_names' method")
if self._validate_arguments:
_validate_input(
_ValidateArgument(
expected=[Sequence[Union[str, Tenant]]],
name="names",
value=tenants,
)
)
return self.__get_with_grpc(tenants=tenants)
def get_by_name(self, tenant: TenantInputType) -> executor.Result[Optional[TenantOutputType]]:
"""Return a specific tenant associated with this collection in Weaviate.
If the tenant does not exist, `None` will be returned.
The collection must have been created with multi-tenancy enabled.
Args:
tenant: The tenant to retrieve.
Raises:
weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails.
weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status.
"""
self._connection._weaviate_version.check_is_at_least_1_25_0("The 'get_by_name' method")
if self._validate_arguments:
_validate_input(
_ValidateArgument(expected=[Union[str, Tenant]], name="tenant", value=tenant)
)
tenant_name = tenant.name if isinstance(tenant, Tenant) else tenant
if self._connection._weaviate_version.is_lower_than(1, 28, 0):
# For Weaviate versions < 1.28.0, we need to use the gRPC API
# such versions don't have RBAC so the filtering issue doesn't exist therein
def resp_grpc(res: Dict[str, TenantOutputType]) -> Optional[TenantOutputType]:
return res.get(tenant_name)
return executor.execute(
response_callback=resp_grpc,
method=self.__get_with_grpc,
tenants=[tenant_name],
)
# For Weaviate versions >= 1.28.0, we need to use the REST API
# as the gRPC API filters out tenants that are not accessible to the user
# due to RBAC requirements
def resp_rest(res: Response) -> Optional[TenantOutputType]:
if res.status_code == 404:
return None
data = res.json()
return TenantOutput(
name=data["name"],
activity_status=TenantActivityStatus(data["activityStatus"]),
)
return executor.execute(
response_callback=resp_rest,
method=self._connection.get,
path=f"/schema/{self._name}/tenants/{tenant_name}",
error_msg=f"Could not get tenant {tenant_name} for collection {self._name}",
status_codes=_ExpectedStatusCodes(
ok_in=[200, 404],
error=f"Get tenant {tenant_name} for collection {self._name}",
),
)
def __update(
self,
tenants: Union[TenantUpdateInputType, Sequence[TenantUpdateInputType]],
) -> executor.Result[None]:
path = "/schema/" + self._name + "/tenants"
if isinstance(self._connection, ConnectionAsync):
async def _execute() -> None:
await asyncio.gather(
*[
executor.aresult(
self._connection.put(
path=path,
weaviate_object=mapped_tenants,
error_msg=f"Collection tenants may not have been updated properly for {self._name}",
status_codes=_ExpectedStatusCodes(
ok_in=200,
error=f"Update collection tenants for {self._name}",
),
)
)
for mapped_tenants in self.__map_update_tenants(tenants)
]
)
return _execute()
for mapped_tenants in self.__map_update_tenants(tenants):
self._connection.put(
path=path,
weaviate_object=mapped_tenants,
error_msg=f"Collection tenants may not have been updated properly for {self._name}",
status_codes=_ExpectedStatusCodes(
ok_in=200, error=f"Update collection tenants for {self._name}"
),
)
def update(
self,
tenants: Union[TenantUpdateInputType, Sequence[TenantUpdateInputType]],
) -> executor.Result[None]:
"""Update the specified tenants for this collection in Weaviate.
The collection must have been created with multi-tenancy enabled.
Args:
tenants: A tenant name, `wvc.config.tenants.Tenant` object, or a list of tenants names
and/or `wvc.config.tenants.Tenant` objects to update for the given collection.
Raises:
weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails.
weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status.
weaviate.exceptions.WeaviateInvalidInputError: If `tenants` is not a list of `wvc.Tenant` objects.
"""
if self._validate_arguments:
_validate_input(
_ValidateArgument(
expected=[
Tenant,
TenantUpdate,
Sequence[Union[Tenant, TenantUpdate]],
],
name="tenants",
value=tenants,
)
)
return self.__update(tenants=tenants)
def exists(self, tenant: TenantInputType) -> executor.Result[bool]:
"""Check if a tenant exists for this collection in Weaviate.
The collection must have been created with multi-tenancy enabled.
Args:
tenant: Tenant name or `wvc.config.tenants.Tenant` object to check for existence.
Returns:
`True` if the tenant exists, `False` otherwise.
Raises:
weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails.
weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status.
"""
self._connection._weaviate_version.check_is_at_least_1_25_0("The 'exists' method")
if self._validate_arguments:
_validate_input(
_ValidateArgument(
expected=[str, Tenant],
name="tenant",
value=tenant,
)
)
def resp(res: Response) -> bool:
return res.status_code == 200
tenant_name = tenant.name if isinstance(tenant, Tenant) else tenant
path = "/schema/" + self._name + "/tenants/" + tenant_name
return executor.execute(
response_callback=resp,
method=self._connection.head,
path=path,
error_msg=f"Could not check if tenant exists for {self._name}",
status_codes=_ExpectedStatusCodes(
ok_in=[200, 404], error=f"Check if tenant exists for {self._name}"
), # allow 404 to perform bool check on response code
)
def __update_tenant_activity_status(
self,
tenant: Union[TenantInputType, Sequence[TenantInputType]],
activity_status: TenantUpdateActivityStatus,
) -> executor.Result[None]:
if self._validate_arguments:
_validate_input(
_ValidateArgument(
expected=[
str,
Tenant,
Sequence[Union[str, Tenant]],
],
name="tenant",
value=tenant,
)
)
if isinstance(tenant, str) or isinstance(tenant, Tenant):
tenants = [
TenantUpdate(
name=tenant.name if isinstance(tenant, Tenant) else tenant,
activity_status=activity_status,
)
]
else:
tenants = [
TenantUpdate(
name=t.name if isinstance(t, Tenant) else t,
activity_status=activity_status,
)
for t in tenant
]
return self.__update(tenants=tenants)
def activate(
self, tenant: Union[TenantInputType, Sequence[TenantInputType]]
) -> executor.Result[None]:
"""Activate the specified tenants for this collection in Weaviate.
The collection must have been created with multi-tenancy enabled.
Args:
tenant: A tenant name, `wvc.config.tenants.Tenant` object, or a list of tenants names
and/or `wvc.config.tenants.Tenant` objects to activate for the given collection.
Raises:
weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails.
weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status.
weaviate.exceptions.WeaviateInvalidInputError: If `tenant` is not a list of `wvc.Tenant` objects.
"""
self.__update_tenant_activity_status(
tenant=tenant,
activity_status=TenantUpdateActivityStatus.ACTIVE,
)
def deactivate(
self, tenant: Union[TenantInputType, Sequence[TenantInputType]]
) -> executor.Result[None]:
"""Deactivate the specified tenants for this collection in Weaviate.
The collection must have been created with multi-tenancy enabled.
Args:
tenant: A tenant name, `wvc.config.tenants.Tenant` object, or a list of tenants names
and/or `wvc.config.tenants.Tenant` objects to deactivate for the given collection.
Raises:
weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails.
weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status.
weaviate.exceptions.WeaviateInvalidInputError: If `tenant` is not a list of `wvc.Tenant` objects.
"""
self.__update_tenant_activity_status(
tenant=tenant,
activity_status=TenantUpdateActivityStatus.INACTIVE,
)
def offload(
self, tenant: Union[TenantInputType, Sequence[TenantInputType]]
) -> executor.Result[None]:
"""Offload the specified tenants for this collection in Weaviate.
The collection must have been created with multi-tenancy enabled.
Args:
tenant: A tenant name, `wvc.config.tenants.Tenant` object, or a list of tenants names
and/or `wvc.config.tenants.Tenant` objects to offload for the given collection.
Raises:
weaviate.exceptions.WeaviateConnectionError: If the network connection to Weaviate fails.
weaviate.exceptions.UnexpectedStatusCodeError: If Weaviate reports a non-OK status.
weaviate.exceptions.WeaviateInvalidInputError: If `tenant` is not a list of `wvc.Tenant` objects.
"""
self.__update_tenant_activity_status(
tenant=tenant,
activity_status=TenantUpdateActivityStatus.OFFLOADED,
)
| _TenantsExecutor |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/graph.py | {
"start": 6518,
"end": 23094
} | class ____:
"""Graph of nodes and edges.
Args:
nodes: Dictionary of nodes in the graph. Defaults to an empty dictionary.
edges: List of edges in the graph. Defaults to an empty list.
"""
nodes: dict[str, Node] = field(default_factory=dict)
edges: list[Edge] = field(default_factory=list)
def to_json(self, *, with_schemas: bool = False) -> dict[str, list[dict[str, Any]]]:
"""Convert the graph to a JSON-serializable format.
Args:
with_schemas: Whether to include the schemas of the nodes if they are
Pydantic models.
Returns:
A dictionary with the nodes and edges of the graph.
"""
stable_node_ids = {
node.id: i if is_uuid(node.id) else node.id
for i, node in enumerate(self.nodes.values())
}
edges: list[dict[str, Any]] = []
for edge in self.edges:
edge_dict = {
"source": stable_node_ids[edge.source],
"target": stable_node_ids[edge.target],
}
if edge.data is not None:
edge_dict["data"] = edge.data # type: ignore[assignment]
if edge.conditional:
edge_dict["conditional"] = True
edges.append(edge_dict)
return {
"nodes": [
{
"id": stable_node_ids[node.id],
**node_data_json(node, with_schemas=with_schemas),
}
for node in self.nodes.values()
],
"edges": edges,
}
def __bool__(self) -> bool:
"""Return whether the graph has any nodes."""
return bool(self.nodes)
def next_id(self) -> str:
"""Return a new unique node identifier.
It that can be used to add a node to the graph.
"""
return uuid4().hex
def add_node(
self,
data: type[BaseModel] | RunnableType | None,
id: str | None = None,
*,
metadata: dict[str, Any] | None = None,
) -> Node:
"""Add a node to the graph and return it.
Args:
data: The data of the node.
id: The id of the node.
metadata: Optional metadata for the node.
Returns:
The node that was added to the graph.
Raises:
ValueError: If a node with the same id already exists.
"""
if id is not None and id in self.nodes:
msg = f"Node with id {id} already exists"
raise ValueError(msg)
id_ = id or self.next_id()
node = Node(id=id_, data=data, metadata=metadata, name=node_data_str(id_, data))
self.nodes[node.id] = node
return node
def remove_node(self, node: Node) -> None:
"""Remove a node from the graph and all edges connected to it.
Args:
node: The node to remove.
"""
self.nodes.pop(node.id)
self.edges = [
edge for edge in self.edges if node.id not in {edge.source, edge.target}
]
def add_edge(
self,
source: Node,
target: Node,
data: Stringifiable | None = None,
conditional: bool = False, # noqa: FBT001,FBT002
) -> Edge:
"""Add an edge to the graph and return it.
Args:
source: The source node of the edge.
target: The target node of the edge.
data: Optional data associated with the edge.
conditional: Whether the edge is conditional.
Returns:
The edge that was added to the graph.
Raises:
ValueError: If the source or target node is not in the graph.
"""
if source.id not in self.nodes:
msg = f"Source node {source.id} not in graph"
raise ValueError(msg)
if target.id not in self.nodes:
msg = f"Target node {target.id} not in graph"
raise ValueError(msg)
edge = Edge(
source=source.id, target=target.id, data=data, conditional=conditional
)
self.edges.append(edge)
return edge
def extend(
self, graph: Graph, *, prefix: str = ""
) -> tuple[Node | None, Node | None]:
"""Add all nodes and edges from another graph.
Note this doesn't check for duplicates, nor does it connect the graphs.
Args:
graph: The graph to add.
prefix: The prefix to add to the node ids.
Returns:
A tuple of the first and last nodes of the subgraph.
"""
if all(is_uuid(node.id) for node in graph.nodes.values()):
prefix = ""
def prefixed(id_: str) -> str:
return f"{prefix}:{id_}" if prefix else id_
# prefix each node
self.nodes.update(
{prefixed(k): v.copy(id=prefixed(k)) for k, v in graph.nodes.items()}
)
# prefix each edge's source and target
self.edges.extend(
[
edge.copy(source=prefixed(edge.source), target=prefixed(edge.target))
for edge in graph.edges
]
)
# return (prefixed) first and last nodes of the subgraph
first, last = graph.first_node(), graph.last_node()
return (
first.copy(id=prefixed(first.id)) if first else None,
last.copy(id=prefixed(last.id)) if last else None,
)
def reid(self) -> Graph:
"""Return a new graph with all nodes re-identified.
Uses their unique, readable names where possible.
"""
node_name_to_ids = defaultdict(list)
for node in self.nodes.values():
node_name_to_ids[node.name].append(node.id)
unique_labels = {
node_id: node_name if len(node_ids) == 1 else f"{node_name}_{i + 1}"
for node_name, node_ids in node_name_to_ids.items()
for i, node_id in enumerate(node_ids)
}
def _get_node_id(node_id: str) -> str:
label = unique_labels[node_id]
if is_uuid(node_id):
return label
return node_id
return Graph(
nodes={
_get_node_id(id_): node.copy(id=_get_node_id(id_))
for id_, node in self.nodes.items()
},
edges=[
edge.copy(
source=_get_node_id(edge.source),
target=_get_node_id(edge.target),
)
for edge in self.edges
],
)
def first_node(self) -> Node | None:
"""Find the single node that is not a target of any edge.
If there is no such node, or there are multiple, return `None`.
When drawing the graph, this node would be the origin.
Returns:
The first node, or None if there is no such node or multiple
candidates.
"""
return _first_node(self)
def last_node(self) -> Node | None:
"""Find the single node that is not a source of any edge.
If there is no such node, or there are multiple, return `None`.
When drawing the graph, this node would be the destination.
Returns:
The last node, or None if there is no such node or multiple
candidates.
"""
return _last_node(self)
def trim_first_node(self) -> None:
"""Remove the first node if it exists and has a single outgoing edge.
i.e., if removing it would not leave the graph without a "first" node.
"""
first_node = self.first_node()
if (
first_node
and _first_node(self, exclude=[first_node.id])
and len({e for e in self.edges if e.source == first_node.id}) == 1
):
self.remove_node(first_node)
def trim_last_node(self) -> None:
"""Remove the last node if it exists and has a single incoming edge.
i.e., if removing it would not leave the graph without a "last" node.
"""
last_node = self.last_node()
if (
last_node
and _last_node(self, exclude=[last_node.id])
and len({e for e in self.edges if e.target == last_node.id}) == 1
):
self.remove_node(last_node)
def draw_ascii(self) -> str:
"""Draw the graph as an ASCII art string.
Returns:
The ASCII art string.
"""
# Import locally to prevent circular import
from langchain_core.runnables.graph_ascii import draw_ascii # noqa: PLC0415
return draw_ascii(
{node.id: node.name for node in self.nodes.values()},
self.edges,
)
def print_ascii(self) -> None:
"""Print the graph as an ASCII art string."""
print(self.draw_ascii()) # noqa: T201
@overload
def draw_png(
self,
output_file_path: str,
fontname: str | None = None,
labels: LabelsDict | None = None,
) -> None: ...
@overload
def draw_png(
self,
output_file_path: None,
fontname: str | None = None,
labels: LabelsDict | None = None,
) -> bytes: ...
def draw_png(
self,
output_file_path: str | None = None,
fontname: str | None = None,
labels: LabelsDict | None = None,
) -> bytes | None:
"""Draw the graph as a PNG image.
Args:
output_file_path: The path to save the image to. If `None`, the image
is not saved.
fontname: The name of the font to use.
labels: Optional labels for nodes and edges in the graph. Defaults to
`None`.
Returns:
The PNG image as bytes if output_file_path is None, None otherwise.
"""
# Import locally to prevent circular import
from langchain_core.runnables.graph_png import PngDrawer # noqa: PLC0415
default_node_labels = {node.id: node.name for node in self.nodes.values()}
return PngDrawer(
fontname,
LabelsDict(
nodes={
**default_node_labels,
**(labels["nodes"] if labels is not None else {}),
},
edges=labels["edges"] if labels is not None else {},
),
).draw(self, output_file_path)
def draw_mermaid(
self,
*,
with_styles: bool = True,
curve_style: CurveStyle = CurveStyle.LINEAR,
node_colors: NodeStyles | None = None,
wrap_label_n_words: int = 9,
frontmatter_config: dict[str, Any] | None = None,
) -> str:
"""Draw the graph as a Mermaid syntax string.
Args:
with_styles: Whether to include styles in the syntax.
curve_style: The style of the edges.
node_colors: The colors of the nodes.
wrap_label_n_words: The number of words to wrap the node labels at.
frontmatter_config: Mermaid frontmatter config.
Can be used to customize theme and styles. Will be converted to YAML and
added to the beginning of the mermaid graph.
See more here: https://mermaid.js.org/config/configuration.html.
Example config:
```python
{
"config": {
"theme": "neutral",
"look": "handDrawn",
"themeVariables": {"primaryColor": "#e2e2e2"},
}
}
```
Returns:
The Mermaid syntax string.
"""
# Import locally to prevent circular import
from langchain_core.runnables.graph_mermaid import draw_mermaid # noqa: PLC0415
graph = self.reid()
first_node = graph.first_node()
last_node = graph.last_node()
return draw_mermaid(
nodes=graph.nodes,
edges=graph.edges,
first_node=first_node.id if first_node else None,
last_node=last_node.id if last_node else None,
with_styles=with_styles,
curve_style=curve_style,
node_styles=node_colors,
wrap_label_n_words=wrap_label_n_words,
frontmatter_config=frontmatter_config,
)
def draw_mermaid_png(
self,
*,
curve_style: CurveStyle = CurveStyle.LINEAR,
node_colors: NodeStyles | None = None,
wrap_label_n_words: int = 9,
output_file_path: str | None = None,
draw_method: MermaidDrawMethod = MermaidDrawMethod.API,
background_color: str = "white",
padding: int = 10,
max_retries: int = 1,
retry_delay: float = 1.0,
frontmatter_config: dict[str, Any] | None = None,
base_url: str | None = None,
proxies: dict[str, str] | None = None,
) -> bytes:
"""Draw the graph as a PNG image using Mermaid.
Args:
curve_style: The style of the edges.
node_colors: The colors of the nodes.
wrap_label_n_words: The number of words to wrap the node labels at.
output_file_path: The path to save the image to. If `None`, the image
is not saved.
draw_method: The method to use to draw the graph.
background_color: The color of the background.
padding: The padding around the graph.
max_retries: The maximum number of retries (`MermaidDrawMethod.API`).
retry_delay: The delay between retries (`MermaidDrawMethod.API`).
frontmatter_config: Mermaid frontmatter config.
Can be used to customize theme and styles. Will be converted to YAML and
added to the beginning of the mermaid graph.
See more here: https://mermaid.js.org/config/configuration.html.
Example config:
```python
{
"config": {
"theme": "neutral",
"look": "handDrawn",
"themeVariables": {"primaryColor": "#e2e2e2"},
}
}
```
base_url: The base URL of the Mermaid server for rendering via API.
proxies: HTTP/HTTPS proxies for requests (e.g. `{"http": "http://127.0.0.1:7890"}`).
Returns:
The PNG image as bytes.
"""
# Import locally to prevent circular import
from langchain_core.runnables.graph_mermaid import ( # noqa: PLC0415
draw_mermaid_png,
)
mermaid_syntax = self.draw_mermaid(
curve_style=curve_style,
node_colors=node_colors,
wrap_label_n_words=wrap_label_n_words,
frontmatter_config=frontmatter_config,
)
return draw_mermaid_png(
mermaid_syntax=mermaid_syntax,
output_file_path=output_file_path,
draw_method=draw_method,
background_color=background_color,
padding=padding,
max_retries=max_retries,
retry_delay=retry_delay,
proxies=proxies,
base_url=base_url,
)
def _first_node(graph: Graph, exclude: Sequence[str] = ()) -> Node | None:
"""Find the single node that is not a target of any edge.
Exclude nodes/sources with IDs in the exclude list.
If there is no such node, or there are multiple, return `None`.
When drawing the graph, this node would be the origin.
"""
targets = {edge.target for edge in graph.edges if edge.source not in exclude}
found: list[Node] = [
node
for node in graph.nodes.values()
if node.id not in exclude and node.id not in targets
]
return found[0] if len(found) == 1 else None
def _last_node(graph: Graph, exclude: Sequence[str] = ()) -> Node | None:
"""Find the single node that is not a source of any edge.
Exclude nodes/targets with IDs in the exclude list.
If there is no such node, or there are multiple, return `None`.
When drawing the graph, this node would be the destination.
"""
sources = {edge.source for edge in graph.edges if edge.target not in exclude}
found: list[Node] = [
node
for node in graph.nodes.values()
if node.id not in exclude and node.id not in sources
]
return found[0] if len(found) == 1 else None
| Graph |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/psycopg.py | {
"start": 9556,
"end": 10890
} | class ____(ranges.AbstractMultiRangeImpl):
def bind_processor(self, dialect):
psycopg_Range = cast(PGDialect_psycopg, dialect)._psycopg_Range
psycopg_Multirange = cast(
PGDialect_psycopg, dialect
)._psycopg_Multirange
def to_range(value):
if isinstance(value, (str, NoneType, psycopg_Multirange)):
return value
return psycopg_Multirange(
[
psycopg_Range(
element.lower,
element.upper,
element.bounds,
element.empty,
)
for element in cast("Iterable[ranges.Range]", value)
]
)
return to_range
def result_processor(self, dialect, coltype):
def to_range(value):
if value is None:
return None
else:
return ranges.MultiRange(
ranges.Range(
elem._lower,
elem._upper,
bounds=elem._bounds if elem._bounds else "[)",
empty=not elem._bounds,
)
for elem in value
)
return to_range
| _PsycopgMultiRange |
python | spack__spack | lib/spack/spack/llnl/util/lang.py | {
"start": 20111,
"end": 21160
} | class ____:
"""Base class that wraps an object. Derived classes can add new behavior
while staying undercover.
This class is modeled after the stackoverflow answer:
* http://stackoverflow.com/a/1445289/771663
"""
def __init__(self, wrapped_object):
wrapped_cls = type(wrapped_object)
wrapped_name = wrapped_cls.__name__
# If the wrapped object is already an ObjectWrapper, or a derived class
# of it, adding type(self) in front of type(wrapped_object)
# results in an inconsistent MRO.
#
# TODO: the implementation below doesn't account for the case where we
# TODO: have different base classes of ObjectWrapper, say A and B, and
# TODO: we want to wrap an instance of A with B.
if type(self) not in wrapped_cls.__mro__:
self.__class__ = type(wrapped_name, (type(self), wrapped_cls), {})
else:
self.__class__ = type(wrapped_name, (wrapped_cls,), {})
self.__dict__ = wrapped_object.__dict__
| ObjectWrapper |
python | tensorflow__tensorflow | tensorflow/python/ops/variable_scope.py | {
"start": 8907,
"end": 42152
} | class ____:
"""Variable store that carries a number of named Variables.
New variable names and new variables can be created; all stored
variables are initialized with the initializer passed to __init__.
Attributes:
vars: a dictionary with string names (same as passed in GetVar) as keys and
the corresponding TensorFlow Variables as values.
"""
__slots__ = ["_vars", "_partitioned_vars", "_store_eager_variables"]
def __init__(self):
"""Create a variable store."""
self._vars = {} # A dictionary of the stored TensorFlow variables.
self._partitioned_vars = {} # A dict of the stored PartitionedVariables.
self._store_eager_variables = False
def get_variable(self,
name,
shape=None,
dtype=dtypes.float32,
initializer=None,
regularizer=None,
reuse=None,
trainable=None,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True,
use_resource=None,
custom_getter=None,
constraint=None,
synchronization=VariableSynchronization.AUTO,
aggregation=VariableAggregation.NONE):
"""Gets an existing variable with these parameters or create a new one.
If a variable with the given name is already stored, we return the stored
variable. Otherwise, we create a new one.
Set `reuse` to `True` when you only want to reuse existing Variables.
Set `reuse` to `False` when you only want to create new Variables.
Set `reuse` to None (the default) or tf.compat.v1.AUTO_REUSE when you want
variables to be created if they don't exist or returned if they do.
If initializer is `None` (the default), the default initializer passed in
the constructor is used. If that one is `None` too, we use a new
`glorot_uniform_initializer`. If initializer is a Tensor, we use
it as a value and derive the shape from the initializer.
If a partitioner is provided, a `PartitionedVariable` is returned.
Accessing this object as a `Tensor` returns the shards concatenated along
the partition axis.
Some useful partitioners are available. See, e.g.,
`variable_axis_size_partitioner` and `min_max_variable_partitioner`.
Args:
name: The name of the new or existing variable.
shape: Shape of the new or existing variable.
dtype: Type of the new or existing variable (defaults to `DT_FLOAT`).
initializer: Initializer for the variable.
regularizer: A (Tensor -> Tensor or None) function; the result of applying
it on a newly created variable will be added to the collection
GraphKeys.REGULARIZATION_LOSSES and can be used for regularization.
reuse: a Boolean, None, or tf.AUTO_REUSE. Controls reuse or creation of
variables. When eager execution is enabled this argument is always
forced to be False.
trainable: If `True` also add the variable to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). `trainable`
defaults to `True`, unless `synchronization` is set to `ON_READ`, in
which case it defaults to `False`.
collections: List of graph collections keys to add the `Variable` to.
Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`).
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the `Variable` reside, to
deduplicate copying through `Switch` and other conditional statements.
partitioner: Optional callable that accepts a fully defined `TensorShape`
and dtype of the `Variable` to be created, and returns a list of
partitions for each axis (currently only one axis can be partitioned).
validate_shape: If False, allows the variable to be initialized with a
value of unknown shape. If True, the default, the shape of initial_value
must be known.
use_resource: If False, creates a regular Variable. If True, creates
instead an experimental ResourceVariable which has well-defined
semantics. Defaults to False (will later change to True). When eager
execution is enabled this argument is always forced to be true.
custom_getter: Callable that takes as a first argument the true getter,
and allows overwriting the internal get_variable method. The signature
of `custom_getter` should match that of this method,
but the most future-proof version will allow for changes: `def
custom_getter(getter, *args, **kwargs)`. Direct access to
all `get_variable` parameters is also allowed: `def
custom_getter(getter, name, *args, **kwargs)`. A simple identity
custom getter that simply creates variables with modified names is:
```python
def custom_getter(getter, name, *args, **kwargs): return getter(name +
'_suffix', *args, **kwargs) ```
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value (which must have
the same shape). Constraints are not safe to use when doing asynchronous
distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses when to
synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
Returns:
The created or existing `Variable` (or `PartitionedVariable`, if a
partitioner was used).
Raises:
ValueError: when creating a new variable and shape is not declared,
when reusing a variable and specifying a conflicting shape,
or when violating reuse during variable creation.
RuntimeError: when eager execution is enabled and not called from an
EagerVariableStore.
"""
if custom_getter is not None and not callable(custom_getter):
raise ValueError("Passed a custom_getter which is not callable: %s" %
custom_getter)
with ops.init_scope():
if context.executing_eagerly():
# Variable creation and initialization takes place in `init_scope`s;
# as such, if an `init_scope` lifts us into the eager context, then we
# need to use `ResourceVariable`s.
use_resource = True
# Note that it's fine to reuse eager variables whose initialization was
# lifted from a function-building graph into the eager context (that's why
# the following clause is not wrapped in an `init_scope`); lifted variables
# are tracked by the graph's `VariableStore`.
if context.executing_eagerly():
if not self._store_eager_variables and reuse:
raise RuntimeError(
"When eager execution is enabled variable reuse is only supported"
" when an EagerVariableStore is active. See the documentation on"
" EagerVariableStore for example usage.")
if self._store_eager_variables:
reuse = AUTO_REUSE
# If a *_ref type is passed in an error would be triggered further down the
# stack. We prevent this using base_dtype to get a non-ref version of the
# type, before doing anything else. When _ref types are removed in favor of
# resources, this line can be removed.
try:
dtype = dtype.base_dtype
except AttributeError:
# .base_dtype not existing means that we will try and use the raw dtype
# which was passed in - this might be a NumPy type which is valid.
pass
# This is the main logic of get_variable. However, custom_getter
# may override this logic. So we save it as a callable and pass
# it to custom_getter.
# Note: the parameters of _true_getter, and their documentation, match
# *exactly* item-for-item with the docstring of this method.
def _true_getter( # pylint: disable=missing-docstring
name,
shape=None,
dtype=dtypes.float32,
initializer=None,
regularizer=None,
reuse=None,
trainable=None,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True,
use_resource=None,
constraint=None,
synchronization=VariableSynchronization.AUTO,
aggregation=VariableAggregation.NONE):
is_scalar = (
shape is not None and isinstance(shape, collections_abc.Sequence) and
not shape)
# Partitioned variable case
if partitioner is not None and not is_scalar:
if not callable(partitioner):
raise ValueError("Partitioner must be callable, but received: %s" %
partitioner)
with ops.name_scope(None):
return self._get_partitioned_variable(
name=name,
shape=shape,
dtype=dtype,
initializer=initializer,
regularizer=regularizer,
reuse=reuse,
trainable=trainable,
collections=collections,
caching_device=caching_device,
partitioner=partitioner,
validate_shape=validate_shape,
use_resource=use_resource,
constraint=constraint,
synchronization=synchronization,
aggregation=aggregation)
# Special case for partitioned variable to allow reuse without having to
# specify partitioner.
if (reuse is True and partitioner is None
and name in self._partitioned_vars):
return self._get_partitioned_variable(
name=name,
shape=shape,
dtype=dtype,
initializer=initializer,
regularizer=regularizer,
reuse=reuse,
trainable=trainable,
collections=collections,
caching_device=caching_device,
partitioner=None,
validate_shape=validate_shape,
use_resource=use_resource,
constraint=constraint,
synchronization=synchronization,
aggregation=aggregation)
# Single variable case
if "%s/part_0" % name in self._vars:
raise ValueError(
"No partitioner was provided, but a partitioned version of the "
"variable was found: %s/part_0. Perhaps a variable of the same "
"name was already created with partitioning?" % name)
return self._get_single_variable(
name=name,
shape=shape,
dtype=dtype,
initializer=initializer,
regularizer=regularizer,
reuse=reuse,
trainable=trainable,
collections=collections,
caching_device=caching_device,
validate_shape=validate_shape,
use_resource=use_resource,
constraint=constraint,
synchronization=synchronization,
aggregation=aggregation)
synchronization, aggregation, trainable = (
variables.validate_synchronization_aggregation_trainable(
synchronization, aggregation, trainable, name))
if custom_getter is not None:
# Handle backwards compatibility with getter arguments that were added
# to the API after users started writing custom getters.
custom_getter_kwargs = {
"getter": _true_getter,
"name": name,
"shape": shape,
"dtype": dtype,
"initializer": initializer,
"regularizer": regularizer,
"reuse": reuse,
"trainable": trainable,
"collections": collections,
"caching_device": caching_device,
"partitioner": partitioner,
"validate_shape": validate_shape,
"use_resource": use_resource,
"synchronization": synchronization,
"aggregation": aggregation,
}
# `fn_args` and `has_kwargs` can handle functions, `functools.partial`,
# `lambda`.
if ("constraint" in function_utils.fn_args(custom_getter) or
function_utils.has_kwargs(custom_getter)):
custom_getter_kwargs["constraint"] = constraint
return custom_getter(**custom_getter_kwargs)
else:
return _true_getter(
name,
shape=shape,
dtype=dtype,
initializer=initializer,
regularizer=regularizer,
reuse=reuse,
trainable=trainable,
collections=collections,
caching_device=caching_device,
partitioner=partitioner,
validate_shape=validate_shape,
use_resource=use_resource,
constraint=constraint,
synchronization=synchronization,
aggregation=aggregation)
def _get_partitioned_variable(self,
name,
partitioner,
shape=None,
dtype=dtypes.float32,
initializer=None,
regularizer=None,
reuse=None,
trainable=None,
collections=None,
caching_device=None,
validate_shape=True,
use_resource=None,
constraint=None,
synchronization=VariableSynchronization.AUTO,
aggregation=VariableAggregation.NONE):
"""Gets or creates a sharded variable list with these parameters.
The `partitioner` must be a callable that accepts a fully defined
`TensorShape` and returns a sequence of integers (the `partitions`).
These integers describe how to partition the given sharded `Variable`
along the given dimension. That is, `partitions[1] = 3` means split
the `Variable` into 3 shards along dimension 1. Currently, sharding along
only one axis is supported.
If the list of variables with the given name (prefix) is already stored,
we return the stored variables. Otherwise, we create a new one.
Set `reuse` to `True` when you only want to reuse existing Variables.
Set `reuse` to `False` when you only want to create new Variables.
Set `reuse` to None (the default) or tf.compat.v1.AUTO_REUSE when you want
variables to be created if they don't exist or returned if they do.
If initializer is `None` (the default), the default initializer passed in
the constructor is used. If that one is `None` too, we use a new
`glorot_uniform_initializer`. If initializer is a Tensor, we use
it as a value and derive the shape from the initializer.
If the initializer is a callable, then it will be called for each
shard. Otherwise the initializer should match the shape of the entire
sharded Variable, and it will be sliced accordingly for each shard.
Some useful partitioners are available. See, e.g.,
`variable_axis_size_partitioner` and `min_max_variable_partitioner`.
Args:
name: the name of the new or existing sharded variable.
partitioner: Optional callable that accepts a fully defined `TensorShape`
and `dtype` of the Variable to be created, and returns a list of
partitions for each axis (currently only one axis can be partitioned).
shape: shape of the new or existing sharded variable.
dtype: type of the new or existing sharded variable (defaults to
`DT_FLOAT`).
initializer: initializer for the sharded variable.
regularizer: a (Tensor -> Tensor or None) function; the result of applying
it on a newly created variable will be added to the collection
GraphKeys.REGULARIZATION_LOSSES and can be used for regularization.
reuse: a Boolean, None, or tf.AUTO_REUSE. Controls reuse or creation of
variables.
trainable: If `True` also add the variable to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).
collections: List of graph collections keys to add the Variable to.
Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`).
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the Variable reside, to
deduplicate copying through `Switch` and other conditional statements.
validate_shape: If False, allows the variable to be initialized with a
value of unknown shape. If True, the default, the shape of initial_value
must be known.
use_resource: If False, creates a regular Variable. If True, creates an
experimental ResourceVariable which has well-defined semantics. Defaults
to False (will later change to True).
constraint: An optional projection function to be applied to the variable
after being updated by an `Optimizer` (e.g. used to implement norm
constraints or value constraints for layer weights). The function must
take as input the unprojected Tensor representing the value of the
variable and return the Tensor for the projected value (which must have
the same shape). Constraints are not safe to use when doing asynchronous
distributed training.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses when to
synchronize.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
Returns:
A `PartitionedVariable` object.
Raises:
ValueError: when creating a new variable and shape is not declared,
when reusing a variable and specifying a conflicting shape,
when violating reuse during variable creation, or if an existing
sharded variable exists for the given name but with different sharding.
"""
initializing_from_value = initializer is not None and isinstance(
initializer, tensor.Tensor)
if name in self._vars:
raise ValueError(
"A partitioner was provided, but an unpartitioned version of the "
"variable was found: %s. Perhaps a variable of the same name was "
"already created without partitioning?" % name)
shape = tensor_shape.as_shape(shape)
if initializing_from_value:
shape = shape.merge_with(initializer.get_shape())
partitions = None
if not reuse or partitioner:
partitions = _call_partitioner(partitioner, shape, dtype)
if name in self._partitioned_vars:
if reuse is False:
raise ValueError(
"Partitioned variable with name %s already exists. Did you mean to "
"set reuse=True or reuse=tf.AUTO_REUSE in VarScope?" % name)
existing_var = self._partitioned_vars[name]
if not shape.is_compatible_with(existing_var.get_shape()):
raise ValueError(
"Trying to reuse partitioned variable %s, but specified shape %s "
"and found shape %s." % (name, shape, existing_var.get_shape()))
if not dtype.is_compatible_with(existing_var.dtype):
raise ValueError(
"Trying to reuse partitioned variable %s, but specified dtype %s "
"and found dtype %s." % (name, dtype.name, existing_var.dtype.name))
# pylint: disable=protected-access
if (partitions is not None and
existing_var._get_partitions() != partitions):
raise ValueError(
"Trying to reuse partitioned variable %s, but specified partitions "
"%s and found partitions %s." %
(name, partitions, existing_var._get_partitions()))
# pylint: enable=protected-access
return existing_var
if reuse is True:
raise ValueError("PartitionedVariable %s does not exist, or was not "
"created with tf.get_variable(). Did you mean to set "
"reuse=False or reuse=tf.AUTO_REUSE in VarScope?" % name)
slice_dim, num_slices = _get_slice_dim_and_num_slices(partitions)
if "%s/part_0" % name in self._vars:
if "%s/part_%d" % (name, num_slices - 1) not in self._vars:
raise ValueError(
"Partitioner returned a different partitioning than what was "
"already found. Partitioner returned %d shards, and shard "
"%s/part_0 was found, but %s/part_%d was not." %
(num_slices, name, name, num_slices - 1))
if "%s/part_%d" % (name, num_slices) in self._vars:
raise ValueError(
"Partitioner returned a different partitioning than what was "
"already found. Partitioner returned %d shards, and shard "
"%s/part_0 was found, but so was the extra shard %s/part_%d." %
(num_slices, name, name, num_slices))
vs = []
for i, (var_offset, var_shape) in enumerate(
_iter_slices(shape.as_list(), num_slices, slice_dim)):
partition_info = _PartitionInfo(
full_shape=shape.as_list(), var_offset=var_offset)
var_full_name = "%s/part_%d" % (name, i)
with ops.name_scope(
var_full_name + "/PartitionedInitializer", skip_on_eager=False):
# Create the tensor to initialize the variable with default value.
if initializer is None:
init, initializing_from_value = self._get_default_initializer(
name=name, shape=shape, dtype=dtype)
if initializing_from_value:
init_shape = None
else:
init_shape = var_shape
elif callable(initializer):
init = initializer
init_shape = var_shape
elif isinstance(initializer, tensor.Tensor):
init = array_ops.slice(initializer, var_offset, var_shape)
# Use the dtype of the given tensor.
dtype = init.dtype.base_dtype
init_shape = None
else:
init = ops.convert_to_tensor(initializer, dtype=dtype)
init = array_ops.slice(init, var_offset, var_shape)
init_shape = None
with ops.name_scope(None):
var = self._get_single_variable(
name=var_full_name,
shape=init_shape,
dtype=dtype,
initializer=init,
partition_info=partition_info,
regularizer=regularizer,
reuse=reuse,
trainable=trainable,
collections=collections,
caching_device=caching_device,
validate_shape=validate_shape,
use_resource=use_resource,
constraint=constraint,
synchronization=synchronization,
aggregation=aggregation,
)
# pylint: disable=protected-access
var._set_save_slice_info(
variables.Variable.SaveSliceInfo(name, shape.as_list(), var_offset,
var_shape))
vs.append(var)
# pylint: enable=protected-access
partitioned_var = variables.PartitionedVariable(
name=name,
shape=shape,
dtype=dtype,
variable_list=vs,
partitions=partitions)
if not context.executing_eagerly() or self._store_eager_variables:
self._partitioned_vars[name] = partitioned_var
return partitioned_var
def _get_single_variable(self,
name,
shape=None,
dtype=dtypes.float32,
initializer=None,
regularizer=None,
partition_info=None,
reuse=None,
trainable=None,
collections=None,
caching_device=None,
validate_shape=True,
use_resource=None,
constraint=None,
synchronization=VariableSynchronization.AUTO,
aggregation=VariableAggregation.NONE):
"""Get or create a single Variable (e.g.
a shard or entire variable).
See the documentation of get_variable above (ignore partitioning components)
for details.
Args:
name: see get_variable.
shape: see get_variable.
dtype: see get_variable.
initializer: see get_variable.
regularizer: see get_variable.
partition_info: _PartitionInfo object.
reuse: see get_variable.
trainable: see get_variable.
collections: see get_variable.
caching_device: see get_variable.
validate_shape: see get_variable.
use_resource: see get_variable.
constraint: see get_variable.
synchronization: see get_variable.
aggregation: see get_variable.
Returns:
A Variable. See documentation of get_variable above.
Raises:
ValueError: See documentation of get_variable above.
"""
# Set to true if initializer is a constant.
initializing_from_value = False
if initializer is not None and not callable(initializer):
initializing_from_value = True
if shape is not None and initializing_from_value:
raise ValueError("If initializer is a constant, do not specify shape.")
dtype = dtypes.as_dtype(dtype)
if shape is not None:
shape = tensor_shape.as_shape(shape)
if name in self._vars:
# Here we handle the case when returning an existing variable.
if reuse is False:
var = self._vars[name]
err_msg = ("Variable %s already exists, disallowed."
" Did you mean to set reuse=True or "
"reuse=tf.AUTO_REUSE in VarScope?" % name)
# ResourceVariables don't have an op associated with so no traceback
if isinstance(var, resource_variable_ops.ResourceVariable):
raise ValueError(err_msg)
tb = var.op.traceback[::-1]
# Throw away internal tf entries and only take a few lines. In some
# cases the traceback can be longer (e.g. if someone uses factory
# functions to create variables) so we take more than needed in the
# default case.
tb = [x for x in tb if "tensorflow/python" not in x[0]][:5]
raise ValueError("%s Originally defined at:\n\n%s" %
(err_msg, "".join(traceback.format_list(tb))))
found_var = self._vars[name]
if shape is not None and not shape.is_compatible_with(
found_var.get_shape()
):
raise ValueError("Trying to share variable %s, but specified shape %s"
" and found shape %s." %
(name, shape, found_var.get_shape()))
if not dtype.is_compatible_with(found_var.dtype):
dtype_str = dtype.name
found_type_str = found_var.dtype.name
raise ValueError("Trying to share variable %s, but specified dtype %s"
" and found dtype %s." %
(name, dtype_str, found_type_str))
return found_var
# The code below handles only the case of creating a new variable.
if reuse is True:
raise ValueError("Variable %s does not exist, or was not created with "
"tf.get_variable(). Did you mean to set "
"reuse=tf.AUTO_REUSE in VarScope?" % name)
# Create the tensor to initialize the variable with default value.
if initializer is None:
if shape is None:
raise ValueError(
f"Variable {name} did not get an initializer, so its `shape`"
" argument must be specified."
)
initializer, initializing_from_value = self._get_default_initializer(
name=name, shape=shape, dtype=dtype)
# Enter an init scope when creating the initializer.
with ops.init_scope():
if initializing_from_value:
init_val = initializer
variable_dtype = None
else:
# Instantiate initializer if provided initializer is a type object.
if tf_inspect.isclass(initializer):
initializer = initializer()
if shape is not None and shape.is_fully_defined():
if "partition_info" in tf_inspect.getargspec(initializer).args:
init_val = functools.partial(initializer,
shape.as_list(),
dtype=dtype,
partition_info=partition_info)
else:
init_val = functools.partial(initializer,
shape.as_list(), dtype=dtype)
variable_dtype = dtype.base_dtype
elif _needs_no_arguments(initializer):
init_val = initializer
variable_dtype = None
else:
raise ValueError("The initializer passed is not valid. It should "
"be a callable with no arguments and the "
"shape should not be provided or an instance of "
"`tf.keras.initializers.*' and `shape` should be "
"fully defined.")
# Create the variable.
if use_resource is None:
# Set the default value if unspecified.
use_resource = resource_variables_toggle.resource_variables_enabled()
v = _variable_v1(
initial_value=init_val,
name=name,
trainable=trainable,
collections=collections,
caching_device=caching_device,
dtype=variable_dtype,
validate_shape=validate_shape,
constraint=constraint,
use_resource=use_resource,
synchronization=synchronization,
aggregation=aggregation,
shape=shape,
)
if context.executing_eagerly() and self._store_eager_variables:
if collections:
ops.add_to_collections(collections, v)
else:
ops.add_to_collection(ops.GraphKeys.GLOBAL_VARIABLES, v)
if trainable:
ops.add_to_collection(ops.GraphKeys.TRAINABLE_VARIABLES, v)
if not context.executing_eagerly() or self._store_eager_variables:
# In eager mode we do not want to keep default references to Variable
# objects as this will prevent their memory from being released.
self._vars[name] = v
logging.vlog(1, "Created variable %s with shape %s and init %s", v.name,
format(shape), initializer)
# Run the regularizer if requested and save the resulting loss.
if regularizer:
def make_regularizer_op():
with ops.colocate_with(v):
with ops.name_scope(name + "/Regularizer/"):
return regularizer(v)
if regularizer(v) is not None:
lazy_eval_tensor = _LazyEvalTensor(make_regularizer_op)
ops.add_to_collection(ops.GraphKeys.REGULARIZATION_LOSSES,
lazy_eval_tensor)
return v
# Initialize variable when no initializer provided
def _get_default_initializer(self, name, shape=None, dtype=dtypes.float32):
"""Provide a default initializer and a corresponding value.
Args:
name: see get_variable.
shape: see get_variable.
dtype: see get_variable.
Returns:
initializer and initializing_from_value. See get_variable above.
Raises:
ValueError: When giving unsupported dtype.
"""
del shape
# If dtype is DT_FLOAT, provide a uniform unit scaling initializer
if dtype.is_floating:
initializer = init_ops.glorot_uniform_initializer()
initializing_from_value = False
# If dtype is DT_INT/DT_UINT, provide a default value `zero`
# If dtype is DT_BOOL, provide a default value `FALSE`
elif (dtype.is_integer or dtype.is_unsigned or dtype.is_bool or
dtype == dtypes.string):
initializer = init_ops.zeros_initializer()
initializing_from_value = False
# NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here?
else:
raise ValueError("An initializer for variable %s of %s is required" %
(name, dtype.base_dtype))
return initializer, initializing_from_value
| _VariableStore |
python | pandas-dev__pandas | pandas/tests/arithmetic/test_datetime64.py | {
"start": 4957,
"end": 13586
} | class ____:
# TODO: moved from tests.series.test_operators; needs cleanup
@pytest.mark.parametrize(
"pair",
[
(
[Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")],
[NaT, NaT, Timestamp("2011-01-03")],
),
(
[Timedelta("1 days"), NaT, Timedelta("3 days")],
[NaT, NaT, Timedelta("3 days")],
),
(
[Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")],
[NaT, NaT, Period("2011-03", freq="M")],
),
],
)
@pytest.mark.parametrize("reverse", [True, False])
@pytest.mark.parametrize("dtype", [None, object])
@pytest.mark.parametrize(
"op, expected",
[
(operator.eq, [False, False, True]),
(operator.ne, [True, True, False]),
(operator.lt, [False, False, False]),
(operator.gt, [False, False, False]),
(operator.ge, [False, False, True]),
(operator.le, [False, False, True]),
],
)
def test_nat_comparisons(
self,
dtype,
index_or_series,
reverse,
pair,
op,
expected,
):
box = index_or_series
lhs, rhs = pair
if reverse:
# add lhs / rhs switched data
lhs, rhs = rhs, lhs
left = Series(lhs, dtype=dtype)
right = box(rhs, dtype=dtype)
result = op(left, right)
tm.assert_series_equal(result, Series(expected))
@pytest.mark.parametrize(
"data",
[
[Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")],
[Timedelta("1 days"), NaT, Timedelta("3 days")],
[Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")],
],
)
@pytest.mark.parametrize("dtype", [None, object])
def test_nat_comparisons_scalar(self, dtype, data, box_with_array):
box = box_with_array
left = Series(data, dtype=dtype)
left = tm.box_expected(left, box)
xbox = get_upcast_box(left, NaT, True)
expected = [False, False, False]
expected = tm.box_expected(expected, xbox)
if box is pd.array and dtype is object:
expected = pd.array(expected, dtype="bool")
tm.assert_equal(left == NaT, expected)
tm.assert_equal(NaT == left, expected)
expected = [True, True, True]
expected = tm.box_expected(expected, xbox)
if box is pd.array and dtype is object:
expected = pd.array(expected, dtype="bool")
tm.assert_equal(left != NaT, expected)
tm.assert_equal(NaT != left, expected)
expected = [False, False, False]
expected = tm.box_expected(expected, xbox)
if box is pd.array and dtype is object:
expected = pd.array(expected, dtype="bool")
tm.assert_equal(left < NaT, expected)
tm.assert_equal(NaT > left, expected)
tm.assert_equal(left <= NaT, expected)
tm.assert_equal(NaT >= left, expected)
tm.assert_equal(left > NaT, expected)
tm.assert_equal(NaT < left, expected)
tm.assert_equal(left >= NaT, expected)
tm.assert_equal(NaT <= left, expected)
@pytest.mark.parametrize("val", [datetime(2000, 1, 4), datetime(2000, 1, 5)])
def test_series_comparison_scalars(self, val):
series = Series(date_range("1/1/2000", periods=10))
result = series > val
expected = Series([x > val for x in series])
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"left,right", [("lt", "gt"), ("le", "ge"), ("eq", "eq"), ("ne", "ne")]
)
def test_timestamp_compare_series(self, left, right):
# see gh-4982
# Make sure we can compare Timestamps on the right AND left hand side.
ser = Series(date_range("20010101", periods=10), name="dates")
s_nat = ser.copy(deep=True)
ser[0] = Timestamp("nat")
ser[3] = Timestamp("nat")
left_f = getattr(operator, left)
right_f = getattr(operator, right)
# No NaT
expected = left_f(ser, Timestamp("20010109"))
result = right_f(Timestamp("20010109"), ser)
tm.assert_series_equal(result, expected)
# NaT
expected = left_f(ser, Timestamp("nat"))
result = right_f(Timestamp("nat"), ser)
tm.assert_series_equal(result, expected)
# Compare to Timestamp with series containing NaT
expected = left_f(s_nat, Timestamp("20010109"))
result = right_f(Timestamp("20010109"), s_nat)
tm.assert_series_equal(result, expected)
# Compare to NaT with series containing NaT
expected = left_f(s_nat, NaT)
result = right_f(NaT, s_nat)
tm.assert_series_equal(result, expected)
def test_dt64arr_timestamp_equality(self, box_with_array):
# GH#11034
box = box_with_array
ser = Series([Timestamp("2000-01-29 01:59:00"), Timestamp("2000-01-30"), NaT])
ser = tm.box_expected(ser, box)
xbox = get_upcast_box(ser, ser, True)
result = ser != ser
expected = tm.box_expected([False, False, True], xbox)
tm.assert_equal(result, expected)
if box is pd.DataFrame:
# alignment for frame vs series comparisons deprecated
# in GH#46795 enforced 2.0
with pytest.raises(ValueError, match="not aligned"):
ser != ser[0]
else:
result = ser != ser[0]
expected = tm.box_expected([False, True, True], xbox)
tm.assert_equal(result, expected)
if box is pd.DataFrame:
# alignment for frame vs series comparisons deprecated
# in GH#46795 enforced 2.0
with pytest.raises(ValueError, match="not aligned"):
ser != ser[2]
else:
result = ser != ser[2]
expected = tm.box_expected([True, True, True], xbox)
tm.assert_equal(result, expected)
result = ser == ser
expected = tm.box_expected([True, True, False], xbox)
tm.assert_equal(result, expected)
if box is pd.DataFrame:
# alignment for frame vs series comparisons deprecated
# in GH#46795 enforced 2.0
with pytest.raises(ValueError, match="not aligned"):
ser == ser[0]
else:
result = ser == ser[0]
expected = tm.box_expected([True, False, False], xbox)
tm.assert_equal(result, expected)
if box is pd.DataFrame:
# alignment for frame vs series comparisons deprecated
# in GH#46795 enforced 2.0
with pytest.raises(ValueError, match="not aligned"):
ser == ser[2]
else:
result = ser == ser[2]
expected = tm.box_expected([False, False, False], xbox)
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"datetimelike",
[
Timestamp("20130101"),
datetime(2013, 1, 1),
np.datetime64("2013-01-01T00:00", "ns"),
],
)
@pytest.mark.parametrize(
"op,expected",
[
(operator.lt, [True, False, False, False]),
(operator.le, [True, True, False, False]),
(operator.eq, [False, True, False, False]),
(operator.gt, [False, False, False, True]),
],
)
def test_dt64_compare_datetime_scalar(self, datetimelike, op, expected):
# GH#17965, test for ability to compare datetime64[ns] columns
# to datetimelike
ser = Series(
[
Timestamp("20120101"),
Timestamp("20130101"),
np.nan,
Timestamp("20130103"),
],
name="A",
)
result = op(ser, datetimelike)
expected = Series(expected, name="A")
tm.assert_series_equal(result, expected)
def test_ts_series_numpy_maximum(self):
# GH#50864, test numpy.maximum does not fail
# given a TimeStamp and Series(with dtype datetime64) comparison
ts = Timestamp("2024-07-01")
ts_series = Series(
["2024-06-01", "2024-07-01", "2024-08-01"],
dtype="datetime64[us]",
)
expected = Series(
["2024-07-01", "2024-07-01", "2024-08-01"],
dtype="datetime64[us]",
)
tm.assert_series_equal(expected, np.maximum(ts, ts_series))
| TestDatetime64SeriesComparison |
python | django-import-export__django-import-export | tests/core/admin.py | {
"start": 2231,
"end": 2317
} | class ____(ImportExportModelAdmin):
pass
@admin.register(UUIDCategory)
| UUIDBookAdmin |
python | PrefectHQ__prefect | src/prefect/server/orchestration/policies.py | {
"start": 2527,
"end": 2643
} | class ____(
BaseOrchestrationPolicy[orm_models.FlowRun, core.FlowRunPolicy]
):
pass
| FlowRunOrchestrationPolicy |
python | numpy__numpy | numpy/_core/tests/test_deprecations.py | {
"start": 13363,
"end": 14163
} | class ____(_DeprecationTestCase):
# Deprecated in Numpy 2.2, 2024-11
@pytest.mark.thread_unsafe(
reason="modifies and checks docstring which is global state"
)
def test_deprecated(self):
doc = struct_ufunc.add_triplet.__doc__
# gh-26718
# This test mutates the C-level docstring pointer for add_triplet,
# which is permanent once set. Skip when re-running tests.
if doc is not None and "new docs" in doc:
pytest.skip("Cannot retest deprecation, otherwise ValueError: "
"Cannot change docstring of ufunc with non-NULL docstring")
self.assert_deprecated(
lambda: np._core.umath._add_newdoc_ufunc(
struct_ufunc.add_triplet, "new docs"
)
)
| TestAddNewdocUFunc |
python | sqlalchemy__sqlalchemy | test/sql/test_metadata.py | {
"start": 144545,
"end": 157703
} | class ____(AssertsCompiledSQL, fixtures.TestBase):
"""Test Column() construction."""
__dialect__ = "default"
def columns(self):
return [
Column(Integer),
Column("b", Integer),
Column(Integer),
Column("d", Integer),
Column(Integer, name="e"),
Column(type_=Integer),
Column(Integer()),
Column("h", Integer()),
Column(type_=Integer()),
]
def test_basic(self):
c = self.columns()
for i, v in ((0, "a"), (2, "c"), (5, "f"), (6, "g"), (8, "i")):
c[i].name = v
c[i].key = v
del i, v
tbl = Table("table", MetaData(), *c)
for i, col in enumerate(tbl.c):
assert col.name == c[i].name
def test_name_none(self):
c = Column(Integer)
assert_raises_message(
exc.ArgumentError,
"Column must be constructed with a non-blank name or assign a "
"non-blank .name ",
Table,
"t",
MetaData(),
c,
)
def test_name_blank(self):
c = Column("", Integer)
assert_raises_message(
exc.ArgumentError,
"Column must be constructed with a non-blank name or assign a "
"non-blank .name ",
Table,
"t",
MetaData(),
c,
)
def test_no_shared_column_schema(self):
c = Column("x", Integer)
Table("t", MetaData(), c)
assert_raises_message(
exc.ArgumentError,
"Column object 'x' already assigned to Table 't'",
Table,
"q",
MetaData(),
c,
)
def test_no_shared_column_sql(self):
c = column("x", Integer)
table("t", c)
assert_raises_message(
exc.ArgumentError,
"column object 'x' already assigned to table 't'",
table,
"q",
c,
)
def test_incomplete_key(self):
c = Column(Integer)
assert c.name is None
assert c.key is None
c.name = "named"
Table("t", MetaData(), c)
assert c.name == "named"
assert c.name == c.key
def test_unique_index_flags_default_to_none(self):
c = Column(Integer)
eq_(c.unique, None)
eq_(c.index, None)
c = Column("c", Integer, index=True)
eq_(c.unique, None)
eq_(c.index, True)
t = Table("t", MetaData(), c)
eq_(list(t.indexes)[0].unique, False)
c = Column(Integer, unique=True)
eq_(c.unique, True)
eq_(c.index, None)
c = Column("c", Integer, index=True, unique=True)
eq_(c.unique, True)
eq_(c.index, True)
t = Table("t", MetaData(), c)
eq_(list(t.indexes)[0].unique, True)
def test_bogus(self):
assert_raises(exc.ArgumentError, Column, "foo", name="bar")
assert_raises(
exc.ArgumentError, Column, "foo", Integer, type_=Integer()
)
def test_custom_subclass_proxy(self):
"""test proxy generation of a Column subclass, can be compiled."""
from sqlalchemy.schema import Column
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql import select
class MyColumn(Column):
def _constructor(self, name, type_, **kw):
kw["name"] = name
return MyColumn(type_, **kw)
def __init__(self, type_, **kw):
Column.__init__(self, type_, **kw)
def my_goofy_thing(self):
return "hi"
@compiles(MyColumn)
def goofy(element, compiler, **kw):
s = compiler.visit_column(element, **kw)
return s + "-"
id_ = MyColumn(Integer, primary_key=True)
id_.name = "id"
name = MyColumn(String)
name.name = "name"
t1 = Table("foo", MetaData(), id_, name)
# goofy thing
eq_(t1.c.name.my_goofy_thing(), "hi")
# create proxy
s = select(t1.select().alias())
# proxy has goofy thing
eq_(s.subquery().c.name.my_goofy_thing(), "hi")
# compile works
self.assert_compile(
select(t1.select().alias()),
"SELECT anon_1.id-, anon_1.name- FROM "
"(SELECT foo.id- AS id, foo.name- AS name "
"FROM foo) AS anon_1",
)
def test_custom_subclass_proxy_typeerror(self):
from sqlalchemy.schema import Column
from sqlalchemy.sql import select
class MyColumn(Column):
def __init__(self, type_, **kw):
Column.__init__(self, type_, **kw)
id_ = MyColumn(Integer, primary_key=True)
id_.name = "id"
name = MyColumn(String)
name.name = "name"
t1 = Table("foo", MetaData(), id_, name)
assert_raises_message(
TypeError,
"Could not create a copy of this <class "
"'test.sql.test_metadata..*MyColumn'> "
"object. Ensure the class includes a _constructor()",
getattr,
select(t1.select().alias()).subquery(),
"c",
)
def test_custom_create(self):
@compiles(schema.CreateColumn)
def compile_(element, compiler, **kw):
column = element.element
if "special" not in column.info:
return compiler.visit_create_column(element, **kw)
text = "%s SPECIAL DIRECTIVE %s" % (
column.name,
compiler.type_compiler.process(column.type),
)
default = compiler.get_column_default_string(column)
if default is not None:
text += " DEFAULT " + default
if not column.nullable:
text += " NOT NULL"
if column.constraints:
text += " ".join(
compiler.process(const) for const in column.constraints
)
return text
t = Table(
"mytable",
MetaData(),
Column("x", Integer, info={"special": True}, primary_key=True),
Column("y", String(50)),
Column("z", String(20), info={"special": True}),
)
self.assert_compile(
schema.CreateTable(t),
"CREATE TABLE mytable (x SPECIAL DIRECTIVE INTEGER "
"NOT NULL, y VARCHAR(50), "
"z SPECIAL DIRECTIVE VARCHAR(20), PRIMARY KEY (x))",
)
deregister(schema.CreateColumn)
@testing.combinations(("index",), ("unique",), argnames="paramname")
@testing.combinations((True,), (False,), (None,), argnames="orig")
@testing.combinations((True,), (False,), (None,), argnames="merging")
def test_merge_index_unique(self, paramname, orig, merging):
"""test #11091"""
source = Column(**{paramname: merging})
target = Column(**{paramname: orig})
source._merge(target)
target_copy = target._copy()
for col in (
target,
target_copy,
):
result = getattr(col, paramname)
if orig is None:
is_(result, merging)
else:
is_(result, orig)
@testing.combinations(
("default", lambda ctx: 10),
("default", func.foo()),
("identity_gen", Identity()),
("identity_gen", Sequence("some_seq")),
("identity_gen", Computed("side * side")),
("onupdate", lambda ctx: 10),
("onupdate", func.foo()),
("server_onupdate", func.foo()),
("server_default", func.foo()),
("nullable", True),
("nullable", False),
("index", True),
("unique", True),
("type", BigInteger()),
("type", Enum("one", "two", "three", create_constraint=True)),
("doc", "some doc"),
("comment", "some comment"),
("system", True),
("autoincrement", True),
("info", {"foo": "bar"}),
argnames="paramname, value",
)
def test_merge_column(self, paramname, value):
args = []
params = {}
if paramname == "type" or isinstance(
value, (Computed, Sequence, Identity)
):
args.append(value)
else:
params[paramname] = value
source = Column(*args, **params)
target = Column()
source._merge(target)
target_copy = target._copy()
for col in (
target,
target_copy,
):
if isinstance(value, (Computed, Identity)):
default = col.server_default
assert isinstance(default, type(value))
is_(default.column, col)
elif isinstance(value, Sequence):
default = col.default
# TODO: sequence mutated in place
is_(default.column, target_copy)
assert isinstance(default, type(value))
elif paramname in (
"default",
"onupdate",
"server_default",
"server_onupdate",
):
default = getattr(col, paramname)
is_(default.arg, value)
# TODO: _copy() seems to note that it isn't copying
# server defaults or defaults outside of Computed, Identity,
# so here it's getting mutated in place. this is a bug
is_(default.column, target_copy)
elif paramname in ("info",):
eq_(col.info, value)
elif paramname == "type":
assert type(col.type) is type(value)
if isinstance(col.type, Enum):
col.name = "data"
t = Table("t", MetaData(), col)
assert CheckConstraint in [type(c) for c in t.constraints]
else:
is_(getattr(col, paramname), value)
@testing.combinations(True, False, argnames="specify_identity")
@testing.combinations(True, False, None, argnames="specify_nullable")
def test_merge_column_identity(
self,
specify_identity,
specify_nullable,
):
if specify_identity:
args = [Identity()]
else:
args = []
if specify_nullable is not None:
params = {"nullable": specify_nullable}
else:
params = {}
source = Column(*args, **params)
target = Column()
source._merge(target)
# test identity + _copy() for #8410
for col in (
target,
target._copy(),
):
if specify_nullable is True:
is_(col.nullable, True)
elif specify_identity:
is_(col.nullable, False)
elif specify_nullable is False:
is_(col.nullable, False)
else:
is_(col.nullable, True)
@testing.combinations(
("default", lambda ctx: 10, lambda ctx: 15),
("default", func.foo(), func.bar()),
("identity_gen", Identity(), Identity()),
("identity_gen", Sequence("some_seq"), Sequence("some_other_seq")),
("identity_gen", Computed("side * side"), Computed("top / top")),
("onupdate", lambda ctx: 10, lambda ctx: 15),
("onupdate", func.foo(), func.bar()),
("server_onupdate", func.foo(), func.bar()),
("server_default", func.foo(), func.bar()),
("nullable", True, False),
("nullable", False, True),
("type", BigInteger(), Numeric()),
argnames="paramname, value, override_value",
)
def test_dont_merge_column(
self,
paramname,
value,
override_value,
):
args = []
params = {}
override_args = []
override_params = {}
if paramname == "type" or isinstance(
value, (Computed, Sequence, Identity)
):
args.append(value)
override_args.append(override_value)
else:
params[paramname] = value
override_params[paramname] = override_value
source = Column(*args, **params)
target = Column(*override_args, **override_params)
source._merge(target)
if isinstance(value, Sequence):
default = target.default
assert default is override_value
elif isinstance(value, (Computed, Identity)):
default = target.server_default
assert default is override_value
elif paramname in (
"default",
"onupdate",
"server_default",
"server_onupdate",
):
default = getattr(target, paramname)
is_(default.arg, override_value)
is_(default.column, target)
elif paramname == "type":
assert type(target.type) is type(override_value)
else:
is_(getattr(target, paramname), override_value)
| ColumnDefinitionTest |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 1080,
"end": 2060
} | class ____:
req_meta: dict[str, Any] = {}
resp_headers: dict[str, str] = {}
settings: dict[str, Any] = {}
scenarii: list[tuple[str, str, bytes | None]] = [
("http://scrapytest.org", "http://scrapytest.org/", b"http://scrapytest.org"),
]
@pytest.fixture
def mw(self) -> RefererMiddleware:
settings = Settings(self.settings)
return RefererMiddleware(settings)
def get_request(self, target: str) -> Request:
return Request(target, meta=self.req_meta)
def get_response(self, origin: str) -> Response:
return Response(origin, headers=self.resp_headers)
def test(self, mw: RefererMiddleware) -> None:
for origin, target, referrer in self.scenarii:
response = self.get_response(origin)
request = self.get_request(target)
out = list(mw.process_spider_output(response, [request]))
assert out[0].headers.get("Referer") == referrer
| TestRefererMiddleware |
python | pytorch__pytorch | test/test_autocast.py | {
"start": 10910,
"end": 13594
} | class ____(TestCase):
def test_cast_cache_is_global(self):
class CustomLinear(torch.autograd.Function):
@staticmethod
def forward(ctx, x, w_t):
ctx.save_for_backward(x, w_t)
return torch.nn.functional.linear(x, w_t)
@staticmethod
def backward(ctx, grad_output):
x, w_t = ctx.saved_tensors
with torch.autocast(device_type="mps"):
dL_dX = torch.matmul(grad_output, w_t)
dL_dW = torch.matmul(x.transpose(0, 1), grad_output).transpose(0, 1)
return dL_dX, dL_dW
data = torch.randn(2, 3).to("mps")
weight = torch.nn.Parameter(torch.randn(4, 3).to("mps"))
weight_dtype_cast_counter = 0
class WeightDTypeCastCounterMode(TorchDispatchMode):
def __torch_dispatch__(self, func, types, args=(), kwargs=None):
if (
func is torch.ops.aten._to_copy.default
and args[0] is weight
and kwargs["dtype"] is torch.float16
):
nonlocal weight_dtype_cast_counter
weight_dtype_cast_counter += 1
return func(*args, **kwargs)
def __enter__(self):
# self.old_clear_cache = torch.clear_autocast_cache
# torch.clear_autocast_cache = lambda: None
return super().__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
# torch.clear_autocast_cache = self.old_clear_cache
return super().__exit__(exc_type, exc_val, exc_tb)
with WeightDTypeCastCounterMode():
with torch.autocast(device_type="mps"):
output = CustomLinear.apply(data, weight)
s = output.sum()
s.backward()
self.assertEqual(weight_dtype_cast_counter, 2)
def test_mps_autocast_error_message(self):
with self.assertWarnsRegex(
UserWarning,
"MPS Autocast only supports dtypes of torch.bfloat16, torch.float16 currently.",
):
with torch.autocast(device_type="mps", dtype=torch.float32):
_ = torch.ones(10)
# torch.bfloat16 is only supported on macOS 14 and above.
@expectedFailureMPSPre14
def test_mps_autocast_bfloat16_supported(self):
with torch.amp.autocast(device_type="mps", dtype=torch.bfloat16):
x = torch.randn(2, 3, device="mps")
y = torch.randn(3, 3, device="mps")
result = torch.mm(x, y)
self.assertEqual(result.dtype, torch.bfloat16)
| TestAutocastMPS |
python | django__django | tests/file_storage/test_generate_filename.py | {
"start": 2212,
"end": 2329
} | class ____(StorageGenerateFilenameTests):
storage_class = FileSystemStorage
| FileSystemStorageGenerateFilenameTests |
python | pennersr__django-allauth | allauth/socialaccount/providers/lichess/provider.py | {
"start": 534,
"end": 1597
} | class ____(OAuth2Provider):
id = "lichess"
name = "Lichess"
account_class = LichessAccount
oauth2_adapter_class = LichessOAuth2Adapter
pkce_enabled_default = True
def extract_uid(self, data):
return str(data["id"])
def extract_common_fields(self, data):
first_name = data.get("profile", {}).get("firstName")
last_name = data.get("profile", {}).get("lastName")
return dict(
username=data.get("username"),
email=data.get("email"),
first_name=first_name,
last_name=last_name,
)
def extract_email_addresses(self, data):
ret = []
email = data.get("email")
if email:
ret.append(
EmailAddress(
email=email,
primary=True,
)
)
return ret
def get_default_scope(self):
ret = []
if QUERY_EMAIL:
ret.append("email:read")
return ret
provider_classes = [LichessProvider]
| LichessProvider |
python | numpy__numpy | numpy/distutils/fcompiler/nag.py | {
"start": 1517,
"end": 2777
} | class ____(BaseNAGFCompiler):
compiler_type = 'nagfor'
description = 'NAG Fortran Compiler'
executables = {
'version_cmd' : ["nagfor", "-V"],
'compiler_f77' : ["nagfor", "-fixed"],
'compiler_fix' : ["nagfor", "-fixed"],
'compiler_f90' : ["nagfor"],
'linker_so' : ["nagfor"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"]
}
def get_flags_linker_so(self):
if sys.platform == 'darwin':
return ['-unsharedrts',
'-Wl,-bundle,-flat_namespace,-undefined,suppress']
return BaseNAGFCompiler.get_flags_linker_so(self)
def get_flags_debug(self):
version = self.get_version()
if version and version > '6.1':
return ['-g', '-u', '-nan', '-C=all', '-thread_safe',
'-kind=unique', '-Warn=allocation', '-Warn=subnormal']
else:
return ['-g', '-nan', '-C=all', '-u', '-thread_safe']
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
from numpy.distutils import customized_fcompiler
compiler = customized_fcompiler(compiler='nagfor')
print(compiler.get_version())
print(compiler.get_flags_debug())
| NAGFORCompiler |
python | run-llama__llama_index | llama-index-core/llama_index/core/graph_stores/types.py | {
"start": 919,
"end": 1465
} | class ____(BaseModel):
"""An entity in a graph."""
label: str = Field(default="node", description="The label of the node.")
embedding: Optional[List[float]] = Field(
default=None, description="The embeddings of the node."
)
properties: Dict[str, Any] = Field(default_factory=dict)
@abstractmethod
def __str__(self) -> str:
"""Return the string representation of the node."""
...
@property
@abstractmethod
def id(self) -> str:
"""Get the node id."""
...
| LabelledNode |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/endpoints-frameworks-v2/iata/main.py | {
"start": 1480,
"end": 3663
} | class ____(remote.Service):
@endpoints.method(
IATA_RESOURCE,
Airport,
path="airport/{iata}",
http_method="GET",
name="get_airport",
)
def get_airport(self, request):
if request.iata not in AIRPORTS:
raise endpoints.NotFoundException()
return Airport(iata=request.iata, name=AIRPORTS[request.iata])
@endpoints.method(
message_types.VoidMessage,
AirportList,
path="airports",
http_method="GET",
name="list_airports",
)
def list_airports(self, request):
codes = AIRPORTS.keys()
codes.sort()
return AirportList(
airports=[Airport(iata=iata, name=AIRPORTS[iata]) for iata in codes]
)
@endpoints.method(
IATA_RESOURCE,
message_types.VoidMessage,
path="airport/{iata}",
http_method="DELETE",
name="delete_airport",
api_key_required=True,
)
def delete_airport(self, request):
if request.iata not in AIRPORTS:
raise endpoints.NotFoundException()
del AIRPORTS[request.iata]
return message_types.VoidMessage()
@endpoints.method(
Airport,
Airport,
path="airport",
http_method="POST",
name="create_airport",
api_key_required=True,
)
def create_airport(self, request):
if request.iata in AIRPORTS:
raise endpoints.BadRequestException()
AIRPORTS[request.iata] = request.name
return Airport(iata=request.iata, name=AIRPORTS[request.iata])
@endpoints.method(
IATA_AIRPORT_RESOURCE,
Airport,
path="airport/{iata}",
http_method="POST",
name="update_airport",
api_key_required=True,
)
def update_airport(self, request):
if request.iata not in AIRPORTS:
raise endpoints.BadRequestException()
AIRPORTS[request.iata] = request.name
return Airport(iata=request.iata, name=AIRPORTS[request.iata])
# [END endpoints_iata_api]
# [START endpoints_iata_api_server]
api = endpoints.api_server([IataApi])
# [END endpoints_iata_api_server]
| IataApi |
python | pypa__virtualenv | src/virtualenv/seed/embed/pip_invoke.py | {
"start": 342,
"end": 2237
} | class ____(BaseEmbed):
def __init__(self, options) -> None:
super().__init__(options)
def run(self, creator):
if not self.enabled:
return
for_py_version = creator.interpreter.version_release_str
with self.get_pip_install_cmd(creator.exe, for_py_version) as cmd:
env = pip_wheel_env_run(self.extra_search_dir, self.app_data, self.env)
self._execute(cmd, env)
@staticmethod
def _execute(cmd, env):
LOGGER.debug("pip seed by running: %s", LogCmd(cmd, env))
process = Popen(cmd, env=env)
process.communicate()
if process.returncode != 0:
msg = f"failed seed with code {process.returncode}"
raise RuntimeError(msg)
return process
@contextmanager
def get_pip_install_cmd(self, exe, for_py_version):
cmd = [str(exe), "-m", "pip", "-q", "install", "--only-binary", ":all:", "--disable-pip-version-check"]
if not self.download:
cmd.append("--no-index")
folders = set()
for dist, version in self.distribution_to_versions().items():
wheel = get_wheel(
distribution=dist,
version=version,
for_py_version=for_py_version,
search_dirs=self.extra_search_dir,
download=False,
app_data=self.app_data,
do_periodic_update=self.periodic_update,
env=self.env,
)
if wheel is None:
msg = f"could not get wheel for distribution {dist}"
raise RuntimeError(msg)
folders.add(str(wheel.path.parent))
cmd.append(Version.as_pip_req(dist, wheel.version))
for folder in sorted(folders):
cmd.extend(["--find-links", str(folder)])
yield cmd
__all__ = [
"PipInvoke",
]
| PipInvoke |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_overlap.py | {
"start": 2889,
"end": 9279
} | class ____(FSDPTest):
@property
def world_size(self):
return 1
def _dist_train(self):
rank = self.rank
world_size = self.world_size
# Save the original torch.distributed.all_gather_into_tensor function since we will
# patch it to include an artificial delay.
orig_all_gather = torch.distributed.all_gather_into_tensor
def run(compute_cycles, all_gather_cycles):
has_params = all_gather_cycles > 0
model = _create_model(compute_cycles, has_params)
# Get the input and sets the input's requires_grad to True because
# we have a fake compute in the forward pass.
batch = torch.rand(1).to(device_type)
batch.requires_grad = True
# Run one dummy iteration to trigger the execution order validation
# all-gathers
out = model(batch)
out.backward()
model.zero_grad(set_to_none=True)
# We run 20 iterations but only collect timing data from the minimal 10
# data points because nondeterministic system events can disturb the timing.
cpu_iter = Min10()
cpu_wait = Min10()
gpu_compute = Min10()
gpu_total = Min10()
for _ in range(20):
# Get two events for measuring the overall time.
e1 = Event(enable_timing=True)
e2 = Event(enable_timing=True)
cpu_start = time.process_time()
all_gather_called = False
def _delayed_all_gather(*args, **kwargs):
nonlocal all_gather_called
all_gather_called = True
if torch.cuda.is_available():
torch.cuda._sleep(all_gather_cycles)
assert orig_all_gather
return orig_all_gather(*args, **kwargs)
# forward pass
#
# Even though both e1 & e2 are on the compute stream, since
# compute depends on all_gather, e2-e1 includes all_gather time.
e1.record()
with patch(
"torch.distributed.all_gather_into_tensor", _delayed_all_gather
):
out = model(batch)
if has_params and world_size > 1:
self.assertTrue(all_gather_called)
else:
self.assertFalse(all_gather_called)
e2.record()
# backward pass
out.backward()
model.zero_grad(set_to_none=True)
cpu_iter_time = time.process_time() - cpu_start
# wait for gpu
out.item()
cpu_wait_for_gpu_time = time.process_time() - cpu_start - cpu_iter_time
# get sum of the compute time
times = []
for mod in model.modules():
if not isinstance(mod, Layer):
continue
times.append(mod.get_time())
# get gpu compute + all_gather time
overall_gpu_time = e1.elapsed_time(e2)
cpu_iter.add(cpu_iter_time)
cpu_wait.add(cpu_wait_for_gpu_time)
gpu_compute.add(sum(times))
gpu_total.add(overall_gpu_time)
del model
return {
"cpu_iter": cpu_iter.avg(),
"cpu_wait": cpu_wait.avg(),
"gpu_compute": gpu_compute.avg(),
"gpu_total": gpu_total.avg(),
}
sleep_cycles = int(100 * get_cycles_per_ms())
e1 = run(0, 0) # no compute, no all-gather
e2 = run(0, sleep_cycles) # no compute, only all-gather
e3 = run(sleep_cycles, 0) # only compute, no all-gather
e4 = run(sleep_cycles, sleep_cycles) # both compute and all-gather
debug_string = f"\nrank{rank}:\n e1: {e1}\n e2: {e2}\n e3: {e3}\n e4: {e4}"
print(debug_string)
# Check the cpu/gpu timing. CPU should run ahead of GPU. Therefore, cpu-gpu
# wait should be long, except when there is no real work on GPU.
#
# If the assertions fail below, we likely have a cpu-gpu wait in the forward/backward pass.
# e4["cpu_iter"] may not be short as cpu may take some time to queue both compute and all-gather.
short = [
e1["cpu_iter"],
e2["cpu_iter"],
e3["cpu_iter"],
e1["cpu_wait"],
]
long = [e3["cpu_wait"], e4["cpu_wait"]]
if world_size == 1:
short.append(e2["cpu_wait"]) # all gather should not be happening.
else:
long.append(
e2["cpu_wait"]
) # all gather should happen and prolong the cpu-gpu wait.
for s in short:
for l in long:
# 10X longer is a safe margin, since the GPU work timing is around 100X more
# of that of the CPU.
self.assertTrue(s * 10 < l)
# Check the GPU timing.
short = [e1["gpu_compute"], e1["gpu_total"], e2["gpu_compute"]]
long = [e3["gpu_compute"], e3["gpu_total"], e4["gpu_compute"], e4["gpu_total"]]
if world_size == 1:
short.append(e2["gpu_total"]) # all gather should not be happening.
else:
long.append(
e2["gpu_total"]
) # all gather should happen and prolong the cpu-gpu wait.
for s in short:
for l in long:
# 10X longer is a safe margin, since the time is around 100X longer
# when there is work on GPU vs. no work.
self.assertTrue(s * 10 < l)
# Check the GPU overlapping when there is all-gather.
if world_size > 1:
compute_only = e3["gpu_compute"]
all_gather_only = e2["gpu_total"]
both = e4["gpu_total"]
self.assertTrue(compute_only + all_gather_only > 1.1 * both)
@unittest.skipIf(TEST_HPU, "HPU doesn't has HW sleep API support, skipping")
@xfailIf(TEST_XPU) # https://github.com/intel/torch-xpu-ops/issues/1504
@skip_if_lt_x_gpu(2)
def test_forward_overlap(self):
self._dist_train()
| TestForwardOverlapWorldSizeOne |
python | scipy__scipy | scipy/stats/_distribution_infrastructure.py | {
"start": 184695,
"end": 190751
} | class ____(TransformedDistribution):
"""Truncated distribution."""
# TODO:
# - consider avoiding catastropic cancellation by using appropriate tail
# - if the mode of `_dist` is within the support, it's still the mode
# - rejection sampling might be more efficient than inverse transform
_lb_domain = _RealInterval(endpoints=(-inf, 'ub'), inclusive=(True, False))
_lb_param = _RealParameter('lb', symbol=r'b_l',
domain=_lb_domain, typical=(0.1, 0.2))
_ub_domain = _RealInterval(endpoints=('lb', inf), inclusive=(False, True))
_ub_param = _RealParameter('ub', symbol=r'b_u',
domain=_ub_domain, typical=(0.8, 0.9))
_parameterizations = [_Parameterization(_lb_param, _ub_param),
_Parameterization(_lb_param),
_Parameterization(_ub_param)]
def __init__(self, X, /, *args, lb=-np.inf, ub=np.inf, **kwargs):
return super().__init__(X, *args, lb=lb, ub=ub, **kwargs)
def _process_parameters(self, lb=None, ub=None, **params):
lb = lb if lb is not None else np.full_like(lb, -np.inf)[()]
ub = ub if ub is not None else np.full_like(ub, np.inf)[()]
parameters = self._dist._process_parameters(**params)
a, b = self._support(lb=lb, ub=ub, **parameters)
logmass = self._dist._logcdf2_dispatch(a, b, **parameters)
parameters.update(dict(lb=lb, ub=ub, _a=a, _b=b, logmass=logmass))
return parameters
def _support(self, lb, ub, **params):
a, b = self._dist._support(**params)
return np.maximum(a, lb), np.minimum(b, ub)
def _overrides(self, method_name):
return False
def _logpdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params):
logpdf = self._dist._logpdf_dispatch(x, *args, **params)
return logpdf - logmass
def _logcdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params):
logcdf = self._dist._logcdf2_dispatch(_a, x, *args, **params)
# of course, if this result is small we could compute with the other tail
return logcdf - logmass
def _logccdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params):
logccdf = self._dist._logcdf2_dispatch(x, _b, *args, **params)
return logccdf - logmass
def _logcdf2_dispatch(self, x, y, *args, lb, ub, _a, _b, logmass, **params):
logcdf2 = self._dist._logcdf2_dispatch(x, y, *args, **params)
return logcdf2 - logmass
def _ilogcdf_dispatch(self, logp, *args, lb, ub, _a, _b, logmass, **params):
log_Fa = self._dist._logcdf_dispatch(_a, *args, **params)
logp_adjusted = np.logaddexp(log_Fa, logp + logmass)
return self._dist._ilogcdf_dispatch(logp_adjusted, *args, **params)
def _ilogccdf_dispatch(self, logp, *args, lb, ub, _a, _b, logmass, **params):
log_cFb = self._dist._logccdf_dispatch(_b, *args, **params)
logp_adjusted = np.logaddexp(log_cFb, logp + logmass)
return self._dist._ilogccdf_dispatch(logp_adjusted, *args, **params)
def _icdf_dispatch(self, p, *args, lb, ub, _a, _b, logmass, **params):
Fa = self._dist._cdf_dispatch(_a, *args, **params)
p_adjusted = Fa + p*np.exp(logmass)
return self._dist._icdf_dispatch(p_adjusted, *args, **params)
def _iccdf_dispatch(self, p, *args, lb, ub, _a, _b, logmass, **params):
cFb = self._dist._ccdf_dispatch(_b, *args, **params)
p_adjusted = cFb + p*np.exp(logmass)
return self._dist._iccdf_dispatch(p_adjusted, *args, **params)
def __repr__(self):
with np.printoptions(threshold=10):
return (f"truncate({repr(self._dist)}, "
f"lb={repr(self.lb)}, ub={repr(self.ub)})")
def __str__(self):
with np.printoptions(threshold=10):
return (f"truncate({str(self._dist)}, "
f"lb={str(self.lb)}, ub={str(self.ub)})")
@xp_capabilities(np_only=True)
def truncate(X, lb=-np.inf, ub=np.inf):
"""Truncate the support of a random variable.
Given a random variable `X`, `truncate` returns a random variable with
support truncated to the interval between `lb` and `ub`. The underlying
probability density function is normalized accordingly.
Parameters
----------
X : `ContinuousDistribution`
The random variable to be truncated.
lb, ub : float array-like
The lower and upper truncation points, respectively. Must be
broadcastable with one another and the shape of `X`.
Returns
-------
X : `ContinuousDistribution`
The truncated random variable.
References
----------
.. [1] "Truncated Distribution". *Wikipedia*.
https://en.wikipedia.org/wiki/Truncated_distribution
Examples
--------
Compare against `scipy.stats.truncnorm`, which truncates a standard normal,
*then* shifts and scales it.
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy import stats
>>> loc, scale, lb, ub = 1, 2, -2, 2
>>> X = stats.truncnorm(lb, ub, loc, scale)
>>> Y = scale * stats.truncate(stats.Normal(), lb, ub) + loc
>>> x = np.linspace(-3, 5, 300)
>>> plt.plot(x, X.pdf(x), '-', label='X')
>>> plt.plot(x, Y.pdf(x), '--', label='Y')
>>> plt.xlabel('x')
>>> plt.ylabel('PDF')
>>> plt.title('Truncated, then Shifted/Scaled Normal')
>>> plt.legend()
>>> plt.show()
However, suppose we wish to shift and scale a normal random variable,
then truncate its support to given values. This is straightforward with
`truncate`.
>>> Z = stats.truncate(scale * stats.Normal() + loc, lb, ub)
>>> Z.plot()
>>> plt.show()
Furthermore, `truncate` can be applied to any random variable:
>>> Rayleigh = stats.make_distribution(stats.rayleigh)
>>> W = stats.truncate(Rayleigh(), lb=0.5, ub=3)
>>> W.plot()
>>> plt.show()
"""
return TruncatedDistribution(X, lb=lb, ub=ub)
| TruncatedDistribution |
python | huggingface__transformers | src/transformers/models/switch_transformers/modeling_switch_transformers.py | {
"start": 42570,
"end": 48531
} | class ____(SwitchTransformersPreTrainedModel):
_tied_weights_keys = {
"encoder.embed_tokens.weight": "shared.weight",
"decoder.embed_tokens.weight": "shared.weight",
}
def __init__(self, config: SwitchTransformersConfig):
super().__init__(config)
self.shared = nn.Embedding(config.vocab_size, config.d_model)
encoder_config = copy.deepcopy(config)
encoder_config.is_decoder = False
encoder_config.use_cache = False
encoder_config.tie_encoder_decoder = False
self.encoder = SwitchTransformersStack(encoder_config)
decoder_config = copy.deepcopy(config)
decoder_config.is_decoder = True
decoder_config.tie_encoder_decoder = False
self.decoder = SwitchTransformersStack(decoder_config)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.shared
def set_input_embeddings(self, new_embeddings):
self.shared = new_embeddings
self.encoder.set_input_embeddings(new_embeddings)
self.decoder.set_input_embeddings(new_embeddings)
@auto_docstring
@can_return_tuple
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.BoolTensor] = None,
encoder_outputs: Optional[tuple[tuple[torch.FloatTensor]]] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.Tensor] = None,
decoder_inputs_embeds: Optional[torch.Tensor] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple[torch.FloatTensor], Seq2SeqMoEModelOutput]:
if encoder_outputs is None:
encoder_outputs = self.encoder(
input_ids=input_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs
)
hidden_states = encoder_outputs[0]
decoder_outputs = self.decoder(
input_ids=decoder_input_ids,
attention_mask=decoder_attention_mask,
inputs_embeds=decoder_inputs_embeds,
past_key_values=past_key_values,
encoder_hidden_states=hidden_states,
encoder_attention_mask=attention_mask,
cache_position=cache_position,
**kwargs,
)
return Seq2SeqMoEModelOutput(
last_hidden_state=decoder_outputs.last_hidden_state,
past_key_values=decoder_outputs.past_key_values,
decoder_hidden_states=decoder_outputs.hidden_states,
decoder_attentions=decoder_outputs.attentions,
cross_attentions=decoder_outputs.cross_attentions,
decoder_router_logits=decoder_outputs.router_logits,
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
encoder_hidden_states=encoder_outputs.hidden_states,
encoder_attentions=encoder_outputs.attentions,
encoder_router_logits=encoder_outputs.router_logits,
)
####################################################
# This dict contains ids and associated url
# for the pretrained weights provided with the models
####################################################
def router_z_loss_func(router_logits: torch.Tensor) -> float:
r"""
Compute the router z-loss implemented in PyTorch.
The router z-loss was introduced in [Designing Effective Sparse Expert Models](https://huggingface.co/papers/2202.08906).
It encourages router logits to remain small in an effort to improve stability.
Args:
router_logits (`float`):
Input logits of shape [batch_size, sequence_length, num_experts]
Returns:
Scalar router z-loss.
"""
num_groups, tokens_per_group, _ = router_logits.shape
log_z = torch.logsumexp(router_logits, dim=-1)
z_loss = log_z**2
return torch.sum(z_loss) / (num_groups * tokens_per_group)
def load_balancing_loss_func(router_probs: torch.Tensor, expert_indices: torch.Tensor) -> float:
r"""
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
experts is too unbalanced.
Args:
router_probs (`torch.Tensor`):
Probability assigned to each expert per token. Shape: [batch_size, sequence_length, num_experts].
expert_indices (`torch.Tensor`):
Indices tensor of shape [batch_size, sequence_length] identifying the selected expert for a given token.
Returns:
The auxiliary loss.
"""
num_experts = router_probs.shape[-1]
# cast the expert indices to int64, otherwise one-hot encoding will fail
if expert_indices.dtype != torch.int64:
expert_indices = expert_indices.to(torch.int64)
if len(expert_indices.shape) == 2:
expert_indices = expert_indices.unsqueeze(2)
expert_mask = torch.nn.functional.one_hot(expert_indices, num_experts)
# For a given token, determine if it was routed to a given expert.
expert_mask = torch.max(expert_mask, axis=-2).values
# cast to float32 otherwise mean will fail
expert_mask = expert_mask.to(torch.float32)
tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
router_prob_per_group_and_expert = torch.mean(router_probs, axis=-2)
return torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert) * (num_experts**2)
@auto_docstring(
custom_intro="""
SWITCH_TRANSFORMERS Model with a `language modeling` head on top.
"""
)
| SwitchTransformersModel |
python | readthedocs__readthedocs.org | readthedocs/core/migrations/0006_remove_userprofile_allow_email.py | {
"start": 121,
"end": 405
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("core", "0005_migrate-old-passwords"),
]
operations = [
migrations.RemoveField(
model_name="userprofile",
name="allow_email",
),
]
| Migration |
python | facebook__pyre-check | scripts/callgraph_utilities.py | {
"start": 5321,
"end": 6057
} | class ____(InputFormat):
def __init__(self) -> None:
self.call_graph: Dict[str, Set[str]] = defaultdict(set)
def extract_callee(self, callee: JSON) -> str:
if not isinstance(callee, str):
raise ValueError(
f"Expected value for individual callee to be a string, got {type(callee)}: {callee}"
)
return callee
def extract_caller(self, qualifier: str) -> str:
return qualifier
def union_call_graph(self, call_graph: Dict[str, Set[str]]) -> None:
if self.call_graph:
for k, v in call_graph.items():
self.call_graph[k] |= v
else:
self.call_graph = defaultdict(set, call_graph)
| UnionCallGraphFormat |
python | pytorch__pytorch | torch/distributions/beta.py | {
"start": 372,
"end": 4050
} | class ____(ExponentialFamily):
r"""
Beta distribution parameterized by :attr:`concentration1` and :attr:`concentration0`.
Example::
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> m = Beta(torch.tensor([0.5]), torch.tensor([0.5]))
>>> m.sample() # Beta distributed with concentration concentration1 and concentration0
tensor([ 0.1046])
Args:
concentration1 (float or Tensor): 1st concentration parameter of the distribution
(often referred to as alpha)
concentration0 (float or Tensor): 2nd concentration parameter of the distribution
(often referred to as beta)
"""
# pyrefly: ignore [bad-override]
arg_constraints = {
"concentration1": constraints.positive,
"concentration0": constraints.positive,
}
support = constraints.unit_interval
has_rsample = True
def __init__(
self,
concentration1: Union[Tensor, float],
concentration0: Union[Tensor, float],
validate_args: Optional[bool] = None,
) -> None:
if isinstance(concentration1, _Number) and isinstance(concentration0, _Number):
concentration1_concentration0 = torch.tensor(
[float(concentration1), float(concentration0)]
)
else:
concentration1, concentration0 = broadcast_all(
concentration1, concentration0
)
concentration1_concentration0 = torch.stack(
[concentration1, concentration0], -1
)
self._dirichlet = Dirichlet(
concentration1_concentration0, validate_args=validate_args
)
super().__init__(self._dirichlet._batch_shape, validate_args=validate_args)
def expand(self, batch_shape, _instance=None):
new = self._get_checked_instance(Beta, _instance)
batch_shape = torch.Size(batch_shape)
new._dirichlet = self._dirichlet.expand(batch_shape)
super(Beta, new).__init__(batch_shape, validate_args=False)
new._validate_args = self._validate_args
return new
@property
def mean(self) -> Tensor:
return self.concentration1 / (self.concentration1 + self.concentration0)
@property
def mode(self) -> Tensor:
return self._dirichlet.mode[..., 0]
@property
def variance(self) -> Tensor:
total = self.concentration1 + self.concentration0
return self.concentration1 * self.concentration0 / (total.pow(2) * (total + 1))
def rsample(self, sample_shape: _size = ()) -> Tensor:
return self._dirichlet.rsample(sample_shape).select(-1, 0)
def log_prob(self, value):
if self._validate_args:
self._validate_sample(value)
heads_tails = torch.stack([value, 1.0 - value], -1)
return self._dirichlet.log_prob(heads_tails)
def entropy(self):
return self._dirichlet.entropy()
@property
def concentration1(self) -> Tensor:
result = self._dirichlet.concentration[..., 0]
if isinstance(result, _Number):
return torch.tensor([result])
else:
return result
@property
def concentration0(self) -> Tensor:
result = self._dirichlet.concentration[..., 1]
if isinstance(result, _Number):
return torch.tensor([result])
else:
return result
@property
def _natural_params(self) -> tuple[Tensor, Tensor]:
return (self.concentration1, self.concentration0)
# pyrefly: ignore [bad-override]
def _log_normalizer(self, x, y):
return torch.lgamma(x) + torch.lgamma(y) - torch.lgamma(x + y)
| Beta |
python | explosion__spaCy | spacy/lang/tr/__init__.py | {
"start": 232,
"end": 450
} | class ____(BaseDefaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
lex_attr_getters = LEX_ATTRS
stop_words = STOP_WORDS
token_match = TOKEN_MATCH
syntax_iterators = SYNTAX_ITERATORS
| TurkishDefaults |
python | doocs__leetcode | solution/2800-2899/2824.Count Pairs Whose Sum is Less than Target/Solution.py | {
"start": 0,
"end": 244
} | class ____:
def countPairs(self, nums: List[int], target: int) -> int:
nums.sort()
ans = 0
for j, x in enumerate(nums):
i = bisect_left(nums, target - x, hi=j)
ans += i
return ans
| Solution |
python | django__django | tests/mail/test_deprecated.py | {
"start": 4008,
"end": 4651
} | class ____(SimpleTestCase):
def test_bad_header_error(self):
"""
Existing code that catches deprecated BadHeaderError should be
compatible with modern email (which raises ValueError instead).
"""
from django.core.mail import BadHeaderError
with self.assertRaises(BadHeaderError):
EmailMessage(subject="Bad\r\nHeader").message()
def test_attachments_mimebase_in_constructor(self):
txt = MIMEText("content1")
msg = EmailMessage(attachments=[txt])
payload = msg.message().get_payload()
self.assertEqual(payload[0], txt)
| DeprecatedCompatibilityTests |
python | prabhupant__python-ds | data_structures/linked_list/reverse.py | {
"start": 0,
"end": 528
} | class ____():
def __init__(self, val):
self.val = val
self.next = None
def reverse(head):
if not head:
return None
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
curr = head
while curr:
print(curr.val)
curr = curr.next
new_head = reverse(head)
curr = new_head
while curr:
print(curr.val)
curr = curr.next
| Node |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 477662,
"end": 484758
} | class ____(Response):
"""
Response of tasks.reset endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
:param deleted_indices: List of deleted ES indices that were removed as part of
the reset process
:type deleted_indices: Sequence[str]
:param dequeued: Response from queues.remove_task
:type dequeued: dict
:param frames: Response from frames.rollback
:type frames: dict
:param events: Response from events.delete_for_task
:type events: dict
:param deleted_models: Number of output models deleted by the reset
:type deleted_models: int
:param urls: The urls of the files that were uploaded by this task. Returned if
the 'return_file_urls' was set to True
:type urls: TaskUrls
"""
_service = "tasks"
_action = "reset"
_version = "2.23"
_schema = {
"definitions": {
"task_urls": {
"properties": {
"artifact_urls": {
"items": {"type": "string"},
"type": ["array", "null"],
},
"event_urls": {
"items": {"type": "string"},
"type": ["array", "null"],
},
"model_urls": {
"items": {"type": "string"},
"type": ["array", "null"],
},
},
"type": "object",
}
},
"properties": {
"deleted_indices": {
"description": "List of deleted ES indices that were removed as part of the reset process",
"items": {"type": "string"},
"type": ["array", "null"],
},
"deleted_models": {
"description": "Number of output models deleted by the reset",
"type": ["integer", "null"],
},
"dequeued": {
"additionalProperties": True,
"description": "Response from queues.remove_task",
"type": ["object", "null"],
},
"events": {
"additionalProperties": True,
"description": "Response from events.delete_for_task",
"type": ["object", "null"],
},
"fields": {
"additionalProperties": True,
"description": "Updated fields names and values",
"type": ["object", "null"],
},
"frames": {
"additionalProperties": True,
"description": "Response from frames.rollback",
"type": ["object", "null"],
},
"updated": {
"description": "Number of tasks updated (0 or 1)",
"enum": [0, 1],
"type": ["integer", "null"],
},
"urls": {
"description": (
"The urls of the files that were uploaded by this task. Returned if the 'return_file_urls' was set"
" to True"
),
"oneOf": [{"$ref": "#/definitions/task_urls"}, {"type": "null"}],
},
},
"type": "object",
}
def __init__(
self,
updated=None,
fields=None,
deleted_indices=None,
dequeued=None,
frames=None,
events=None,
deleted_models=None,
urls=None,
**kwargs
):
super(ResetResponse, self).__init__(**kwargs)
self.updated = updated
self.fields = fields
self.deleted_indices = deleted_indices
self.dequeued = dequeued
self.frames = frames
self.events = events
self.deleted_models = deleted_models
self.urls = urls
@schema_property("updated")
def updated(self):
return self._property_updated
@updated.setter
def updated(self, value):
if value is None:
self._property_updated = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "updated", six.integer_types)
self._property_updated = value
@schema_property("fields")
def fields(self):
return self._property_fields
@fields.setter
def fields(self, value):
if value is None:
self._property_fields = None
return
self.assert_isinstance(value, "fields", (dict,))
self._property_fields = value
@schema_property("deleted_indices")
def deleted_indices(self):
return self._property_deleted_indices
@deleted_indices.setter
def deleted_indices(self, value):
if value is None:
self._property_deleted_indices = None
return
self.assert_isinstance(value, "deleted_indices", (list, tuple))
self.assert_isinstance(
value, "deleted_indices", six.string_types, is_array=True
)
self._property_deleted_indices = value
@schema_property("dequeued")
def dequeued(self):
return self._property_dequeued
@dequeued.setter
def dequeued(self, value):
if value is None:
self._property_dequeued = None
return
self.assert_isinstance(value, "dequeued", (dict,))
self._property_dequeued = value
@schema_property("frames")
def frames(self):
return self._property_frames
@frames.setter
def frames(self, value):
if value is None:
self._property_frames = None
return
self.assert_isinstance(value, "frames", (dict,))
self._property_frames = value
@schema_property("events")
def events(self):
return self._property_events
@events.setter
def events(self, value):
if value is None:
self._property_events = None
return
self.assert_isinstance(value, "events", (dict,))
self._property_events = value
@schema_property("deleted_models")
def deleted_models(self):
return self._property_deleted_models
@deleted_models.setter
def deleted_models(self, value):
if value is None:
self._property_deleted_models = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "deleted_models", six.integer_types)
self._property_deleted_models = value
@schema_property("urls")
def urls(self):
return self._property_urls
@urls.setter
def urls(self, value):
if value is None:
self._property_urls = None
return
if isinstance(value, dict):
value = TaskUrls.from_dict(value)
else:
self.assert_isinstance(value, "urls", TaskUrls)
self._property_urls = value
| ResetResponse |
python | charliermarsh__ruff | crates/ty_python_semantic/mdtest.py | {
"start": 785,
"end": 9757
} | class ____:
mdtest_executable: Path | None
console: Console
filters: list[str]
def __init__(self, filters: list[str] | None = None) -> None:
self.mdtest_executable = None
self.console = Console()
self.filters = [
f.removesuffix(".md").replace("/", "_").replace("-", "_")
for f in (filters or [])
]
def _run_cargo_test(self, *, message_format: Literal["human", "json"]) -> str:
return subprocess.check_output(
[
"cargo",
"test",
"--package",
CRATE_NAME,
"--no-run",
"--color=always",
"--test=mdtest",
"--message-format",
message_format,
],
cwd=CRATE_ROOT,
env=dict(os.environ, CLI_COLOR="1"),
stderr=subprocess.STDOUT,
text=True,
)
def _recompile_tests(
self, status_message: str, *, message_on_success: bool = True
) -> bool:
with self.console.status(status_message):
# Run it with 'human' format in case there are errors:
try:
self._run_cargo_test(message_format="human")
except subprocess.CalledProcessError as e:
print(e.output)
return False
# Run it again with 'json' format to find the mdtest executable:
try:
json_output = self._run_cargo_test(message_format="json")
except subprocess.CalledProcessError as _:
# `cargo test` can still fail if something changed in between the two runs.
# Here we don't have a human-readable output, so just show a generic message:
self.console.print("[red]Error[/red]: Failed to compile tests")
return False
if json_output:
self._get_executable_path_from_json(json_output)
if message_on_success:
self.console.print("[dim]Tests compiled successfully[/dim]")
return True
def _get_executable_path_from_json(self, json_output: str) -> None:
for json_line in json_output.splitlines():
try:
data = json.loads(json_line)
except json.JSONDecodeError:
continue
if data.get("target", {}).get("name") == "mdtest":
self.mdtest_executable = Path(data["executable"])
break
else:
raise RuntimeError(
"Could not find mdtest executable after successful compilation"
)
def _run_mdtest(
self, arguments: list[str] | None = None, *, capture_output: bool = False
) -> subprocess.CompletedProcess:
assert self.mdtest_executable is not None
arguments = arguments or []
return subprocess.run(
[self.mdtest_executable, *arguments],
cwd=CRATE_ROOT,
env=dict(
os.environ,
CLICOLOR_FORCE="1",
INSTA_FORCE_PASS="1",
INSTA_OUTPUT="none",
),
capture_output=capture_output,
text=True,
check=False,
)
def _mangle_path(self, markdown_file: Path) -> str:
return (
markdown_file.as_posix()
.replace("/", "_")
.replace("-", "_")
.removesuffix(".md")
)
def _run_mdtests_for_file(self, markdown_file: Path) -> None:
path_mangled = self._mangle_path(markdown_file)
test_name = f"mdtest__{path_mangled}"
output = self._run_mdtest(["--exact", test_name], capture_output=True)
if output.returncode == 0:
if "running 0 tests\n" in output.stdout:
self.console.log(
f"[yellow]Warning[/yellow]: No tests were executed with filter '{test_name}'"
)
else:
self.console.print(
f"Test for [bold green]{markdown_file}[/bold green] succeeded"
)
else:
self.console.print()
self.console.rule(
f"Test for [bold red]{markdown_file}[/bold red] failed",
style="gray",
)
self._print_trimmed_cargo_test_output(
output.stdout + output.stderr, test_name
)
def _print_trimmed_cargo_test_output(self, output: str, test_name: str) -> None:
# Skip 'cargo test' boilerplate at the beginning:
lines = output.splitlines()
start_index = 0
for i, line in enumerate(lines):
if f"{test_name} stdout" in line:
start_index = i
break
for line in lines[start_index + 1 :]:
if "MDTEST_TEST_FILTER" in line:
continue
if line.strip() == "-" * 50:
# Skip 'cargo test' boilerplate at the end
break
print(line)
def watch(self):
def keyboard_input() -> None:
for _ in sys.stdin:
# This is silly, but there is no other way to inject events into
# the main `watch` loop. We use changes to the `README.md` file
# as a trigger to re-run all mdtests:
MDTEST_README.touch()
input_thread = threading.Thread(target=keyboard_input, daemon=True)
input_thread.start()
self._recompile_tests("Compiling tests...", message_on_success=False)
self._run_mdtest(self.filters)
self.console.print("[dim]Ready to watch for changes...[/dim]")
for changes in watch(*DIRS_TO_WATCH):
new_md_files = set()
changed_md_files = set()
rust_code_has_changed = False
vendored_typeshed_has_changed = False
for change, path_str in changes:
path = Path(path_str)
# See above: `README.md` changes trigger a full re-run of all tests
if path == MDTEST_README:
self._run_mdtest(self.filters)
continue
match path.suffix:
case ".rs":
rust_code_has_changed = True
case ".pyi" if path.is_relative_to(TY_VENDORED):
vendored_typeshed_has_changed = True
case ".md":
pass
case _:
continue
try:
relative_path = Path(path).relative_to(MDTEST_DIR)
except ValueError:
continue
match change:
case Change.added:
# When saving a file, some editors (looking at you, Vim) might first
# save the file with a temporary name (e.g. `file.md~`) and then rename
# it to the final name. This creates a `deleted` and `added` change.
# We treat those files as `changed` here.
if (Change.deleted, path_str) in changes:
changed_md_files.add(relative_path)
else:
new_md_files.add(relative_path)
case Change.modified:
changed_md_files.add(relative_path)
case Change.deleted:
# No need to do anything when a Markdown test is deleted
pass
case _ as unreachable:
assert_never(unreachable)
if rust_code_has_changed:
if self._recompile_tests("Rust code has changed, recompiling tests..."):
self._run_mdtest(self.filters)
elif vendored_typeshed_has_changed:
if self._recompile_tests(
"Vendored typeshed has changed, recompiling tests..."
):
self._run_mdtest(self.filters)
elif new_md_files:
files = " ".join(file.as_posix() for file in new_md_files)
self._recompile_tests(
f"New Markdown test [yellow]{files}[/yellow] detected, recompiling tests..."
)
for path in new_md_files | changed_md_files:
self._run_mdtests_for_file(path)
def main() -> None:
parser = argparse.ArgumentParser(
description="A runner for Markdown-based tests for ty"
)
parser.add_argument(
"filters",
nargs="*",
help="Partial paths or mangled names, e.g., 'loops/for.md' or 'loops_for'",
)
args = parser.parse_args()
try:
runner = MDTestRunner(filters=args.filters)
runner.watch()
except KeyboardInterrupt:
print()
if __name__ == "__main__":
main()
| MDTestRunner |
python | doocs__leetcode | solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/Solution.py | {
"start": 0,
"end": 419
} | class ____:
def minNumberOfHours(
self, x: int, y: int, energy: List[int], experience: List[int]
) -> int:
ans = 0
for dx, dy in zip(energy, experience):
if x <= dx:
ans += dx + 1 - x
x = dx + 1
if y <= dy:
ans += dy + 1 - y
y = dy + 1
x -= dx
y += dy
return ans
| Solution |
python | huggingface__transformers | src/transformers/cli/serve.py | {
"start": 9418,
"end": 9789
} | class ____:
"""Lightweight class to keep track of the tool call state."""
def __init__(self):
self.reset()
def reset(self):
"""Reset the tool call state (assumes we're outside a tool call)."""
self.inside_tool_call = False
self.has_tool_name_defined = False
self.arg_nesting_level = 0
self.buffer = ""
| ToolState |
python | mahmoud__glom | glom/core.py | {
"start": 88552,
"end": 89772
} | class ____:
def __init__(self):
self.cache = {}
def mode(self, target, spec, scope):
"""
similar to FILL, but without function calling;
useful for default, scope assignment, call/invoke, etc
"""
recur = lambda val: scope[glom](target, val, scope)
result = spec
if type(spec) in (list, dict): # can contain themselves
if id(spec) in self.cache:
return self.cache[id(spec)]
result = self.cache[id(spec)] = type(spec)()
if type(spec) is dict:
result.update({recur(key): recur(val) for key, val in spec.items()})
else:
result.extend([recur(val) for val in spec])
if type(spec) in (tuple, set, frozenset): # cannot contain themselves
result = type(spec)([recur(val) for val in spec])
return result
def arg_val(target, arg, scope):
"""
evaluate an argument to find its value
(arg_val phonetically similar to "eval" -- evaluate as an arg)
"""
mode = scope[MIN_MODE]
scope[MIN_MODE] = _ArgValuator().mode
result = scope[glom](target, arg, scope)
scope[MIN_MODE] = mode
return result
| _ArgValuator |
python | python-attrs__attrs | src/attr/_make.py | {
"start": 2109,
"end": 7874
} | class ____(int):
"""
An integer subclass that pickles / copies as None
This is used for non-slots classes with ``cache_hash=True``, to avoid
serializing a potentially (even likely) invalid hash value. Since `None`
is the default value for uncalculated hashes, whenever this is copied,
the copy's value for the hash should automatically reset.
See GH #613 for more details.
"""
def __reduce__(self, _none_constructor=type(None), _args=()): # noqa: B008
return _none_constructor, _args
def attrib(
default=NOTHING,
validator=None,
repr=True,
cmp=None,
hash=None,
init=True,
metadata=None,
type=None,
converter=None,
factory=None,
kw_only=None,
eq=None,
order=None,
on_setattr=None,
alias=None,
):
"""
Create a new field / attribute on a class.
Identical to `attrs.field`, except it's not keyword-only.
Consider using `attrs.field` in new code (``attr.ib`` will *never* go away,
though).
.. warning::
Does **nothing** unless the class is also decorated with
`attr.s` (or similar)!
.. versionadded:: 15.2.0 *convert*
.. versionadded:: 16.3.0 *metadata*
.. versionchanged:: 17.1.0 *validator* can be a ``list`` now.
.. versionchanged:: 17.1.0
*hash* is `None` and therefore mirrors *eq* by default.
.. versionadded:: 17.3.0 *type*
.. deprecated:: 17.4.0 *convert*
.. versionadded:: 17.4.0
*converter* as a replacement for the deprecated *convert* to achieve
consistency with other noun-based arguments.
.. versionadded:: 18.1.0
``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``.
.. versionadded:: 18.2.0 *kw_only*
.. versionchanged:: 19.2.0 *convert* keyword argument removed.
.. versionchanged:: 19.2.0 *repr* also accepts a custom callable.
.. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01.
.. versionadded:: 19.2.0 *eq* and *order*
.. versionadded:: 20.1.0 *on_setattr*
.. versionchanged:: 20.3.0 *kw_only* backported to Python 2
.. versionchanged:: 21.1.0
*eq*, *order*, and *cmp* also accept a custom callable
.. versionchanged:: 21.1.0 *cmp* undeprecated
.. versionadded:: 22.2.0 *alias*
.. versionchanged:: 25.4.0
*kw_only* can now be None, and its default is also changed from False to
None.
"""
eq, eq_key, order, order_key = _determine_attrib_eq_order(
cmp, eq, order, True
)
if hash is not None and hash is not True and hash is not False:
msg = "Invalid value for hash. Must be True, False, or None."
raise TypeError(msg)
if factory is not None:
if default is not NOTHING:
msg = (
"The `default` and `factory` arguments are mutually exclusive."
)
raise ValueError(msg)
if not callable(factory):
msg = "The `factory` argument must be a callable."
raise ValueError(msg)
default = Factory(factory)
if metadata is None:
metadata = {}
# Apply syntactic sugar by auto-wrapping.
if isinstance(on_setattr, (list, tuple)):
on_setattr = setters.pipe(*on_setattr)
if validator and isinstance(validator, (list, tuple)):
validator = and_(*validator)
if converter and isinstance(converter, (list, tuple)):
converter = pipe(*converter)
return _CountingAttr(
default=default,
validator=validator,
repr=repr,
cmp=None,
hash=hash,
init=init,
converter=converter,
metadata=metadata,
type=type,
kw_only=kw_only,
eq=eq,
eq_key=eq_key,
order=order,
order_key=order_key,
on_setattr=on_setattr,
alias=alias,
)
def _compile_and_eval(
script: str,
globs: dict[str, Any] | None,
locs: Mapping[str, object] | None = None,
filename: str = "",
) -> None:
"""
Evaluate the script with the given global (globs) and local (locs)
variables.
"""
bytecode = compile(script, filename, "exec")
eval(bytecode, globs, locs)
def _linecache_and_compile(
script: str,
filename: str,
globs: dict[str, Any] | None,
locals: Mapping[str, object] | None = None,
) -> dict[str, Any]:
"""
Cache the script with _linecache_, compile it and return the _locals_.
"""
locs = {} if locals is None else locals
# In order of debuggers like PDB being able to step through the code,
# we add a fake linecache entry.
count = 1
base_filename = filename
while True:
linecache_tuple = (
len(script),
None,
script.splitlines(True),
filename,
)
old_val = linecache.cache.setdefault(filename, linecache_tuple)
if old_val == linecache_tuple:
break
filename = f"{base_filename[:-1]}-{count}>"
count += 1
_compile_and_eval(script, globs, locs, filename)
return locs
def _make_attr_tuple_class(cls_name: str, attr_names: list[str]) -> type:
"""
Create a tuple subclass to hold `Attribute`s for an `attrs` class.
The subclass is a bare tuple with properties for names.
class MyClassAttributes(tuple):
__slots__ = ()
x = property(itemgetter(0))
"""
attr_class_name = f"{cls_name}Attributes"
body = {}
for i, attr_name in enumerate(attr_names):
def getter(self, i=i):
return self[i]
body[attr_name] = property(getter)
return type(attr_class_name, (tuple,), body)
# Tuple class for extracted attributes from a class definition.
# `base_attrs` is a subset of `attrs`.
| _CacheHashWrapper |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 28398,
"end": 28545
} | class ____(str, Enum):
"""
* `DESC`: Descending order.
* `ASC`: Ascending order.
"""
desc = "DESC"
asc = "ASC"
| ListOrder |
python | pdm-project__pdm | src/pdm/models/search.py | {
"start": 200,
"end": 396
} | class ____:
name: str = ""
version: str = ""
description: str = ""
def as_frozen(self) -> SearchResult:
return SearchResult(self.name, self.version, self.description)
| Result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.