scalable-pypeline 2.1.31__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. pypeline/__init__.py +1 -0
  2. pypeline/barrier.py +63 -0
  3. pypeline/constants.py +94 -0
  4. pypeline/dramatiq.py +455 -0
  5. pypeline/executable_job_config_schema.py +35 -0
  6. pypeline/extensions.py +17 -0
  7. pypeline/flask/__init__.py +16 -0
  8. pypeline/flask/api/__init__.py +0 -0
  9. pypeline/flask/api/pipelines.py +275 -0
  10. pypeline/flask/api/schedules.py +40 -0
  11. pypeline/flask/decorators.py +41 -0
  12. pypeline/flask/flask_pypeline.py +156 -0
  13. pypeline/job_runner.py +205 -0
  14. pypeline/pipeline_config_schema.py +352 -0
  15. pypeline/pipeline_settings_schema.py +561 -0
  16. pypeline/pipelines/__init__.py +0 -0
  17. pypeline/pipelines/composition/__init__.py +0 -0
  18. pypeline/pipelines/composition/parallel_pipeline_composition.py +375 -0
  19. pypeline/pipelines/composition/pypeline_composition.py +215 -0
  20. pypeline/pipelines/factory.py +86 -0
  21. pypeline/pipelines/middleware/__init__.py +0 -0
  22. pypeline/pipelines/middleware/get_active_worker_id_middleware.py +22 -0
  23. pypeline/pipelines/middleware/graceful_shutdown_middleware.py +50 -0
  24. pypeline/pipelines/middleware/parallel_pipeline_middleware.py +60 -0
  25. pypeline/pipelines/middleware/pypeline_middleware.py +202 -0
  26. pypeline/pypeline_yaml.py +468 -0
  27. pypeline/schedule_config_schema.py +125 -0
  28. pypeline/utils/__init__.py +0 -0
  29. pypeline/utils/config_utils.py +81 -0
  30. pypeline/utils/dramatiq_utils.py +134 -0
  31. pypeline/utils/executable_job_util.py +35 -0
  32. pypeline/utils/graceful_shutdown_util.py +39 -0
  33. pypeline/utils/module_utils.py +108 -0
  34. pypeline/utils/pipeline_utils.py +144 -0
  35. pypeline/utils/schema_utils.py +24 -0
  36. scalable_pypeline-2.1.31.dist-info/LICENSE +177 -0
  37. scalable_pypeline-2.1.31.dist-info/METADATA +212 -0
  38. scalable_pypeline-2.1.31.dist-info/RECORD +42 -0
  39. scalable_pypeline-2.1.31.dist-info/WHEEL +6 -0
  40. scalable_pypeline-2.1.31.dist-info/entry_points.txt +6 -0
  41. scalable_pypeline-2.1.31.dist-info/top_level.txt +2 -0
  42. tests/fixtures/__init__.py +0 -0
@@ -0,0 +1,134 @@
1
+ import os.path
2
+ import sys
3
+ import typing
4
+ from typing import Optional, Callable, Union, Awaitable
5
+ from functools import wraps
6
+ from typing import TYPE_CHECKING, TypeVar
7
+ from dramatiq import Broker, actor as register_actor
8
+
9
+ from pypeline.constants import (
10
+ DEFAULT_TASK_MAX_RETRY,
11
+ DEFAULT_TASK_MIN_BACKOFF,
12
+ MS_IN_SECONDS,
13
+ DEFAULT_TASK_MAX_BACKOFF,
14
+ DEFAULT_TASK_TTL,
15
+ DEFAULT_RESULT_TTL,
16
+ )
17
+
18
+ if TYPE_CHECKING:
19
+ from typing_extensions import ParamSpec
20
+
21
+ P = ParamSpec("P")
22
+ else:
23
+ P = TypeVar("P")
24
+
25
+ R = TypeVar("R")
26
+
27
+
28
+ def guess_code_directory(broker):
29
+ actor = next(iter(broker.actors.values()))
30
+ modname, *_ = actor.fn.__module__.partition(".")
31
+ mod = sys.modules[modname]
32
+ return os.path.dirname(mod.__file__)
33
+
34
+
35
+ def list_managed_actors(broker, queues):
36
+ queues = set(queues)
37
+ all_actors = broker.actors.values()
38
+ if not queues:
39
+ return all_actors
40
+ else:
41
+ return [a for a in all_actors if a.queue_name in queues]
42
+
43
+
44
+ def register_lazy_actor(
45
+ broker: Broker,
46
+ fn: Optional[Callable[P, Union[Awaitable[R], R]]] = None,
47
+ pipeline_meta: typing.Dict = {},
48
+ server_type: Optional[str] = None,
49
+ **kwargs,
50
+ ) -> typing.Type["LazyActor"]:
51
+ if server_type:
52
+ kwargs["queue_name"] = server_type + "-" + pipeline_meta.get("queue", "default")
53
+ else:
54
+ kwargs["queue_name"] = pipeline_meta.get("queue", "default")
55
+ kwargs["max_retries"] = pipeline_meta.get("maxRetry", DEFAULT_TASK_MAX_RETRY)
56
+ # Convert from seconds to milliseconds
57
+ kwargs["min_backoff"] = (
58
+ pipeline_meta.get("retryBackoff", DEFAULT_TASK_MIN_BACKOFF) * MS_IN_SECONDS
59
+ )
60
+ kwargs["max_backoff"] = (
61
+ pipeline_meta.get("retryBackoffMax", DEFAULT_TASK_MAX_BACKOFF) * MS_IN_SECONDS
62
+ )
63
+ kwargs["time_limit"] = pipeline_meta.get("maxTtl", DEFAULT_TASK_TTL) * MS_IN_SECONDS
64
+ # Always store results for registered pipeline actors
65
+ kwargs["store_results"] = pipeline_meta.get("store_results", True)
66
+ if kwargs["store_results"]:
67
+ kwargs["result_ttl"] = (
68
+ pipeline_meta.get("result_ttl", DEFAULT_RESULT_TTL) * MS_IN_SECONDS
69
+ )
70
+ lazy_actor: LazyActor = LazyActor(fn, kwargs)
71
+ lazy_actor.register(broker)
72
+ return lazy_actor
73
+
74
+
75
+ def ensure_return_value(default_value=None):
76
+ def decorator(func):
77
+ @wraps(func)
78
+ def wrapper(*args, **kwargs):
79
+ # Call the original function
80
+ result = func(*args, **kwargs)
81
+ # Check if the function has returned a value
82
+ if result is None:
83
+ # Return the default value if the function returned None
84
+ return default_value
85
+ return result
86
+
87
+ return wrapper
88
+
89
+ return decorator
90
+
91
+
92
+ class LazyActor(object):
93
+ # Intermediate object that register actor on broker an call.
94
+
95
+ def __init__(self, fn, kw):
96
+ self.fn = fn
97
+ self.kw = kw
98
+ self.actor = None
99
+
100
+ def __call__(self, *a, **kw):
101
+ return self.fn(*a, **kw)
102
+
103
+ def __repr__(self):
104
+ return "<%s %s.%s>" % (
105
+ self.__class__.__name__,
106
+ self.fn.__module__,
107
+ self.fn.__name__,
108
+ )
109
+
110
+ def __getattr__(self, name):
111
+ if not self.actor:
112
+ raise AttributeError(name)
113
+ return getattr(self.actor, name)
114
+
115
+ def register(self, broker):
116
+ actor_name = f"{self.fn.__module__}.{self.fn.__name__}-{self.kw['queue_name']}"
117
+ if actor_name in broker.actors:
118
+ self.actor = broker.actors[actor_name]
119
+ else:
120
+ self.actor = register_actor(
121
+ actor_name=actor_name,
122
+ broker=broker,
123
+ **self.kw,
124
+ )(ensure_return_value(default_value=True)(self.fn))
125
+
126
+ # Next is regular actor API.
127
+ def send(self, *a, **kw):
128
+ return self.actor.send(*a, **kw)
129
+
130
+ def message(self, *a, **kw):
131
+ return self.actor.message(*a, **kw)
132
+
133
+ def send_with_options(self, *a, **kw):
134
+ return self.actor.send_with_options(*a, **kw)
@@ -0,0 +1,35 @@
1
+ from dramatiq.broker import get_broker
2
+
3
+ from pypeline.utils.config_utils import retrieve_executable_job_config
4
+ from pypeline.utils.dramatiq_utils import register_lazy_actor, LazyActor
5
+ from pypeline.utils.module_utils import get_callable
6
+
7
+
8
+ def execute_job(fn, *args, **kwargs):
9
+ executable_jobs_config = retrieve_executable_job_config()
10
+
11
+ module_path = kwargs.get("module_path", None)
12
+
13
+ job = None
14
+
15
+ for j in executable_jobs_config or []:
16
+ if module_path and module_path == j["config"]["task"]:
17
+ job = j
18
+ break
19
+ elif fn.__name__ in j["config"]["task"]:
20
+ if job:
21
+ raise ValueError(
22
+ f"Multiple matches found in yaml for {fn.__name__}, "
23
+ f"Consider passing module_path as a kwarg to avoid ambiguity."
24
+ )
25
+ job = j
26
+
27
+ if job is None:
28
+ raise ValueError(f"No match found in yaml for {fn.__name__} function.")
29
+
30
+ pipeline_meta = {"queue": job["config"].get("queue", "default")}
31
+ tmp_handler = get_callable(job["config"]["task"])
32
+
33
+ actor: LazyActor = register_lazy_actor(get_broker(), tmp_handler, pipeline_meta, None)
34
+
35
+ return actor.send(*args, **kwargs)
@@ -0,0 +1,39 @@
1
+ import threading
2
+ import signal
3
+ import os
4
+ import redis
5
+ import socket
6
+ import sys
7
+ import time
8
+ import logging
9
+ from pypeline.pipelines.middleware.graceful_shutdown_middleware import (
10
+ GraceFulShutdownMiddleware,
11
+ )
12
+
13
+ logging.basicConfig(level=logging.INFO)
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def enable_graceful_shutdown(broker, redis_url):
18
+ """Attach GracefulShutdownMiddleware and a SIGTERM handler to the current process."""
19
+ broker.add_middleware(GraceFulShutdownMiddleware(redis_url=redis_url))
20
+
21
+ if threading.current_thread().name == "MainThread":
22
+ key_prefix = "busy"
23
+ hostname = socket.gethostname()
24
+ pid = os.getpid()
25
+ busy_key = f"{key_prefix}:{hostname}-{pid}"
26
+ r = redis.Redis.from_url(redis_url)
27
+
28
+ def shutdown_handler(signum, frame):
29
+ logger.info(f"[Signal Handler] Received signal {signum}")
30
+ wait_counter = 0
31
+ while r.get(busy_key):
32
+ if wait_counter % 30 == 0: # Only log every 30 checks
33
+ logger.info(f"[Signal Handler] Busy ({busy_key}), waiting...")
34
+ time.sleep(1)
35
+ wait_counter += 1
36
+ logger.info(f"[Signal Handler] Done. Exiting.")
37
+ sys.exit(0)
38
+
39
+ signal.signal(signal.SIGTERM, shutdown_handler)
@@ -0,0 +1,108 @@
1
+ """ Utilities for loading modules/callables based on strings.
2
+ """
3
+
4
+ import re
5
+ import logging
6
+ import importlib
7
+ from typing import Callable
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class PypelineModuleLoader(object):
13
+ """Helper class to load modules / classes / methods based on a path string."""
14
+
15
+ def get_module(self, resource_dot_path: str):
16
+ """Retrieve the module based on a 'resource dot path'.
17
+ e.g. package.subdir.feature_file.MyCallable
18
+ """
19
+ module_path = ".".join(resource_dot_path.split(".")[:-1])
20
+ module = importlib.import_module(module_path)
21
+ return module
22
+
23
+ def get_callable_name(self, resource_dot_path: str) -> str:
24
+ """Retrieve the callable based on config string.
25
+ e.g. package.subdir.feature_file.MyCallable
26
+ """
27
+ callable_name = resource_dot_path.split(".")[-1]
28
+ return callable_name
29
+
30
+ def get_callable(self, resource_dot_path: str) -> Callable:
31
+ """Retrieve the actual handler class based on config string.
32
+ e.g. package.subdir.feature_file.MyCallable
33
+ """
34
+ module = self.get_module(resource_dot_path)
35
+ callable_name = self.get_callable_name(resource_dot_path)
36
+ return getattr(module, callable_name)
37
+
38
+
39
+ def normalized_pkg_name(pkg_name: str, dashed: bool = False):
40
+ """We maintain consistency by always specifying the package name as
41
+ the "dashed version".
42
+
43
+ Python/setuptools will replace "_" with "-" but resource_filename()
44
+ expects the exact directory name, essentially. In order to keep it
45
+ simple upstream and *always* provide package name as the dashed
46
+ version, we do replacement here to 'normalize' both versions to
47
+ whichever convention you need at the time.
48
+
49
+ if `dashed`:
50
+ my-package-name --> my-package-name
51
+ my_package_name --> my-package-name
52
+
53
+ else:
54
+ my-package-name --> my_package_name
55
+ my_package_name --> my_package_name
56
+ """
57
+ if dashed:
58
+ return str(pkg_name).replace("_", "-")
59
+ return str(pkg_name).replace("-", "_")
60
+
61
+
62
+ def match_prefix(string: str, prefix_p: str) -> bool:
63
+ """For given string, determine whether it begins with provided prefix_p."""
64
+ pattern = re.compile("^(" + prefix_p + ").*")
65
+ if pattern.match(string):
66
+ return True
67
+ return False
68
+
69
+
70
+ def match_suffix(string: str, suffix_p: str) -> bool:
71
+ """For given string, determine whether it ends with provided suffix_p."""
72
+ pattern = re.compile(".*(" + suffix_p + ")$")
73
+ if pattern.match(string):
74
+ return True
75
+ return False
76
+
77
+
78
+ def match_prefix_suffix(string: str, prefix_p: str, suffix_p: str) -> bool:
79
+ """For given string, determine whether it starts w/ prefix & ends w/ suffix"""
80
+ if match_prefix(string, prefix_p) and match_suffix(string, suffix_p):
81
+ return True
82
+ return False
83
+
84
+
85
+ def get_module(resource_dot_path: str):
86
+ """Retrieve the module based on a 'resource dot path'.
87
+ e.g. package.subdir.feature_file.MyCallable
88
+ """
89
+ module_path = ".".join(resource_dot_path.split(".")[:-1])
90
+ module = importlib.import_module(module_path)
91
+ return module
92
+
93
+
94
+ def get_callable_name(resource_dot_path: str) -> str:
95
+ """Retrieve the callable based on config string.
96
+ e.g. package.subdir.feature_file.MyCallable
97
+ """
98
+ callable_name = resource_dot_path.split(".")[-1]
99
+ return callable_name
100
+
101
+
102
+ def get_callable(resource_dot_path: str) -> Callable:
103
+ """Retrieve the actual handler class based on config string.
104
+ e.g. package.subdir.feature_file.MyCallable
105
+ """
106
+ module = get_module(resource_dot_path)
107
+ callable_name = get_callable_name(resource_dot_path)
108
+ return getattr(module, callable_name)
@@ -0,0 +1,144 @@
1
+ import logging
2
+ import typing
3
+ import networkx as nx
4
+
5
+
6
+ T = typing.TypeVar("T") # T can be any type
7
+
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def get_execution_graph(
13
+ config: dict,
14
+ adjacency_key: str = "dagAdjacency",
15
+ task_definitions_key: str = "taskDefinitions",
16
+ ) -> nx.DiGraph:
17
+ """Generate a directed graph based on a pipeline config's adjacency list
18
+ and task definitions.
19
+
20
+ `dagAdjacency` is a dictionary containing all nodes and downstream
21
+ nodes.
22
+
23
+ `taskDefinitions` is a dictionary containing metadata required for
24
+ each node such as the worker, model version, etc. This metadata is
25
+ attached to each node so it can be retrieved directly from the graph.
26
+ """
27
+ G = nx.DiGraph()
28
+
29
+ # Get our adjacency list and task definitions
30
+ adjacency_dict = config.get(adjacency_key, {})
31
+ task_definitions = config.get(task_definitions_key, {})
32
+ if len(adjacency_dict.keys()) == 0:
33
+ logger.warning(
34
+ "Adjacency definition `{}` was not found ...".format(adjacency_key)
35
+ )
36
+
37
+ # Build the graph
38
+ for node in adjacency_dict.keys():
39
+ adjacent_nodes = adjacency_dict[node]
40
+
41
+ # If no adjacent nodes, then this is a terminal node
42
+ if len(adjacent_nodes) == 0:
43
+ G.add_node(node, attr_dict=task_definitions.get(node, {}))
44
+ continue
45
+
46
+ # Otherwise, we'll add an edge from this node to all adjacent nodes
47
+ # and add the task defnition metadata to the edge
48
+ G.add_edges_from(
49
+ [(node, n, task_definitions.get(n, {})) for n in adjacent_nodes]
50
+ )
51
+ return G
52
+
53
+
54
+ def process_non_none_value(value: T) -> None:
55
+ """
56
+ Processes a value that must not be None.
57
+
58
+ The function checks if the provided value is None and raises a ValueError if it is.
59
+ If the value is not None, it proceeds to process and print the value.
60
+
61
+ :param value: The value to process. Can be of any type, but must not be None.
62
+
63
+ :raises ValueError: If the value is None.
64
+
65
+ Example:
66
+ >>> process_non_none_value(42)
67
+ Processing value: 42
68
+
69
+ >>> process_non_none_value("hello")
70
+ Processing value: hello
71
+
72
+ >>> process_non_none_value(None)
73
+ Traceback (most recent call last):
74
+ ...
75
+ ValueError: None value is not allowed
76
+ """
77
+ if value is None:
78
+ raise ValueError("None value is not allowed")
79
+
80
+
81
+ def topological_sort_with_parallelism(
82
+ graph: nx.DiGraph, executable_nodes=None
83
+ ) -> typing.List[typing.List[T]]:
84
+ """
85
+ Recurse over the graph to find an optimal execution strategy for processing nodes in an order where
86
+ no node shall be processed before all of its predecessors have been processed. The function handles
87
+ parallel execution by identifying nodes that can be processed in parallel at each step. If the graph
88
+ contains a cycle, the function will not be able to generate an execution plan and will raise an exception.
89
+
90
+ :param graph: A directed acyclic graph (DiGraph) from NetworkX.
91
+ :param executable_nodes: A list of lists where each inner list contains nodes that can be executed
92
+ in parallel at each step. This parameter is used for recursion.
93
+ :return: A list of lists where each inner list contains nodes that can be executed in parallel at each step.
94
+
95
+ >>> g = nx.DiGraph()
96
+ >>> g.add_edges_from([(1, 2), (1, 3), (2, 4), (3, 4)])
97
+ >>> topological_sort_with_parallelism(g)
98
+ [[1], [2, 3], [4]]
99
+
100
+ >>> g = nx.DiGraph()
101
+ >>> g.add_edges_from([(1, 2), (2, 3), (3, 4)])
102
+ >>> topological_sort_with_parallelism(g)
103
+ [[1], [2], [3], [4]]
104
+
105
+ >>> g = nx.DiGraph()
106
+ >>> g.add_edges_from([(1, 2), (2, 3), (3, 1)])
107
+ >>> topological_sort_with_parallelism(g)
108
+ Traceback (most recent call last):
109
+ ...
110
+ NetworkXUnfeasible: Graph contains a cycle, cannot compute a topological sort.
111
+ """
112
+ nodes = list(nx.topological_sort(graph))
113
+ round_executable_nodes = [n for n in nodes if graph.in_degree(n) == 0]
114
+ graph.remove_nodes_from(round_executable_nodes)
115
+
116
+ if len(round_executable_nodes) == 0:
117
+ return executable_nodes
118
+ else:
119
+ executable_nodes = [] if executable_nodes is None else executable_nodes
120
+ executable_nodes.append(round_executable_nodes)
121
+ return topological_sort_with_parallelism(graph, executable_nodes)
122
+
123
+
124
+ def plt_execution_tree(G):
125
+ import networkx as nx
126
+ import matplotlib.pyplot as plt
127
+
128
+ # Draw the graph
129
+ plt.figure(figsize=(8, 6))
130
+ pos = nx.spring_layout(G) # Compute positions for nodes
131
+ nx.draw(
132
+ G,
133
+ pos,
134
+ with_labels=True,
135
+ node_color="lightblue",
136
+ node_size=3000,
137
+ edge_color="gray",
138
+ arrowsize=20,
139
+ font_size=12,
140
+ )
141
+
142
+ # Show the plot
143
+ plt.title("Directed Graph Visualization")
144
+ plt.show()
@@ -0,0 +1,24 @@
1
+ def get_clean_validation_messages(validation_error):
2
+ """
3
+ Extract and format clean validation error messages.
4
+
5
+ Args:
6
+ validation_error (ValidationError): The Marshmallow ValidationError instance.
7
+
8
+ Returns:
9
+ str: A formatted string with all validation error messages.
10
+ """
11
+
12
+ def format_errors(errors, parent_key=""):
13
+ messages = []
14
+ for key, value in errors.items():
15
+ full_key = f"{parent_key}.{key}" if parent_key else key
16
+ if isinstance(value, dict):
17
+ # Recursively format nested errors
18
+ messages.extend(format_errors(value, full_key))
19
+ else:
20
+ # Append error messages
21
+ messages.append(f"{full_key}: {', '.join(value)}")
22
+ return messages
23
+
24
+ return "\n".join(format_errors(validation_error.messages))
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS