index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
56,310
saltant-org/saltant
refs/heads/master
/tasksapi/apps.py
from django.apps import AppConfig class TasksApiConfig(AppConfig): name = "tasksapi" verbose_name = "tasks API"
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,311
saltant-org/saltant
refs/heads/master
/tasksapi/serializers/container_tasks.py
"""Contains serializers for the container tasks models.""" from django.core.exceptions import ValidationError from rest_framework import serializers from tasksapi.models import ContainerTaskInstance, ContainerTaskType from .abstract_tasks import ( AbstractTaskInstanceSerializer, AbstractTaskTypeSerializer, ) class ContainerTaskTypeSerializer(AbstractTaskTypeSerializer): """A serializer for a container task type.""" class Meta(AbstractTaskTypeSerializer.Meta): model = ContainerTaskType class ContainerTaskInstanceSerializer(AbstractTaskInstanceSerializer): """A serializer for a container task instance.""" class Meta(AbstractTaskInstanceSerializer.Meta): model = ContainerTaskInstance def validate(self, attrs): """Refer to parent class docstring :)""" # Call parent validator attrs = super().validate(attrs) # Test the instance try: test_instance = ContainerTaskInstance( user=self.context["request"].user, task_type=attrs["task_type"], task_queue=attrs["task_queue"], arguments=attrs["arguments"], ) test_instance.clean() except ValidationError as e: raise serializers.ValidationError(str(e)) return attrs
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,312
saltant-org/saltant
refs/heads/master
/tasksapi/serializers/task_queues.py
"""Contains serializers for task queues.""" from rest_framework import serializers from tasksapi.models import TaskQueue, TaskWhitelist class TaskQueueSerializer(serializers.ModelSerializer): """A serializer for a task type.""" user = serializers.SlugRelatedField(slug_field="username", read_only=True) class Meta: model = TaskQueue fields = "__all__" class TaskWhitelistSerializer(serializers.ModelSerializer): """A serializer for a task whitelist.""" user = serializers.SlugRelatedField(slug_field="username", read_only=True) class Meta: model = TaskWhitelist fields = "__all__"
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,313
saltant-org/saltant
refs/heads/master
/tasksapi/models/abstract_tasks.py
"""Models to represent abstract task types and instances. Other task type and task instance models should inherit from these. """ import json from uuid import uuid4 from django.contrib.postgres.fields import JSONField from django.core.exceptions import ValidationError from django.db import models from tasksapi.constants import ( CREATED, STATE_CHOICES, STATE_MAX_LENGTH, EXECUTABLE_TASK, DOCKER, SINGULARITY, ) from .task_queues import TaskQueue from .users import User from .utils import determine_task_class from .validators import task_instance_args_are_valid, task_type_args_are_valid class AbstractTaskType(models.Model): """A type of task to create instances with.""" name = models.CharField( max_length=200, unique=True, help_text="The name of the task." ) description = models.TextField( blank=True, help_text="A description of the task." ) user = models.ForeignKey( User, null=True, on_delete=models.SET_NULL, help_text="The author of this task.", ) # The datetime the task type was created. This will be automatically # set upon creation of a task type and is *not* editable. See # https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.DateField.auto_now_add # for more details. datetime_created = models.DateTimeField(auto_now_add=True) command_to_run = models.CharField( max_length=400, help_text=( "The command to run to execute the task. For example, " '"python /app/myscript.py". Note that shell operators ' "will *not* be parsed; for example, | and &&. " "Arguments will be appended to the end of the command." ), ) # Required environment variables environment_variables = JSONField( blank=True, default=list, help_text=( "A JSON array of environment variables to consume from " "the Celery worker's environment. Defaults to []. Note " "that all task instances have their job UUID available " "in the environment variable JOB_UUID." ), ) # Required arguments required_arguments = JSONField( blank=True, default=list, help_text="A JSON array of required argument names. Defaults to [].", ) # Default required argument values encoded as a dictionary. This # dictionary must be a subset of the required arguments, which is # validated when saving task types. required_arguments_default_values = JSONField( blank=True, default=dict, help_text=( "A JSON dictionary of default values for required " "arguments, where the keys are the argument names and " "the values are their corresponding default values. " "Defaults to {}." ), ) class Meta: # Don't make an actual database table for this. Note that this # gets set to False when the model is inherited. abstract = True # Ordering ordering = ["id"] def __str__(self): """String representation of a task type.""" return self.name def save(self, *args, **kwargs): # pylint: disable=arguments-differ # Call clean self.clean() # Call the parent save method super().save(*args, **kwargs) def clean(self): """Validate a task type's required arguments.""" # Set null JSON values to empty Python data structures if self.environment_variables is None: self.environment_variables = [] if self.required_arguments is None: self.required_arguments = [] if self.required_arguments_default_values is None: self.required_arguments_default_values = {} # If JSON was passed in as a string, try to interpret it as JSON if isinstance(self.environment_variables, str): try: self.environment_variables = json.loads( self.environment_variables ) except json.JSONDecodeError: raise ValidationError( "'%s' is not valid JSON!" % self.environment_variables ) if isinstance(self.required_arguments, str): try: self.required_arguments = json.loads(self.required_arguments) except json.JSONDecodeError: raise ValidationError( "'%s' is not valid JSON!" % self.required_arguments ) if isinstance(self.required_arguments_default_values, str): try: self.required_arguments_default_values = json.loads( self.required_arguments_default_values ) except json.JSONDecodeError: raise ValidationError( "'%s' is not valid JSON!" % self.required_arguments_default_values ) # Make sure that JSON dicts are dicts and JSON arrays are lists if not isinstance(self.environment_variables, list): raise ValidationError( "'%s' is not a valid JSON array!" % self.environment_variables ) if not isinstance(self.required_arguments, list): raise ValidationError( "'%s' is not a valid JSON array!" % self.required_arguments ) if not isinstance(self.required_arguments_default_values, dict): raise ValidationError( "'%s' is not a valid JSON dictionary!" % self.required_arguments_default_values ) # Make sure arguments are valid is_valid, reason = task_type_args_are_valid(self) # Arguments are not valid! if not is_valid: raise ValidationError(reason) class AbstractTaskInstance(models.Model): """A running instance of a task type. Make sure you define a foreign key to the appropriate task type when you subclass this! """ name = models.CharField( max_length=200, blank=True, help_text="An optional non-unique name for the task instance.", ) uuid = models.UUIDField( primary_key=True, default=uuid4, editable=False, verbose_name="UUID", help_text="The UUID for the running job.", ) state = models.CharField( max_length=STATE_MAX_LENGTH, choices=STATE_CHOICES, default=CREATED ) user = models.ForeignKey( User, null=True, on_delete=models.SET_NULL, help_text="The author of this instance.", ) task_queue = models.ForeignKey( TaskQueue, on_delete=models.CASCADE, help_text="The queue this instance runs on.", ) datetime_created = models.DateTimeField( auto_now_add=True, help_text="When the job was created." ) datetime_finished = models.DateTimeField( null=True, editable=False, help_text="When the job finished." ) # Arguments encoded as a dictionary. The arguments pass in must # contain all of the required arguments of the task type for which # there don't exist default arguments. arguments = JSONField( blank=True, default=dict, help_text=( "A JSON dictionary of arguments, where the keys are the " "argument names and the values are their corresponding " "values. A task instance must specify values for all " "values of a task type's required arguments for which " "no default value exists. Defaults to {}." ), ) class Meta: """Model metadata.""" # Don't make an actual database table for this. Note that this # gets set to False when the model is inherited. abstract = True # Order with respect to most recently created ordering = ["-datetime_created"] def __str__(self): """String representation of a task instance.""" return str(self.uuid) def save(self, *args, **kwargs): # pylint: disable=arguments-differ """Perform additonal validation.""" # Call clean self.clean(fill_in_missing_args=True) # Call the parent save method super().save(*args, **kwargs) def clean( self, fill_in_missing_args=False ): # pylint: disable=arguments-differ """Validate an instance's arguments.""" # Set null JSON values to empty Python data structures if self.arguments is None: self.arguments = {} # If JSON was passed in as a string, try to interpret it as JSON if isinstance(self.arguments, str): try: self.arguments = json.loads(self.arguments) except json.JSONDecodeError: raise ValidationError("%s is not valid JSON!" % self.arguments) # Make sure the arguments JSON passed in is a dictionary if not isinstance(self.arguments, dict): raise ValidationError( "'%s' is not a valid JSON dictionary!" % self.arguments ) # Make sure the queue is active if not self.task_queue.active: raise ValidationError( "Queue %s is not active" % self.task_queue.name ) # Make sure the user is authorized to use the queue they're # posting to if self.task_queue.private and self.user != self.task_queue.user: raise ValidationError( "%s is not authorized to use the queue %s" % (self.user, self.task_queue.name) ) # Determine task class for queue validation this_task_class = determine_task_class(self) # Make sure this task type is on one of the queue's whitelists if this_task_class == EXECUTABLE_TASK: if not self.task_queue.whitelists.filter( whitelisted_executable_task_types=self.task_type ): raise ValidationError( "Queue %s has not whitelisted task type %s" % (self.task_queue.name, self.task_type.name) ) else: if not self.task_queue.whitelists.filter( whitelisted_container_task_types=self.task_type ): raise ValidationError( "Queue %s has not whitelisted task type %s" % (self.task_queue.name, self.task_type.name) ) # Make sure the queue accepts the type of task they're posting # to if this_task_class == EXECUTABLE_TASK: if not self.task_queue.runs_executable_tasks: raise ValidationError( "Queue %s does not accept executable tasks" % self.task_queue.name ) else: if ( self.task_type.container_type == DOCKER and not self.task_queue.runs_docker_container_tasks ): raise ValidationError( "Queue %s does not accept Docker container tasks" % self.task_queue.name ) elif ( self.task_type.container_type == SINGULARITY and not self.task_queue.runs_singularity_container_tasks ): raise ValidationError( "Queue %s does not accept Singularity container tasks" % self.task_queue.name ) # Make sure arguments are valid is_valid, reason = task_instance_args_are_valid( instance=self, fill_missing_args=fill_in_missing_args ) # Arguments are not valid! if not is_valid: raise ValidationError(reason)
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,314
saltant-org/saltant
refs/heads/master
/tasksapi/serializers/__init__.py
"""Collect all serializers to "export" from this directory.""" from .container_tasks import ( ContainerTaskTypeSerializer, ContainerTaskInstanceSerializer, ) from .executable_tasks import ( ExecutableTaskTypeSerializer, ExecutableTaskInstanceSerializer, ) from .task_instance_update import ( TaskInstanceStateUpdateRequestSerializer, TaskInstanceStateUpdateResponseSerializer, ) from .task_queues import TaskQueueSerializer, TaskWhitelistSerializer from .users import UserSerializer
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,315
saltant-org/saltant
refs/heads/master
/frontend/views/accounts.py
"""Views for accounts.""" from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views.generic import UpdateView from tasksapi.models import User class UserUpdate(LoginRequiredMixin, UpdateView): """A view for editing one's user info.""" model = User fields = ["username", "email", "time_zone"] template_name = "frontend/account_edit_profile.html" success_url = reverse_lazy("account") def get_object(self, queryset=None): """Get the user from the request.""" return self.request.user
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,316
saltant-org/saltant
refs/heads/master
/frontend/views/utils_logs.py
"""Contains helpers for getting task instance logs.""" import os from django.conf import settings import boto3 def get_s3_logs_for_task_instance(job_uuid): """Get logs for a task instance. The text from the job logs will be one long text strings, so no splitting at new lines here. If the project doesn't have AWS stuff defined, then this just returns an empty dictionary. Args: job_uuid: A string specifying the UUID of the task instance to get logs for. Returns: A dictionary where keys are file names and values are dictionaries containing the date the logs were last modified and the text they contain. """ # Get out if we don't have any AWS stuff defined for the project if ( not os.environ["AWS_ACCESS_KEY_ID"] or not os.environ["AWS_SECRET_ACCESS_KEY"] or not settings.AWS_LOGS_BUCKET_NAME ): return {} # This'll grab its settings from the environment (ultimately coming # from .env file) s3 = boto3.resource("s3") bucket = s3.Bucket(settings.AWS_LOGS_BUCKET_NAME) # Get the files log_files_dict = {} log_files = bucket.objects.filter(Prefix=job_uuid) for log_file in log_files: # Extract the file name and text file_name = log_file.key[len(job_uuid) + 1 :] file_last_modified = log_file.last_modified file_text = log_file.get()["Body"].read().decode("utf-8") # Add in this log file to our output sub_dict = {"last_modified": file_last_modified, "text": file_text} log_files_dict[file_name] = sub_dict return log_files_dict def get_s3_logs_for_executable_task_instance(job_uuid): """Get stdout and stderr logs for executable task instances. This is basically the same thing as get_s3_logs_for_task_instance except it changes the key names to "stdout" and "stderr" (since those are the only two types of logs an executable task type can have). Args: job_uuid: A string specifying the UUID of the exedcutable task instance to get logs for. Returns: A dictionary with keys "stdout" and "stderr" where the values are dictionaries containing the date the logs were last modified and the text they contain. However, if logs can't be found, then just return an empty dictionary. """ # Call the base function these_logs = get_s3_logs_for_task_instance(job_uuid) # Get out if these logs don't exist if not these_logs: return these_logs # Update the key names these_logs["stdout"] = these_logs.pop(job_uuid + "-" + "stdout.txt") these_logs["stderr"] = these_logs.pop(job_uuid + "-" + "stderr.txt") return these_logs
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,317
saltant-org/saltant
refs/heads/master
/tasksapi/migrations/0001_initial.py
# Generated by Django 2.1.2 on 2018-12-05 05:50 from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators import django.contrib.postgres.fields.jsonb import django.core.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), ], options={ 'verbose_name': 'user', 'verbose_name_plural': 'users', 'abstract': False, }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.CreateModel( name='ContainerTaskInstance', fields=[ ('name', models.CharField(blank=True, help_text='An optional non-unique name for the task instance.', max_length=200)), ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, help_text='The UUID for the running job.', primary_key=True, serialize=False, verbose_name='UUID')), ('state', models.CharField(choices=[('created', 'created'), ('published', 'published'), ('running', 'running'), ('successful', 'successful'), ('failed', 'failed'), ('terminated', 'terminated')], default='created', max_length=10)), ('datetime_created', models.DateTimeField(auto_now_add=True, help_text='When the job was created.')), ('datetime_finished', models.DateTimeField(editable=False, help_text='When the job finished.', null=True)), ('arguments', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=dict, help_text="A JSON dictionary of arguments, where the keys are the argument names and the values are their corresponding values. A task instance must specify values for all values of a task type's required arguments for which no default value exists. Defaults to {}.")), ], options={ 'ordering': ['-datetime_created'], 'abstract': False, }, ), migrations.CreateModel( name='ContainerTaskType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='The name of the task.', max_length=200, unique=True)), ('description', models.TextField(blank=True, help_text='A description of the task.')), ('datetime_created', models.DateTimeField(auto_now_add=True)), ('command_to_run', models.CharField(help_text='The command to run to execute the task. For example, "python /app/myscript.py". Note that shell operators will *not* be parsed; for example, | and &&. Arguments will be added to the end of this command as a JSON string, should there be any arguments.', max_length=400)), ('environment_variables', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=list, help_text="A JSON array of environment variables to consume from the Celery worker's environment. Defaults to []. Note that all task instances have their job UUID available in the environment variable JOB_UUID.")), ('required_arguments', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=list, help_text='A JSON array of required argument names. Defaults to [].')), ('required_arguments_default_values', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=dict, help_text='A JSON dictionary of default values for required arguments, where the keys are the argument names and the values are their corresponding default values. Defaults to {}.')), ('logs_path', models.CharField(blank=True, default=None, help_text='The path of the logs directory inside the container. Specify null if no logs directory. Defaults to null.', max_length=400, null=True)), ('results_path', models.CharField(blank=True, default=None, help_text='The path of the results (or "outputs") directory inside the container. Specify null if no results directory. Defaults to null.', max_length=400, null=True)), ('container_image', models.CharField(help_text='The container name and tag. For example, "ubuntu:14.04" for Docker; and "docker://ubuntu:14.04" or "shub://vsoch/hello-world" for Singularity.', max_length=200)), ('container_type', models.CharField(choices=[('docker', 'Docker'), ('singularity', 'Singularity')], help_text='The type of container provided.', max_length=11)), ('user', models.ForeignKey(help_text='The author of this task.', on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['id'], 'abstract': False, }, ), migrations.CreateModel( name='ExecutableTaskInstance', fields=[ ('name', models.CharField(blank=True, help_text='An optional non-unique name for the task instance.', max_length=200)), ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, help_text='The UUID for the running job.', primary_key=True, serialize=False, verbose_name='UUID')), ('state', models.CharField(choices=[('created', 'created'), ('published', 'published'), ('running', 'running'), ('successful', 'successful'), ('failed', 'failed'), ('terminated', 'terminated')], default='created', max_length=10)), ('datetime_created', models.DateTimeField(auto_now_add=True, help_text='When the job was created.')), ('datetime_finished', models.DateTimeField(editable=False, help_text='When the job finished.', null=True)), ('arguments', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=dict, help_text="A JSON dictionary of arguments, where the keys are the argument names and the values are their corresponding values. A task instance must specify values for all values of a task type's required arguments for which no default value exists. Defaults to {}.")), ], options={ 'ordering': ['-datetime_created'], 'abstract': False, }, ), migrations.CreateModel( name='ExecutableTaskType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='The name of the task.', max_length=200, unique=True)), ('description', models.TextField(blank=True, help_text='A description of the task.')), ('datetime_created', models.DateTimeField(auto_now_add=True)), ('command_to_run', models.CharField(help_text='The command to run to execute the task. For example, "python /app/myscript.py". Note that shell operators will *not* be parsed; for example, | and &&. Arguments will be added to the end of this command as a JSON string, should there be any arguments.', max_length=400)), ('environment_variables', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=list, help_text="A JSON array of environment variables to consume from the Celery worker's environment. Defaults to []. Note that all task instances have their job UUID available in the environment variable JOB_UUID.")), ('required_arguments', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=list, help_text='A JSON array of required argument names. Defaults to [].')), ('required_arguments_default_values', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=dict, help_text='A JSON dictionary of default values for required arguments, where the keys are the argument names and the values are their corresponding default values. Defaults to {}.')), ('json_file_option', models.CharField(blank=True, default=None, help_text="The name of a command line option, e.g., --json-file, which accepts a JSON-encoded file for the command to run. If this value is non-null, then the instance's JSON arguments are written to a file and this file is passed to the command (cf. normal behaviour where the JSON arguments are passed as a single argument to the task).", max_length=50, null=True, verbose_name='JSON file option')), ('user', models.ForeignKey(help_text='The author of this task.', on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['id'], 'abstract': False, }, ), migrations.CreateModel( name='TaskQueue', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='The name of the Celery queue.', max_length=50, unique=True, validators=[django.core.validators.RegexValidator(message=' @/+/-/_ only', regex='^[\\w@+-]+$')])), ('description', models.TextField(blank=True, help_text='A description of the queue.')), ('private', models.BooleanField(blank=True, default=False, help_text='A boolean specifying whether other users besides the queue creator can use the queue. Defaults to False.')), ('active', models.BooleanField(blank=True, default=True, help_text='A boolean showing the status of the queue. As of now, this needs to be toggled manually. Defaults to True.')), ('user', models.ForeignKey(help_text='The creator of the queue.', on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ['id'], }, ), migrations.AddField( model_name='executabletaskinstance', name='task_queue', field=models.ForeignKey(help_text='The queue this instance runs on.', on_delete=django.db.models.deletion.PROTECT, to='tasksapi.TaskQueue'), ), migrations.AddField( model_name='executabletaskinstance', name='task_type', field=models.ForeignKey(help_text='The task type for which this is an instance.', on_delete=django.db.models.deletion.PROTECT, to='tasksapi.ExecutableTaskType'), ), migrations.AddField( model_name='executabletaskinstance', name='user', field=models.ForeignKey(help_text='The author of this instance.', on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='containertaskinstance', name='task_queue', field=models.ForeignKey(help_text='The queue this instance runs on.', on_delete=django.db.models.deletion.PROTECT, to='tasksapi.TaskQueue'), ), migrations.AddField( model_name='containertaskinstance', name='task_type', field=models.ForeignKey(help_text='The task type for which this is an instance.', on_delete=django.db.models.deletion.PROTECT, to='tasksapi.ContainerTaskType'), ), migrations.AddField( model_name='containertaskinstance', name='user', field=models.ForeignKey(help_text='The author of this instance.', on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL), ), ]
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,318
saltant-org/saltant
refs/heads/master
/tasksapi/views.py
"""Contains view(sets) related to tasks.""" from celery.result import AsyncResult from django.core.exceptions import ObjectDoesNotExist from drf_yasg.utils import swagger_auto_schema from rest_framework import permissions, serializers, viewsets from rest_framework.decorators import action, api_view, permission_classes from rest_framework.response import Response from rest_framework.status import ( HTTP_200_OK, HTTP_201_CREATED, HTTP_202_ACCEPTED, HTTP_400_BAD_REQUEST, ) from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) from tasksapi.filters import ( ContainerTaskInstanceFilter, ContainerTaskTypeFilter, ExecutableTaskInstanceFilter, ExecutableTaskTypeFilter, TaskQueueFilter, TaskWhitelistFilter, UserFilter, ) from tasksapi.models import ( ContainerTaskInstance, ContainerTaskType, ExecutableTaskInstance, ExecutableTaskType, TaskQueue, TaskWhitelist, User, ) from tasksapi.paginators import SmallResultsSetPagination from tasksapi.permissions import IsAdminOrOwnerThenWriteElseReadOnly from tasksapi.serializers import ( ContainerTaskInstanceSerializer, ContainerTaskTypeSerializer, ExecutableTaskInstanceSerializer, ExecutableTaskTypeSerializer, TaskInstanceStateUpdateRequestSerializer, TaskInstanceStateUpdateResponseSerializer, TaskQueueSerializer, TaskWhitelistSerializer, UserSerializer, ) class UserViewSet(viewsets.ModelViewSet): """A viewset for users.""" queryset = User.objects.all().order_by("username") serializer_class = UserSerializer lookup_field = "username" http_method_names = ["get"] filter_class = UserFilter class UserInjectedModelViewSet(viewsets.ModelViewSet): """Subclass this for a ModelViewSet with an injected user attribute. Injected means that the user as determined by the request's authentication header will be sent to the viewset's serializer (cf. specified explicitly in the request body) for instance creation requests. """ def perform_create(self, serializer): serializer.save(user=self.request.user) class ContainerTaskInstanceViewSet(UserInjectedModelViewSet): """A viewset for container task instances.""" queryset = ContainerTaskInstance.objects.all() serializer_class = ContainerTaskInstanceSerializer pagination_class = SmallResultsSetPagination lookup_field = "uuid" http_method_names = ["get", "post"] filter_class = ContainerTaskInstanceFilter @swagger_auto_schema( method="post", request_body=serializers.Serializer, responses={HTTP_201_CREATED: ContainerTaskInstanceSerializer}, ) @action(methods=["post"], detail=True) def clone(self, request, uuid): """Clone a job with the same arguments, task type, and task queue.""" # Get the instance to be cloned instance_to_clone = ContainerTaskInstance.objects.get(uuid=uuid) # Build the new instance cloned_instance = ContainerTaskInstance.objects.create( name=instance_to_clone.name, user=request.user, task_type=instance_to_clone.task_type, task_queue=instance_to_clone.task_queue, arguments=instance_to_clone.arguments, ) # Serialize the new instance and return it in the response serialized_instance = ContainerTaskInstanceSerializer(cloned_instance) return Response(serialized_instance.data, status=HTTP_201_CREATED) @swagger_auto_schema( method="post", request_body=serializers.Serializer, responses={HTTP_202_ACCEPTED: ContainerTaskInstanceSerializer}, ) @action(methods=["post"], detail=True) def terminate(self, request, uuid): """Send a terminate signal to a job.""" # Terminate the job AsyncResult(uuid).revoke(terminate=True) # Post the object back as the response this_instance = ContainerTaskInstance.objects.get(uuid=uuid) serialized_instance = ContainerTaskInstanceSerializer(this_instance) return Response(serialized_instance.data, status=HTTP_202_ACCEPTED) @permission_classes((IsAdminOrOwnerThenWriteElseReadOnly,)) class ContainerTaskTypeViewSet(UserInjectedModelViewSet): """A viewset for container task types.""" queryset = ContainerTaskType.objects.all() serializer_class = ContainerTaskTypeSerializer http_method_names = ["get", "post", "put"] filter_class = ContainerTaskTypeFilter class ExecutableTaskInstanceViewSet(UserInjectedModelViewSet): """A viewset for executable task instances.""" queryset = ExecutableTaskInstance.objects.all() serializer_class = ExecutableTaskInstanceSerializer pagination_class = SmallResultsSetPagination lookup_field = "uuid" http_method_names = ["get", "post"] filter_class = ExecutableTaskInstanceFilter @swagger_auto_schema( method="post", request_body=serializers.Serializer, responses={HTTP_201_CREATED: ExecutableTaskInstanceSerializer}, ) @action(methods=["post"], detail=True) def clone(self, request, uuid): """Clone a job with the same arguments, task type, and task queue.""" # Get the instance to be cloned instance_to_clone = ExecutableTaskInstance.objects.get(uuid=uuid) # Build the new instance cloned_instance = ExecutableTaskInstance.objects.create( name=instance_to_clone.name, user=request.user, task_type=instance_to_clone.task_type, task_queue=instance_to_clone.task_queue, arguments=instance_to_clone.arguments, ) # Serialize the new instance and return it in the response serialized_instance = ExecutableTaskInstanceSerializer(cloned_instance) return Response(serialized_instance.data, status=HTTP_201_CREATED) @swagger_auto_schema( method="post", request_body=serializers.Serializer, responses={HTTP_202_ACCEPTED: ExecutableTaskInstanceSerializer}, ) @action(methods=["post"], detail=True) def terminate(self, request, uuid): """Send a terminate signal to a job.""" # Terminate the job AsyncResult(uuid).revoke(terminate=True) # Post the object back as the response this_instance = ExecutableTaskInstance.objects.get(uuid=uuid) serialized_instance = ExecutableTaskInstanceSerializer(this_instance) return Response(serialized_instance.data, status=HTTP_202_ACCEPTED) @permission_classes((IsAdminOrOwnerThenWriteElseReadOnly,)) class ExecutableTaskTypeViewSet(UserInjectedModelViewSet): """A viewset for executable task types.""" queryset = ExecutableTaskType.objects.all() serializer_class = ExecutableTaskTypeSerializer http_method_names = ["get", "post", "put"] filter_class = ExecutableTaskTypeFilter @permission_classes((IsAdminOrOwnerThenWriteElseReadOnly,)) class TaskQueueViewSet(UserInjectedModelViewSet): """A viewset for task queues.""" queryset = TaskQueue.objects.all() serializer_class = TaskQueueSerializer http_method_names = ["get", "post", "patch", "put"] filter_class = TaskQueueFilter @permission_classes((IsAdminOrOwnerThenWriteElseReadOnly,)) class TaskWhitelistViewSet(UserInjectedModelViewSet): """A viewset for task queues.""" queryset = TaskWhitelist.objects.all() serializer_class = TaskWhitelistSerializer http_method_names = ["get", "post", "patch", "put"] filter_class = TaskWhitelistFilter class TokenObtainPairPermissiveView(TokenObtainPairView): """Always make sure that users can obtain JWT tokens.""" # Inherit the more useful docstring (shown in the API reference) # from the parent __doc__ = TokenObtainPairView.__doc__ permission_classes = (permissions.AllowAny,) @swagger_auto_schema(security=[]) def post(self, request, *args, **kwargs): # Make sure drg-yasg knows this doesn't require auth headers. return super().post(request, *args, **kwargs) class TokenRefreshPermissiveView(TokenRefreshView): """Always make sure that users can obtain JWT tokens.""" # Inherit the more useful docstring (shown in the API reference) # from the parent __doc__ = TokenRefreshView.__doc__ permission_classes = (permissions.AllowAny,) @swagger_auto_schema(security=[]) def post(self, request, *args, **kwargs): # Make sure drg-yasg knows this doesn't require auth headers. return super().post(request, *args, **kwargs) @swagger_auto_schema( method="patch", request_body=TaskInstanceStateUpdateRequestSerializer, responses={HTTP_200_OK: TaskInstanceStateUpdateResponseSerializer}, ) @api_view(["PATCH"]) def update_task_instance_status(request, uuid): """Updates the status for task instances of any class of task.""" # Find the instance we need to update state = request.data["state"] try: # Try finding a container task instance first instance = ContainerTaskInstance.objects.get(uuid=uuid) instance.state = state instance.save() serialized_instance = TaskInstanceStateUpdateResponseSerializer( instance ) return Response(serialized_instance.data, status=HTTP_200_OK) except ObjectDoesNotExist: # Not a container task instance pass # Now try finding an executable task instance try: instance = ExecutableTaskInstance.objects.get(uuid=uuid) instance.state = state instance.save() serialized_instance = TaskInstanceStateUpdateResponseSerializer( instance ) return Response(serialized_instance.data, status=HTTP_200_OK) except ObjectDoesNotExist: # Not a container task instance pass # Bad request :( return Response( "No task instance with UUID {} found".format(uuid), status=HTTP_400_BAD_REQUEST, )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,319
saltant-org/saltant
refs/heads/master
/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py
"""Contains tests for user editing permissions.""" from rest_framework import status from rest_framework.test import APITestCase from .utils import ( TEST_CONTAINER_TASK_TYPE_DICT, TEST_EXECUTABLE_TASK_TYPE_DICT, ) # Put info about our fixtures data as constants here NON_ADMIN_USER_AUTH_TOKEN = "02d205bc79d5e8f15f83e249ac227ef0085f953f" NOT_USERS_CONTAINER_TASK_TYPE_PK = 1 NOT_USERS_EXECUTABLE_TASK_TYPE_PK = 1 NOT_USERS_QUEUE_PK = 1 NOT_USERS_WHITELIST_PK = 1 class UserEditPermissionsRequestsTests(APITestCase): """Test user editing permissions.""" fixtures = ["test-fixture.yaml"] def setUp(self): """Add in user's auth to client.""" self.client.credentials( HTTP_AUTHORIZATION="Token " + NON_ADMIN_USER_AUTH_TOKEN ) def test_modifying_other_users_container_task_type(self): """Test modifying another user's container task type.""" put_response = self.client.put( "/api/containertasktypes/%d/" % NOT_USERS_CONTAINER_TASK_TYPE_PK, TEST_CONTAINER_TASK_TYPE_DICT, format="json", ) self.assertEqual(put_response.status_code, status.HTTP_403_FORBIDDEN) def test_modifying_other_users_executable_task_type(self): """Test modifying another user's executable task type.""" put_response = self.client.put( "/api/executabletasktypes/%d/" % NOT_USERS_EXECUTABLE_TASK_TYPE_PK, TEST_EXECUTABLE_TASK_TYPE_DICT, format="json", ) self.assertEqual(put_response.status_code, status.HTTP_403_FORBIDDEN) def test_modifying_other_users_queue(self): """Test modifying another user's queue.""" put_response = self.client.put( "/api/taskqueues/%d/" % NOT_USERS_QUEUE_PK, dict(name="mine now"), format="json", ) self.assertEqual(put_response.status_code, status.HTTP_403_FORBIDDEN) def test_modifying_other_users_whitelist(self): """Test modifying another user's whitelist.""" put_response = self.client.put( "/api/taskqueues/%d/" % NOT_USERS_QUEUE_PK, dict(name="mine now"), format="json", ) self.assertEqual(put_response.status_code, status.HTTP_403_FORBIDDEN)
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,320
saltant-org/saltant
refs/heads/master
/frontend/views/tasktypes.py
"""Views for task types.""" from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views.generic import ( CreateView, DeleteView, DetailView, ListView, UpdateView, ) from tasksapi.constants import CONTAINER_TASK, EXECUTABLE_TASK from tasksapi.models import ContainerTaskType, ExecutableTaskType from .mixins import ( ContainerTaskTypeFormViewMixin, DisableUserSelectFormViewMixin, ExecutableTaskTypeFormViewMixin, IsAdminOrOwnerOnlyMixin, SetContainerTaskClassCookieMixin, SetExecutableTaskClassCookieMixin, TaskTypeFormViewMixin, UserFormViewMixin, ) from .utils import get_context_data_for_chartjs class BaseTaskTypeCreate( UserFormViewMixin, TaskTypeFormViewMixin, DisableUserSelectFormViewMixin, LoginRequiredMixin, CreateView, ): """A base view for creating a task type.""" model = None fields = "__all__" template_name = None def get_success_url(self): """Redirect to detail page.""" raise NotImplementedError class BaseTaskTypeDetail(LoginRequiredMixin, DetailView): """A base view for specific task types.""" model = None task_class = None context_object_name = "tasktype" template_name = None def get_context_data(self, **kwargs): """Pass along extra bits to the context.""" context = super().get_context_data(**kwargs) # Add in related task instances context["taskinstances"] = self.get_taskinstances() context["taskinstance_urlname"] = self.get_taskinstance_urlname() context[ "taskinstance_create_urlname" ] = self.get_taskinstance_create_urlname() # Get a nice representation of the command to run context[ "command_to_run_formatted" ] = self.get_formatted_command_to_run() # Get data for Chart.js context = { **context, **get_context_data_for_chartjs( task_class=self.task_class, task_type_pk=self.get_object().pk ), } return context def get_formatted_command_to_run(self): """Get a nice representation of the command to run. This assumes that JSON is being passed directly to the command. If this isn't the case then replace this method in subclasses. """ this_tasktype = self.get_object() # Build up the command to run as we go command_to_run = this_tasktype.command_to_run # Add in the JSON args if there are any if this_tasktype.required_arguments: command_to_run += " '{ json_args }'" return command_to_run def get_taskinstances(self): """Get a queryset of the task type's instances.""" raise NotImplementedError def get_taskinstance_urlname(self): """Get the URL name for task instances.""" raise NotImplementedError def get_taskinstance_create_urlname(self): """Get the URL name for creating task instances.""" raise NotImplementedError class BaseTaskTypeUpdate( LoginRequiredMixin, IsAdminOrOwnerOnlyMixin, TaskTypeFormViewMixin, DisableUserSelectFormViewMixin, UpdateView, ): """A base view for updating a task type.""" model = None fields = "__all__" template_name = None def get_success_url(self): """Redirect to detail page.""" raise NotImplementedError class BaseTaskTypeDelete( LoginRequiredMixin, IsAdminOrOwnerOnlyMixin, DeleteView ): """A base view for deleting a task type.""" model = None context_object_name = "tasktype" template_name = "frontend/base_tasktype_delete.html" success_url = None class ContainerTaskTypeList( SetContainerTaskClassCookieMixin, LoginRequiredMixin, ListView ): """A view for listing container task types.""" model = ContainerTaskType template_name = "frontend/containertasktype_list.html" class ContainerTaskTypeCreate( ContainerTaskTypeFormViewMixin, BaseTaskTypeCreate ): """A view for creating a container task type.""" model = ContainerTaskType template_name = "frontend/containertasktype_create.html" def get_success_url(self): """Redirect to detail page.""" return reverse_lazy( "containertasktype-detail", kwargs={"pk": self.object.pk} ) class ContainerTaskTypeDetail(BaseTaskTypeDetail): """A view for a specific container task type.""" model = ContainerTaskType task_class = CONTAINER_TASK template_name = "frontend/containertasktype_detail.html" def get_taskinstances(self): """Get a queryset of the task type's instances.""" return self.get_object().containertaskinstance_set.all() def get_taskinstance_urlname(self): """Get the URL name for task instances.""" return "containertaskinstance-detail" def get_taskinstance_create_urlname(self): """Get the URL name for creating task instances.""" return "containertaskinstance-create" class ContainerTaskTypeUpdate( ContainerTaskTypeFormViewMixin, BaseTaskTypeUpdate ): """A view for updating a container task type.""" model = ContainerTaskType template_name = "frontend/containertasktype_update.html" def get_success_url(self): """Redirect to detail page.""" return reverse_lazy( "containertasktype-detail", kwargs={"pk": self.object.pk} ) class ContainerTaskTypeDelete(BaseTaskTypeDelete): """A view for deleting a container task type.""" model = ContainerTaskType success_url = reverse_lazy("containertasktype-list") class ExecutableTaskTypeList( SetExecutableTaskClassCookieMixin, LoginRequiredMixin, ListView ): """A view for listing executable task types.""" model = ExecutableTaskType template_name = "frontend/executabletasktype_list.html" class ExecutableTaskTypeCreate( ExecutableTaskTypeFormViewMixin, BaseTaskTypeCreate ): """A view for creating an executable task type.""" model = ExecutableTaskType template_name = "frontend/executabletasktype_create.html" def get_success_url(self): """Redirect to detail page.""" return reverse_lazy( "executabletasktype-detail", kwargs={"pk": self.object.pk} ) class ExecutableTaskTypeDetail(BaseTaskTypeDetail): """A view for a specific executable task type.""" model = ExecutableTaskType task_class = EXECUTABLE_TASK template_name = "frontend/executabletasktype_detail.html" def get_formatted_command_to_run(self): """Get a nice representation of the command to run. This is aware of executable task type's json_file_option. """ this_tasktype = self.get_object() # Build up the command to run as we go command_to_run = this_tasktype.command_to_run # Add in the JSON args if there are any if this_tasktype.required_arguments: if this_tasktype.json_file_option: command_to_run += ( " " + this_tasktype.json_file_option + " json_args_file.json" ) else: command_to_run += " '{ json_args }'" return command_to_run def get_taskinstances(self): """Get a queryset of the task type's instances.""" return self.get_object().executabletaskinstance_set.all() def get_taskinstance_urlname(self): """Get the URL name for task instances.""" return "executabletaskinstance-detail" def get_taskinstance_create_urlname(self): """Get the URL name for creating task instances.""" return "executabletaskinstance-create" class ExecutableTaskTypeUpdate( ExecutableTaskTypeFormViewMixin, BaseTaskTypeUpdate ): """A view for updating an executable task type.""" model = ExecutableTaskType template_name = "frontend/executabletasktype_update.html" def get_success_url(self): """Redirect to detail page.""" return reverse_lazy( "executabletasktype-detail", kwargs={"pk": self.object.pk} ) class ExecutableTaskTypeDelete(BaseTaskTypeDelete): """A view for deleting an executable task type.""" model = ExecutableTaskType success_url = reverse_lazy("executabletasktype-list")
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,321
saltant-org/saltant
refs/heads/master
/saltant/urls.py
"""saltant URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path from frontend.views import ( BadRequest400, PermissionDenied403, PageNotFound404, ServerError500, ) handler400 = BadRequest400.as_view() handler403 = PermissionDenied403.as_view() handler404 = PageNotFound404.as_view() handler500 = ServerError500.as_view() urlpatterns = [ path("", include("frontend.urls")), path("admin/", admin.site.urls, name="admin"), path("api/", include("tasksapi.urls")), ] # Serve static files properly during development (see # https://docs.djangoproject.com/en/2.0/howto/static-files/) if settings.DEBUG: urlpatterns += static( settings.STATIC_URL, document_root=settings.STATIC_ROOT )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,322
saltant-org/saltant
refs/heads/master
/frontend/context_processors.py
"""Give common information to templates.""" import os def export_env_vars(_): """Let templates know about common things.""" data = {} data["DJANGO_BASE_URL"] = os.environ["DJANGO_BASE_URL"] data["FLOWER_URL"] = os.environ["FLOWER_URL"] data["PROJECT_NAME"] = os.environ["PROJECT_NAME"] data["PROJECT_USES_ROLLBAR"] = os.environ["PROJECT_USES_ROLLBAR"] data["RABBITMQ_MANAGEMENT_URL"] = os.environ["RABBITMQ_MANAGEMENT_URL"] data["ROLLBAR_PROJECT_URL"] = os.environ["ROLLBAR_PROJECT_URL"] return data
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,323
saltant-org/saltant
refs/heads/master
/tasksapi/migrations/0002_auto_20181204_2210.py
# Generated by Django 2.1.2 on 2018-12-05 06:10 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('tasksapi', '0001_initial'), ] operations = [ migrations.AlterField( model_name='containertaskinstance', name='task_queue', field=models.ForeignKey(help_text='The queue this instance runs on.', on_delete=django.db.models.deletion.CASCADE, to='tasksapi.TaskQueue'), ), migrations.AlterField( model_name='containertaskinstance', name='task_type', field=models.ForeignKey(help_text='The task type for which this is an instance.', on_delete=django.db.models.deletion.CASCADE, to='tasksapi.ContainerTaskType'), ), migrations.AlterField( model_name='containertaskinstance', name='user', field=models.ForeignKey(help_text='The author of this instance.', null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='containertasktype', name='user', field=models.ForeignKey(help_text='The author of this task.', null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='executabletaskinstance', name='task_queue', field=models.ForeignKey(help_text='The queue this instance runs on.', on_delete=django.db.models.deletion.CASCADE, to='tasksapi.TaskQueue'), ), migrations.AlterField( model_name='executabletaskinstance', name='task_type', field=models.ForeignKey(help_text='The task type for which this is an instance.', on_delete=django.db.models.deletion.CASCADE, to='tasksapi.ExecutableTaskType'), ), migrations.AlterField( model_name='executabletaskinstance', name='user', field=models.ForeignKey(help_text='The author of this instance.', null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='executabletasktype', name='user', field=models.ForeignKey(help_text='The author of this task.', null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL), ), migrations.AlterField( model_name='taskqueue', name='user', field=models.ForeignKey(help_text='The creator of the queue.', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,324
saltant-org/saltant
refs/heads/master
/tasksapi/paginators.py
"""Contains paginators for the API. See http://www.django-rest-framework.org/api-guide/pagination/ """ from rest_framework.pagination import PageNumberPagination class PageNumberVariableSizePagination(PageNumberPagination): """A paginator that allows for variable page size.""" page_size_query_param = "page_size" class LargeResultsSetPagination(PageNumberVariableSizePagination): """A paginator that shows lots of results.""" page_size = 100 class SmallResultsSetPagination(PageNumberVariableSizePagination): """A paginator that shows _some_ results.""" page_size = 10
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,325
saltant-org/saltant
refs/heads/master
/tasksapi/serializers/abstract_tasks.py
"""Contains serializers for the abstract tasks models.""" from django.core.exceptions import ValidationError from rest_framework import serializers from tasksapi.models import AbstractTaskInstance, AbstractTaskType from tasksapi.utils import get_allowed_queues_sorted class AbstractTaskTypeSerializer(serializers.ModelSerializer): """A serializer for a task type.""" user = serializers.SlugRelatedField(slug_field="username", read_only=True) class Meta: # Make sure you change this in the subclass serializer! model = AbstractTaskType fields = "__all__" def to_internal_value(self, data): """Inject the user into validation data. Need to inject it here before the UniqueTogether validator runs. See discussion here: https://stackoverflow.com/questions/27591574/order-of-serializer-validation-in-django-rest-framework. """ data = super().to_internal_value(data) data["user"] = self.context["request"].user return data def validate(self, attrs): """Ensure the argument fields passed in are valid. Relies on the model's clean method. Note that the object-level validation used here effectively precludes being able to validate partial updates, due to lack of support in DRF for object-level validation in partial updates. """ # Call parent validate method attrs = super().validate(attrs) # Be careful with optional arguments try: required_args = attrs["required_arguments"] assert required_args is not None except (KeyError, AssertionError): required_args = [] try: default_vals = attrs["required_arguments_default_values"] assert default_vals is not None except (KeyError, AssertionError): default_vals = {} try: environment_vars = attrs["environment_variables"] assert environment_vars is not None except (KeyError, AssertionError): environment_vars = [] # Test instance try: test_type_instance = AbstractTaskType( user=attrs["user"], name=attrs["name"], command_to_run=attrs["command_to_run"], environment_variables=environment_vars, required_arguments_default_values=default_vals, required_arguments=required_args, ) test_type_instance.clean() except ValidationError as e: raise serializers.ValidationError(str(e)) return attrs class AbstractTaskInstanceSerializer(serializers.ModelSerializer): """A serializer for reading a task instance.""" user = serializers.SlugRelatedField(slug_field="username", read_only=True) def __init__(self, *args, **kwargs): """Initialize the queryset for task queues.""" # Call parent constructor super().__init__(*args, **kwargs) # Customize the queryset of the task queues to only include # allowed queues. If a bad task type for a queue is chosen the # task instance model validation will deal with it; we can't do # anything more here without having a particular task in hand. if "context" in kwargs: self.fields["task_queue"].queryset = get_allowed_queues_sorted( user=kwargs["context"]["request"].user ) class Meta: # Make sure you change this in the subclass serializer! model = AbstractTaskInstance read_only_fields = ("state",) fields = "__all__" def validate(self, attrs): """Ensure the arguments fields passed in are valid. Relies on the model's clean method. Note that the object-level validation used here effectively precludes being able to validate partial updates, due to lack of support in DRF for object-level validation in partial updates. """ # Call parent validate method attrs = super().validate(attrs) # Be careful with optional arguments try: arguments = attrs["arguments"] assert arguments is not None except (KeyError, AssertionError): attrs["arguments"] = {} # Make sure to do a test like the following in the subclass' # validate method. Call super() first, please :) # # try: # test_instance = AbstractTaskInstance( # user=self.context['request'].user, # task_type=attrs['task_type'], # task_queue=attrs['task_queue'], # arguments=attrs['arguments'],) # test_instance.clean() # except ValidationError as e: # raise serializers.ValidationError(str(e)) return attrs
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,326
saltant-org/saltant
refs/heads/master
/saltant/__init__.py
"""Things here get run first. This initializes the Celery app, and makes sure that environment variables are loaded for it. """ from __future__ import absolute_import # for Python 2.x workers import os import warnings import dotenv # Load environment variables from .env file with warnings.catch_warnings(): warnings.filterwarnings("error") try: dotenv.read_dotenv( os.path.join(os.path.dirname(os.path.dirname(__file__)), ".env") ) except UserWarning: raise FileNotFoundError("Could not find .env!") # Initialize Celery (see # http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html) from saltant.celery import app as celery_app __all__ = ("celery_app",)
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,327
saltant-org/saltant
refs/heads/master
/frontend/views/mixins.py
"""Contains CBV mixins for frontend views.""" from frontend.constants import SELECTED_TASK_CLASS from frontend.widgets import JSONEditorWidget from tasksapi.constants import CONTAINER_TASK, EXECUTABLE_TASK class IsAdminOrOwnerOnlyMixin: """Allow access views only for admin or associated object user. This is analogous to the IsAdminOrOwnerThenWriteElseReadOnly permissions class in the tasks API. """ def dispatch(self, request, *args, **kwargs): """Call parent dispatch method only if user is allowed.""" if request.user.is_superuser or request.user == self.get_object().user: return super().dispatch(request, *args, **kwargs) return self.handle_no_permission() class UserFormViewMixin: """Provides the user as initial data to formviews.""" def get_initial(self): """Automatically fill in the user.""" initial = super().get_initial() return {**initial, "user": self.request.user.pk} class DisableUserSelectFormViewMixin: """Don't let the user form field be editable.""" def get_form(self, form_class=None): """Set the user field to disabled.""" form = super().get_form(form_class) form.fields["user"].disabled = True return form class TaskTypeFormViewMixin: """Set specific form settings for task types.""" def get_form(self, form_class=None): """Tweak the widgets and ordering.""" form = super().get_form(form_class) # Adjust the ordering. See # https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.field_order. # Unrecognized fields will be ignored, so we can set order for # all of the subclasses' fields, even if not all occur in each # subclass. form.field_order = [ "name", "description", "user", "container_type", "container_image", "logs_path", "results_path", "command_to_run", "json_file_option", "required_arguments", "required_arguments_default_values", "environment_variables", ] form.order_fields(form.field_order) # Use JSON Editor widget for JSON fields form.fields["environment_variables"].widget = JSONEditorWidget() form.fields["required_arguments"].widget = JSONEditorWidget() form.fields[ "required_arguments_default_values" ].widget = JSONEditorWidget() # Use monospace on code bits form.fields["command_to_run"].widget.attrs.update( style="font-family: monospace" ) return form class ContainerTaskTypeFormViewMixin: """Set widgets for container task type fields.""" def get_form(self, form_class=None): """Tweak the widget for container stuff.""" form = super().get_form(form_class) # Use monospace on code bits form.fields["container_image"].widget.attrs.update( style="font-family: monospace" ) form.fields["logs_path"].widget.attrs.update( style="font-family: monospace" ) form.fields["results_path"].widget.attrs.update( style="font-family: monospace" ) return form class ExecutableTaskTypeFormViewMixin: """Set widgets for container task type fields.""" def get_form(self, form_class=None): """Tweak the widget for the JSON file option.""" form = super().get_form(form_class) # Use monospace on code bits form.fields["json_file_option"].widget.attrs.update( style="font-family: monospace" ) return form class SetTaskClassCookieMixin: """Set the task class cookie when get is called.""" task_class = "fill me in" def get(self, *args, **kwargs): """Set the cookie if it's not what we want.""" if ( SELECTED_TASK_CLASS not in self.request.session or self.request.session[SELECTED_TASK_CLASS] != self.task_class ): self.request.session[SELECTED_TASK_CLASS] = self.task_class return super().get(*args, **kwargs) class SetContainerTaskClassCookieMixin(SetTaskClassCookieMixin): """Set cookie to prefer container task classes.""" task_class = CONTAINER_TASK class SetExecutableTaskClassCookieMixin(SetTaskClassCookieMixin): """Set cookie to prefer executable task classes.""" task_class = EXECUTABLE_TASK
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,328
saltant-org/saltant
refs/heads/master
/tasksapi/migrations/0003_auto_20181204_2211.py
# Generated by Django 2.1.2 on 2018-12-05 06:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tasksapi', '0002_auto_20181204_2210'), ] operations = [ migrations.AlterField( model_name='containertasktype', name='command_to_run', field=models.CharField(help_text='The command to run to execute the task. For example, "python /app/myscript.py". Note that shell operators will *not* be parsed; for example, | and &&. Arguments will be appended to the end of the command.', max_length=400), ), migrations.AlterField( model_name='executabletasktype', name='command_to_run', field=models.CharField(help_text='The command to run to execute the task. For example, "python /app/myscript.py". Note that shell operators will *not* be parsed; for example, | and &&. Arguments will be appended to the end of the command.', max_length=400), ), ]
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,329
saltant-org/saltant
refs/heads/master
/tasksapi/tasks/container_tasks.py
"""Contains task functionality for container-based tasks. Note that none of these functions themselves are registered with Celery; instead they are used by other functions which *are* registered with Celery. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import shlex import timeout_decorator from .utils import create_local_directory class SingularityPullFailure(Exception): """An error for when Singularity pulls fail.""" pass def run_docker_container_command( uuid, container_image, command_to_run, logs_path, results_path, env_vars_list, args_dict, ): """Launch an executable within a Docker container. Args: uuid: A string containing the uuid of the job being run. container_image: A string containing the name of the container to pull. command_to_run: A string containing the command to run. logs_path: A string (or None) containing the path of the directory containing the relevant logs within the container. results_path: A string (or None) containing the path of the directory containing any output files from the container. env_vars_list: A list of strings containing the environment variable names for the worker to consume from its environment. args_dict: A dictionary containing arguments and corresponding values. Raises: KeyError: An environment variable specified was not available in the worker's environment. """ # Import Docker. Useful to just import it here if we want to have # workers which *only* can support Singularity. import docker # Get the Docker client on the host machine (see # https://docker-py.readthedocs.io/en/stable/client.html#docker.client.from_env) client = docker.from_env() # Pull the Docker container. This pull in the latest version of the # container (with the specified tag if provided). client.images.pull(container_image) # Find out where to put the logs if logs_path is None: volumes_dict = {} else: host_logs_path = os.path.join( os.environ["WORKER_LOGS_DIRECTORY"], uuid ) volumes_dict = {host_logs_path: {"bind": logs_path, "mode": "rw"}} # Find out where to put the results if results_path is not None: host_results_path = os.path.join( os.environ["WORKER_RESULTS_DIRECTORY"], uuid ) volumes_dict[host_results_path] = {"bind": results_path, "mode": "rw"} # Consume necessary environment variables try: environment = {key: os.environ[key] for key in env_vars_list} except KeyError as e: raise KeyError( "Environment variable %s not present in the worker's environment!" % e ) # Also pass along the job's UUID environment["JOB_UUID"] = uuid # Compose the command to run if args_dict: command = "{executable} '{args}'".format( executable=command_to_run, args=json.dumps(args_dict) ) else: command = command_to_run # Run the executable client.containers.run( image=container_image, command=command, environment=environment, volumes=volumes_dict, ) def run_singularity_container_command( uuid, container_image, command_to_run, logs_path, results_path, env_vars_list, args_dict, ): """Launch an executable within a Singularity container. Args: uuid: A string containing the uuid of the job being run. container_image: A string containing the name of the container to pull. command_to_run: A string containing the command to run. logs_path: A string (or None) containing the path of the directory containing the relevant logs within the container. results_path: A string (or None) containing the path of the directory containing any output files from the container. env_vars_list: A list of strings containing the environment variable names for the worker to consume from its environment. args_dict: A dictionary containing arguments and corresponding values. Raises: KeyError: An environment variable specified was not available in the worker's environment. SingularityPullFailure: The Singularity pull could not complete with the specified timeout and number of retries. """ # Import Singularity library from spython.main import Client as client # Pull the specified container. This pull in the latest version of # the container (with the specified tag if provided). timeout = int(os.environ["SINGULARITY_PULL_TIMEOUT"]) num_retries = int(os.environ["SINGULARITY_PULL_RETRIES"]) # Put a timeout on the client pull method client.pull = timeout_decorator.timeout( timeout, timeout_exception=StopIteration )(client.pull) for retry in range(num_retries): try: singularity_image = client.pull( image=container_image, pull_folder=os.environ["WORKER_SINGULARITY_IMAGES_DIRECTORY"], name_by_commit=True, ) break except StopIteration: # If this is the last retry, raise an exception to indicate # a failed job if retry == num_retries - 1: raise SingularityPullFailure( ( "Could not pull {image_url} within " "{timeout} seconds after {num_retries} retries." ).format( image_url=container_image, timeout=timeout, num_retries=num_retries, ) ) # Find out where to put the logs if logs_path is None: bind_option = [] else: # Create the host logs path. This is required by the Singularity # library (though not the Docker library) host_logs_path = os.path.join( os.environ["WORKER_LOGS_DIRECTORY"], uuid ) create_local_directory(host_logs_path) # Build the bind option to pass on to Singularity bind_option = [ host_logs_path.rstrip("/") + ":" + logs_path.rstrip("/") ] # Find out where to put the results if results_path is not None: # Create the host results path host_results_path = os.path.join( os.environ["WORKER_RESULTS_DIRECTORY"], uuid ) create_local_directory(host_results_path) # Build the bind option to pass on to Singularity bind_option += [ host_results_path.rstrip("/") + ":" + results_path.rstrip("/") ] # Check for required environment variables. Note that by default # Singularity containers have access to their outside environment # variables, so we don't need to pass them along explicitly like we # need to for a Docker container. try: # Test to see that all keys are defined {key: os.environ[key] for key in env_vars_list} except KeyError as e: raise KeyError( "Environment variable %s not present in the worker's environment!" % e ) # Pass along the job's UUID os.environ["JOB_UUID"] = uuid # Compose the command to run command = shlex.split(command_to_run) if args_dict: command += [json.dumps(args_dict)] # Run the executable iter_ = client.execute( image=singularity_image, command=command, bind=bind_option, stream=True ) # Okay, here's some magic. The issue is that without stream=True in # the above call, there's no way of determining the return code of # the above operation, and so no way of knowing whether it failed. # However, with stream=True, it'll raise a # subprocess.CalledProcessError exception for any non-zero return # code. Great! But before we can get that exception triggered we # need to iterate through all of the command's stdout, which is what # the below (seemingly useless) loop does. for _ in iter_: pass
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,330
saltant-org/saltant
refs/heads/master
/saltant/celery.py
"""Celery app settings.""" from __future__ import absolute_import # for Python 2.x workers from celery import Celery from saltant import settings from tasksapi.tasks import run_task # Run the celery app app = Celery("saltant") # Set the config options specified in settings app.conf.update( broker_pool_limit=settings.CELERY_BROKER_POOL_LIMIT, broker_url=settings.CELERY_BROKER_URL, timezone=settings.CELERY_TIMEZONE, ) # Set SSL setting if we're using SSL try: app.conf.update(broker_use_ssl=settings.BROKER_USE_SSL) except AttributeError: pass # Let Rollbar report Celery worker errors (see # https://www.mattlayman.com/2017/django-celery-rollbar.html) if settings.PROJECT_USES_ROLLBAR and settings.IM_A_CELERY_WORKER: from celery.signals import task_failure import rollbar rollbar.init(**settings.ROLLBAR) def celery_base_data_hook(request, data): data["framework"] = "celery" rollbar.BASE_DATA_HOOK = celery_base_data_hook @task_failure.connect def handle_task_failure(**kw): rollbar.report_exc_info(extra_data=kw)
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,331
saltant-org/saltant
refs/heads/master
/frontend/constants.py
"""Constants for the frontend.""" from tasksapi.constants import ( CREATED, PUBLISHED, RUNNING, SUCCESSFUL, FAILED, TERMINATED, ) # Use this to translate from weekday number to day of week DATES_LIST = ["Mon", "Tues", "Weds", "Thurs", "Fri", "Sat", "Sun"] # States we care about emphasizing. The order here is signicant INTERESTING_STATES = (SUCCESSFUL, FAILED, TERMINATED, RUNNING, PUBLISHED) # Colours to represent states we care about. STATE_COLOR_DICT = { PUBLISHED: "#f2efea", RUNNING: "#9bdeac", SUCCESSFUL: "#a3d9ff", FAILED: "#ff6978", TERMINATED: "#fac8cd", } STATE_COLOR_LIGHTER_DICT = { CREATED: "#f9ebd1", PUBLISHED: "#f9ebd1", RUNNING: "#b5f4c6", SUCCESSFUL: "#bce3ff", FAILED: "#ffa8b0", TERMINATED: "#f9d9dc", } # Cookie attribute name of selected task class SELECTED_TASK_CLASS = "selected_task_class" # The default number of days to plot for task instances, provided there # are tasks within this range. DEFAULT_DAYS_TO_PLOT = 7
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,332
saltant-org/saltant
refs/heads/master
/tasksapi/models/__init__.py
"""Collect all models to "export" from this directory.""" from .abstract_tasks import AbstractTaskInstance, AbstractTaskType from .container_tasks import ContainerTaskInstance, ContainerTaskType from .executable_tasks import ExecutableTaskInstance, ExecutableTaskType from .task_queues import TaskQueue, TaskWhitelist from .users import User
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,333
saltant-org/saltant
refs/heads/master
/frontend/views/taskinstances_create.py
"""Views for creating and cloning task instances. There's a fair amount of complexity with these views, such that it warrants these views having a separate module. """ import json from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import ValidationError from django.http import HttpResponseRedirect from django.urls import reverse_lazy from django.views.generic import FormView from django.views.generic.detail import SingleObjectMixin from frontend.forms import BaseTaskInstanceCreateForm from tasksapi.models import ( ContainerTaskInstance, ContainerTaskType, ExecutableTaskInstance, ExecutableTaskType, ) from tasksapi.utils import get_allowed_queues_sorted # Match instance models with thet success URL names SUCCESS_URLNAMES_DICT = { ContainerTaskInstance: "containertaskinstance-detail", ExecutableTaskInstance: "executabletaskinstance-detail", } class BaseTaskInstanceBaseCreate( LoginRequiredMixin, SingleObjectMixin, FormView ): """A base view for creating task instances. There will be some important implementation differences depending on whether the operation is a clone or "from scratch" create. """ form_class = BaseTaskInstanceCreateForm # Fill these in in subclasses model = None context_object_name = None task_instance_model = None template_name = None def get_context_data(self, **kwargs): """Set up the context.""" # Let the view know about our "object". This could be done # someplace else, but it's done here for convenience. self.object = self.get_object() # And the task type kwargs["tasktype"] = self.get_tasktype() # Give the form to the context if "form" not in kwargs: kwargs["form"] = self.get_form() if self.request.method != "POST": # Add in some flourishes kwargs["form"] = self.customize_form(kwargs["form"]) return super().get_context_data(**kwargs) def customize_form(self, form): """Customize the form for GETs.""" # Restrict the task queues to ones the user can access form.fields["task_queue"].queryset = get_allowed_queues_sorted( self.request.user, self.get_tasktype() ) # Intialize the JSON arguments (how this is done depends on the # specific operation) form.fields["arguments"].initial = json.dumps( self.get_initial_arguments_json() ) return form def get_tasktype(self): """Get the relevant task type.""" # Define this in subclasses raise NotImplementedError def get_initial_arguments_json(self): """Get the initial arguments JSON.""" # Define this in subclasses raise NotImplementedError def post(self, request, *args, **kwargs): """Handle validation and creation of the task instance.""" # Get the form form = self.get_form() # Validate that the fields are filled in if not form.is_valid(): return self.form_invalid(form) # Now try creating the task instance try: this_instance = self.task_instance_model( user=self.request.user, task_type=self.get_tasktype(), task_queue=form.cleaned_data["task_queue"], arguments=form.cleaned_data["arguments"], ) if form.cleaned_data["name"]: this_instance.name = form.cleaned_data["name"] this_instance.clean() except ValidationError as e: # Didn't work! form.add_error(field=None, error=e) return self.form_invalid(form) # Save the instance this_instance.save() # Go to the detail page for the newly created task instance return HttpResponseRedirect( reverse_lazy( SUCCESS_URLNAMES_DICT[self.task_instance_model], kwargs={"uuid": this_instance.uuid}, ) ) class BaseTaskInstanceClone(BaseTaskInstanceBaseCreate): """A base view for cloning task instances.""" pk_url_kwarg = "uuid" context_object_name = "taskinstance" def get_tasktype(self): """Get the relevant task type.""" return self.get_object().task_type def get_initial_arguments_json(self): """Get the initial arguments JSON.""" return self.get_object().arguments def customize_form(self, form): """Add in a default task queue.""" # Call parent constructer form = super().customize_form(form) # Use the same queue as before by default form.fields["task_queue"].initial = self.get_object().task_queue # And name if self.get_object().name: form.fields["name"].initial = self.get_object().name return form class ContainerTaskInstanceClone(BaseTaskInstanceClone): """A view for cloning container task instances.""" model = ContainerTaskInstance task_instance_model = ContainerTaskInstance template_name = "frontend/containertaskinstance_clone.html" class ExecutableTaskInstanceClone(BaseTaskInstanceClone): """A view for cloning executable task instances.""" model = ExecutableTaskInstance task_instance_model = ExecutableTaskInstance template_name = "frontend/executabletaskinstance_clone.html" class BaseTaskInstanceCreate(BaseTaskInstanceBaseCreate): """A base view for creating task instances. This is done with respect to a given task type, which is this view's "object". """ context_object_name = "tasktype" def get_tasktype(self): """Get the relevant task type.""" return self.get_object() def get_initial_arguments_json(self): """Get the initial arguments JSON.""" tasktype = self.get_object() return { **{key: "value" for key in tasktype.required_arguments}, **tasktype.required_arguments_default_values, } def customize_form(self, form): """Tweak the help message for arguments field.""" # Call parent constructer form = super().customize_form(form) # Use the same queue as before by default form.fields["arguments"].help_text += ( " Arguments with no default values" ' are given the placeholder "value".' ) return form class ContainerTaskInstanceCreate(BaseTaskInstanceCreate): """A view for creating container task instances.""" model = ContainerTaskType task_instance_model = ContainerTaskInstance template_name = "frontend/containertaskinstance_create.html" class ExecutableTaskInstanceCreate(BaseTaskInstanceCreate): """A view for creating executable task instances.""" model = ExecutableTaskType task_instance_model = ExecutableTaskInstance template_name = "frontend/executabletaskinstance_create.html"
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,334
saltant-org/saltant
refs/heads/master
/tasksapi/models/users.py
"""Contains custom user model.""" from django.contrib.auth.models import AbstractUser from timezone_field import TimeZoneField class User(AbstractUser): """Custom user model.""" time_zone = TimeZoneField(default="America/Vancouver")
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,335
saltant-org/saltant
refs/heads/master
/tasksapi/tasks/executable_tasks.py
"""Contains task functionality for executable-based tasks. Note that none of these functions themselves are registered with Celery; instead they are used by other functions which *are* registered with Celery. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import shlex import subprocess from .utils import create_local_directory def run_executable_command( uuid, command_to_run, env_vars_list, args_dict, json_file_option ): """Launch an executable within a Docker container. Args: uuid: A string containing the uuid of the job being run. command_to_run: A string containing the command to run. env_vars_list: A list of strings containing the environment variable names for the worker to consume from its environment. args_dict: A dictionary containing arguments and corresponding values. json_file_option: A string (or None) containing the name of the command line option to specify a JSON-encoded file to read from. Raises: KeyError: An environment variable specified was not available in the worker's environment. subprocess.CalledProcessError: The process returned with a non-zero code. """ # Set up the host log directory for the job host_logs_path = os.path.join(os.environ["WORKER_LOGS_DIRECTORY"], uuid) create_local_directory(host_logs_path) # Build paths to stdout and stdin files host_stdout_log_path = os.path.join( host_logs_path, uuid + "-" + "stdout.txt" ) host_stderr_log_path = os.path.join( host_logs_path, uuid + "-" + "stderr.txt" ) # Consume necessary environment variables try: environment = {key: os.environ[key] for key in env_vars_list} except KeyError as e: raise KeyError( "Environment variable %s not present in the worker's environment!" % e ) # Also pass along the job's UUID environment["JOB_UUID"] = uuid # And PATH try: environment["PATH"] = os.environ["PATH"] except KeyError: # Okay, no path defined. No big deal pass # Interpret the command to run: split the string into # substrings "naturally" (see Python's shlex library); and # try to process anything that looks like an environment # variable. command_to_run = os.path.expandvars(command_to_run) cmd_list = shlex.split(command_to_run) # Add in arguments. Option 1: the task type wants to read the # arguments for a file; in this case we'll write the arguments to a # file and pass it to the specified json_file_option. Option 2: we # pass in the arguments JSON on the command line directly. Option 3: # there are no arguments, so we don't bother giving the command # anything. temp_files_to_clean_up = [] if args_dict: if json_file_option: # Write the the JSON args to a file, and then pass them # along to the command after the flag json_file_path = os.path.join( os.environ["WORKER_TEMP_DIRECTORY"], uuid + "_args.json" ) with open(json_file_path, "w") as f: print(json.dumps(args_dict), file=f) cmd_list += [json_file_option, json_file_path] # Clean up the temp file after we're done with it temp_files_to_clean_up += [json_file_path] elif args_dict: # Pass in JSON args directly cmd_list += [json.dumps(args_dict)] # Run the command try: with open(host_stdout_log_path, "w") as f_stdout: with open(host_stderr_log_path, "w") as f_stderr: # Run command subprocess.check_call( args=cmd_list, stdout=f_stdout, stderr=f_stderr, env=environment, ) finally: # Clean up any temp files for temp_file in temp_files_to_clean_up: os.remove(temp_file)
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,336
saltant-org/saltant
refs/heads/master
/tasksapi/tests/__init__.py
"""Import tests here so Django notices them.""" # Comment out any tests you don't want to run from .execution_tests.container_execution_tests import ContainerExecutionTests from .execution_tests.executable_execution_tests import ( ExecutableExecutionTests, ) from .models_tests.queue_permission_attrs_tests import ( TaskQueuePermissionAttributesTests, ) from .models_tests.queue_whitelist_tests import TaskQueueWhitelistTests from .requests_tests.basic_requests_tests import BasicHTTPRequestsTests from .requests_tests.user_editing_permissions_requests_tests import ( UserEditPermissionsRequestsTests, ) from .requests_tests.user_queue_permissions_requests_tests import ( UserQueuePermissionsRequestsTests, )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,337
saltant-org/saltant
refs/heads/master
/frontend/views/view_classes.py
"""Contains view classes.""" from django.conf import settings from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views.generic.base import RedirectView from frontend.constants import SELECTED_TASK_CLASS from tasksapi.constants import CONTAINER_TASK class TaskClassRedirect(LoginRequiredMixin, RedirectView): """Redirect to a particular page for the given task class. How the class is determined happens depends primarly on cookies, should they exist; and if they don't exist, by a server setting. Subclass this and fill in the relevant URL names. """ container_url_name = "fill me in" executable_url_name = "fill me in" def get_redirect_url(self, *args, **kwargs): """Lookup cookies and redirect.""" # Use cookie if SELECTED_TASK_CLASS in self.request.session: if self.request.session[SELECTED_TASK_CLASS] == CONTAINER_TASK: return reverse_lazy(self.container_url_name) return reverse_lazy(self.executable_url_name) # No cookie. Use default setting. if settings.DEFAULT_TASK_CLASS == CONTAINER_TASK: return reverse_lazy(self.container_url_name) return reverse_lazy(self.executable_url_name)
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,338
saltant-org/saltant
refs/heads/master
/frontend/views/__init__.py
"""Contains views for the frontend.""" # Make stuff in this package visible from .accounts import UserUpdate from .errors import ( BadRequest400, PermissionDenied403, PageNotFound404, ServerError500, ) from .misc import ( Home, About, TaskTypeRedirect, TaskInstanceRedirect, ContainerTaskInstanceCreateTaskTypeMenu, ExecutableTaskInstanceCreateTaskTypeMenu, ) from .queues import ( QueueList, QueueCreate, QueueDetail, QueueUpdate, QueueDelete, ) from .taskinstances import ( ContainerTaskInstanceList, ContainerTaskInstanceDetail, ContainerTaskInstanceRename, ContainerTaskInstanceStateUpdate, ContainerTaskInstanceTerminate, ContainerTaskInstanceDelete, ExecutableTaskInstanceList, ExecutableTaskInstanceDetail, ExecutableTaskInstanceRename, ExecutableTaskInstanceStateUpdate, ExecutableTaskInstanceTerminate, ExecutableTaskInstanceDelete, ) from .taskinstances_create import ( ContainerTaskInstanceClone, ContainerTaskInstanceCreate, ExecutableTaskInstanceClone, ExecutableTaskInstanceCreate, ) from .tasktypes import ( ContainerTaskTypeList, ContainerTaskTypeCreate, ContainerTaskTypeDetail, ContainerTaskTypeUpdate, ContainerTaskTypeDelete, ExecutableTaskTypeList, ExecutableTaskTypeCreate, ExecutableTaskTypeDetail, ExecutableTaskTypeUpdate, ExecutableTaskTypeDelete, ) from .whitelists import ( WhitelistList, WhitelistCreate, WhitelistDetail, WhitelistUpdate, WhitelistDelete, )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,339
saltant-org/saltant
refs/heads/master
/tasksapi/tasks/base_task.py
"""Contains the base task and signal handlers to register with Celery.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from celery import shared_task from celery.signals import ( after_task_publish, task_prerun, task_success, task_failure, task_revoked, ) import requests from tasksapi.constants import ( PUBLISHED, RUNNING, SUCCESSFUL, FAILED, TERMINATED, CONTAINER_TASK, EXECUTABLE_TASK, DOCKER, SINGULARITY, ) from .container_tasks import ( run_docker_container_command, run_singularity_container_command, ) from .executable_tasks import run_executable_command @shared_task def run_task( uuid, task_class, command_to_run, env_vars_list, args_dict, **task_class_kwargs ): """Launch an instance's job. This is the main function used to launch all tasks instance jobs. Args: uuid: A string containing the uuid of the job being run. task_class: A string defined in the constants module resprenting one of the task classes. command_to_run: A string containing the command to run. env_vars_list: A list of strings containing the environment variable names for the worker to consume from its environment. args_dict: A dictionary containing arguments and corresponding values. **task_class_kwargs: Arbitrary keywords arguments containing variables specific to the class of the task: For container task types you should be passing in logs_path: A string (or None) containing the path of the directory in the container containing the logs. results_path: A string (or None) containing the path of the directory in the container containing any output files. container_image: A string containing the name of the container to pull. container_type: A string defined in the constants module representing the type of container. For executable task types you should be passing in json_file_option: A string (or None) containing the name of the command line option to specify a JSON-encoded file to read from. Raises: NotImplementedError: An unsupported container type was passed in. """ # Determine which class of task to run if task_class == CONTAINER_TASK: # Unpack some variables logs_path = task_class_kwargs["logs_path"] results_path = task_class_kwargs["results_path"] container_image = task_class_kwargs["container_image"] container_type = task_class_kwargs["container_type"] # Determine whether to run a Docker or Singularity container if container_type == DOCKER: return run_docker_container_command( uuid=uuid, container_image=container_image, command_to_run=command_to_run, logs_path=logs_path, results_path=results_path, env_vars_list=env_vars_list, args_dict=args_dict, ) if container_type == SINGULARITY: return run_singularity_container_command( uuid=uuid, container_image=container_image, command_to_run=command_to_run, logs_path=logs_path, results_path=results_path, env_vars_list=env_vars_list, args_dict=args_dict, ) # Container type passed in is not supported! raise NotImplementedError( "Unsupported container type {}".format(container_type) ) elif task_class == EXECUTABLE_TASK: # Unpack some variables json_file_option = task_class_kwargs["json_file_option"] return run_executable_command( uuid=uuid, command_to_run=command_to_run, env_vars_list=env_vars_list, args_dict=args_dict, json_file_option=json_file_option, ) else: # Task class passed in is not supported! raise NotImplementedError( "Unsupported task class {}".format(task_class) ) def update_job(api_token, job_uuid, state): """Update the status of the job. Args: api_token: A string containing a valid token for the API. job_uuid: A string containing the UUID for the task instance to update. state: A string which must be one of the state constants. Returns: A requests.Response object containing the server's response to the HTTP request. """ # Form the API endpoint URL base_url = os.environ["DJANGO_BASE_URL"] endpoint_url_pieces = ( base_url, r"/api/updatetaskinstancestatus/", job_uuid, ) endpoint_url = "/".join(s.strip("/") for s in endpoint_url_pieces) + "/" # Make the HTTP request return requests.patch( endpoint_url, data={"state": state}, headers={"Authorization": "Token {}".format(api_token)}, ) @after_task_publish.connect def task_sent_handler(**kwargs): """Update the state of the task instance. Note that this function is processed by the process sending the task. Also note that the kwarg dictionaries given to the various handlers in general do not contain the same information, and if they do, then in general they will not share the same schema. Arg: kwargs: A dictionary containing information about the task instance. """ update_job( api_token=os.environ["API_AUTH_TOKEN"], job_uuid=str(kwargs["headers"]["id"]), state=PUBLISHED, ) @task_prerun.connect def task_prerun_handler(**kwargs): """Update the state of the task instance. Arg: kwargs: A dictionary containing information about the task instance. """ update_job( api_token=os.environ["API_AUTH_TOKEN"], job_uuid=str(kwargs["task_id"]), state=RUNNING, ) @task_success.connect def task_success_handler(**kwargs): """Update the state of the task instance. Arg: kwargs: A dictionary containing information about the task instance. """ update_job( api_token=os.environ["API_AUTH_TOKEN"], job_uuid=kwargs["sender"].request.id, state=SUCCESSFUL, ) @task_failure.connect def task_failure_handler(**kwargs): """Update the state of the task instance. Arg: kwargs: A dictionary containing information about the task instance. """ update_job( api_token=os.environ["API_AUTH_TOKEN"], job_uuid=kwargs["task_id"], state=FAILED, ) @task_revoked.connect def task_revoked_handler(**kwargs): """Update the state of the task instance. Arg: kwargs: A dictionary containing information about the task instance. """ update_job( api_token=os.environ["API_AUTH_TOKEN"], job_uuid=kwargs["request"].task_id, state=TERMINATED, )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,340
saltant-org/saltant
refs/heads/master
/frontend/templatetags/color_state.py
"""Add background color to a status.""" import json from django.template import Library from frontend.constants import STATE_COLOR_LIGHTER_DICT register = Library() @register.filter(is_safe=True) def color_state(state): """Add background colour to state text.""" return ( '<span style="background-color: %s; padding: 0 0.169em;">%s</span>' % (STATE_COLOR_LIGHTER_DICT[state], state) )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,341
saltant-org/saltant
refs/heads/master
/frontend/views/misc.py
"""Contains views that don't fit in other modules. The other views usually *directly* act on models, while these either don't, or do it indirectly. I guess "directly" isn't super well defined here, but whatever. """ from datetime import date, timedelta import json from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse_lazy from django.views.generic import FormView, TemplateView from frontend.forms import ( ContainerTaskTypeSelectForm, ExecutableTaskTypeSelectForm, ) from tasksapi.constants import RUNNING from tasksapi.models import ContainerTaskInstance, ExecutableTaskInstance from .utils_stats import ( determine_days_to_plot, get_job_state_data_date_enumerated, ) from .view_classes import TaskClassRedirect class Home(TemplateView): """A view for the home page.""" template_name = "frontend/index.html" def get_context_data(self, **kwargs): """Get some stats for the front page.""" context = super().get_context_data(**kwargs) # Get the number of jobs in progress context["running_jobs"] = ( ContainerTaskInstance.objects.filter(state=RUNNING).count() + ExecutableTaskInstance.objects.filter(state=RUNNING).count() ) # Find the number of days to plot from a query parameter. If the # query parameter wasn't passed in or is invalid, just use the # default. If there aren't any tasks within the default, then # show up to the week before the most recent task. try: days_to_plot_raw = self.request.GET.get("days") days_to_plot = int(float(days_to_plot_raw)) assert days_to_plot > 0 assert days_to_plot <= timedelta.max.days except (AssertionError, TypeError, ValueError): days_to_plot = determine_days_to_plot() # Pass this info to the context context["days_plotted"] = days_to_plot # If there are 7 or less days, label data with days of the week # (cf. ISO 8601 dates) use_week_days = bool(days_to_plot <= 7) # Get data for Chart.js today = date.today() last_week_date = date.today() - timedelta(days=days_to_plot - 1) chart_data = get_job_state_data_date_enumerated( start_date=last_week_date, end_date=today, use_day_of_week=use_week_days, ) # Add the Charts.js stuff to our context context["labels"] = json.dumps(chart_data["labels"]) context["datasets"] = json.dumps(chart_data["datasets"]) return context class About(TemplateView): """A view for the about page.""" template_name = "frontend/about.html" class TaskTypeRedirect(TaskClassRedirect): """Redirect to list page for a given task type class.""" container_url_name = "containertasktype-list" executable_url_name = "executabletasktype-list" class TaskInstanceRedirect(TaskClassRedirect): """Redirect to list page for a given task instance class.""" container_url_name = "containertaskinstance-list" executable_url_name = "executabletaskinstance-list" class BaseTaskInstanceCreateTaskTypeMenu(LoginRequiredMixin, FormView): """Base view for task instance creation submenu.""" form_class = None create_urlname = None template_name = "frontend/base_taskinstance_create_submenu.html" def form_valid(self, form): return HttpResponseRedirect( reverse_lazy( self.create_urlname, kwargs={"pk": form.cleaned_data["task_type"].pk}, ) ) class ContainerTaskInstanceCreateTaskTypeMenu( BaseTaskInstanceCreateTaskTypeMenu ): """View for container task instance creation submenu.""" form_class = ContainerTaskTypeSelectForm create_urlname = "containertaskinstance-create" class ExecutableTaskInstanceCreateTaskTypeMenu( BaseTaskInstanceCreateTaskTypeMenu ): """View for executable task instance creation submenu.""" form_class = ExecutableTaskTypeSelectForm create_urlname = "executabletaskinstance-create"
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,342
saltant-org/saltant
refs/heads/master
/tasksapi/middleware.py
"""Custom middleware for tasksapi.""" from django.utils import timezone from django.utils.deprecation import MiddlewareMixin class TimezoneMiddleware(MiddlewareMixin): """Make saltant timezone aware.""" def process_request(self, request): """Get the timezone from the user's profile. Provided a user is logged in. """ try: timezone.activate(request.user.time_zone) except AttributeError: timezone.deactivate()
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,343
saltant-org/saltant
refs/heads/master
/frontend/forms.py
"""Forms for the frontend.""" from django import forms from tasksapi.models import ContainerTaskType, ExecutableTaskType, TaskQueue from .widgets import JSONEditorWidget class BaseTaskInstanceCreateForm(forms.Form): """Base form for creating both types of task instances.""" name = forms.CharField( required=False, help_text="An optional name for the task instance" ) task_queue = forms.ModelChoiceField( queryset=TaskQueue.objects.all(), label="Queue", help_text="The queue to run the task instance on.", ) arguments = forms.CharField( widget=JSONEditorWidget(), help_text="Arguments required by the task type as JSON.", ) # When creating a task instance, one must first specify a task type to # base it off of. (Technically they could do so in the same form, but # that's more work given the initial data setting features.) class ContainerTaskTypeSelectForm(forms.Form): """Form for selecting a container task type.""" task_type = forms.ModelChoiceField( queryset=ContainerTaskType.objects.all() ) class ExecutableTaskTypeSelectForm(forms.Form): """Form for selecting an executable task type.""" task_type = forms.ModelChoiceField( queryset=ExecutableTaskType.objects.all() )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,344
saltant-org/saltant
refs/heads/master
/tasksapi/models/executable_tasks.py
"""Models to represent task types and instances which run commands directly.""" from django.db import models from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.utils import timezone from tasksapi.constants import SUCCESSFUL, FAILED, EXECUTABLE_TASK from tasksapi.tasks import run_task from .abstract_tasks import AbstractTaskInstance, AbstractTaskType class ExecutableTaskType(AbstractTaskType): """A type of task to create instances which run commands directly.""" json_file_option = models.CharField( max_length=50, blank=True, null=True, default=None, verbose_name="JSON file option", help_text=( "The name of a command line option, e.g., --json-file, " "which accepts a JSON-encoded file for the command to run. " "If this value is non-null, then the instance's JSON arguments " "are written to a file and this file is passed to the command " "(cf. normal behaviour where the JSON arguments are passed as " "a single argument to the task)." ), ) class ExecutableTaskInstance(AbstractTaskInstance): """A running instance of an executable task type.""" task_type = models.ForeignKey( ExecutableTaskType, on_delete=models.CASCADE, help_text="The task type for which this is an instance.", ) @receiver(pre_save, sender=ExecutableTaskInstance) def executable_task_instance_pre_save_handler(instance, **_): """Adds additional behavior before saving a task instance. If the state is about to be changed to a finished change, update the datetime finished field. Args: instance: The task instance about to be saved. """ if instance.state in (SUCCESSFUL, FAILED): instance.datetime_finished = timezone.now() @receiver(post_save, sender=ExecutableTaskInstance) def executable_task_instance_post_save_handler(instance, created, **_): """Adds additional behavior after saving a task instance. Right now this just queues up the task instance upon creation. Args: instance: The task instance just saved. created: A boolean telling us if the task instance was just created (cf. modified). """ # Only start the job if the instance was just created if created: kwargs = { "uuid": instance.uuid, "task_class": EXECUTABLE_TASK, "command_to_run": instance.task_type.command_to_run, "env_vars_list": instance.task_type.environment_variables, "args_dict": instance.arguments, "json_file_option": instance.task_type.json_file_option, } run_task.apply_async( kwargs=kwargs, queue=instance.task_queue.name, task_id=str(instance.uuid), )
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,345
saltant-org/saltant
refs/heads/master
/tasksapi/migrations/0006_auto_20181217_1212.py
# Generated by Django 2.1.2 on 2018-12-17 20:12 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('tasksapi', '0005_auto_20181211_1415'), ] operations = [ migrations.CreateModel( name='TaskWhitelist', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='The name of the whitelist.', max_length=50, unique=True)), ('description', models.TextField(blank=True, help_text='A description of the whitelist.')), ('user', models.ForeignKey(help_text='The maintainer of the whitelist.', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('whitelisted_container_task_types', models.ManyToManyField(blank=True, help_text='The set of container task types to whitelist.', to='tasksapi.ContainerTaskType')), ('whitelisted_executable_task_types', models.ManyToManyField(blank=True, help_text='The set of executable task types to whitelist.', to='tasksapi.ExecutableTaskType')), ], options={ 'ordering': ['id'], }, ), migrations.AddField( model_name='taskqueue', name='whitelists', field=models.ManyToManyField(blank=True, help_text='A set of task whitelists.', to='tasksapi.TaskWhitelist'), ), ]
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,346
saltant-org/saltant
refs/heads/master
/frontend/views/queues.py
"""Views for queues.""" from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views.generic import ( CreateView, DeleteView, DetailView, ListView, UpdateView, ) from tasksapi.models import TaskQueue from .mixins import ( DisableUserSelectFormViewMixin, IsAdminOrOwnerOnlyMixin, UserFormViewMixin, ) class QueueList(LoginRequiredMixin, ListView): """A view for listing queues.""" model = TaskQueue template_name = "frontend/queue_list.html" class QueueCreate( UserFormViewMixin, DisableUserSelectFormViewMixin, LoginRequiredMixin, CreateView, ): """A view for creating a queue.""" model = TaskQueue fields = "__all__" template_name = "frontend/queue_create.html" def get_success_url(self): """Redirect to queue detail page.""" return reverse_lazy("queue-detail", kwargs={"pk": self.object.pk}) class QueueDetail(LoginRequiredMixin, DetailView): """A view for a specific queue.""" model = TaskQueue template_name = "frontend/queue_detail.html" class QueueUpdate( LoginRequiredMixin, IsAdminOrOwnerOnlyMixin, DisableUserSelectFormViewMixin, UpdateView, ): """A view for deleting a queue.""" model = TaskQueue fields = "__all__" template_name = "frontend/queue_update.html" def get_success_url(self): """Redirect to queue detail page.""" return reverse_lazy("queue-detail", kwargs={"pk": self.object.pk}) class QueueDelete(LoginRequiredMixin, IsAdminOrOwnerOnlyMixin, DeleteView): """A view for deleting a queue.""" model = TaskQueue template_name = "frontend/queue_delete.html" success_url = reverse_lazy("queue-list")
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,347
saltant-org/saltant
refs/heads/master
/tasksapi/models/validators.py
"""Contains validators for task models.""" def task_instance_args_are_valid(instance, fill_missing_args=False): """Determines whether a task instance's arguments are valid. The arguments are valid if the instance's argument includes all of its task type's required arguments (but not necessarily the arguments for which a default value exists). Arg: instance: A task instance instance. (Yikes!) fill_missing_args: A boolean determining whether to fill in any missing arguments in the instance with default values. Returns: A tuple containing a boolean and a string, where the boolean signals whether the arguments are valid and the string explains why, in the case that the boolean is False (otherwise it's an empty string). """ # Validate an instance's args against its required args. task_type_required_args = instance.task_type.required_arguments task_type_default_vals = ( instance.task_type.required_arguments_default_values ) instance_arg_keys = instance.arguments.keys() for required_arg in task_type_required_args: # Check if the required argument is provided if required_arg not in instance_arg_keys: # Required argument not provided. Check if default argument # value exists. if required_arg not in task_type_default_vals: # No default exists return ( False, "required argument '%s' not provided!" % required_arg, ) # Fill in the default value if we're told to if fill_missing_args: instance.arguments[required_arg] = task_type_default_vals[ required_arg ] # Valid return (True, "") def task_type_args_are_valid(instance): """Determines whether a task type's argument fields are valid. The argument fields are valid if the argument keys in the required_arguments_default_values field are a subset of its required arguments. Arg: instance: A task type instance. Returns: A tuple containing a boolean and a string, where the boolean signals whether the arguments are valid and the string explains why, in the case that the boolean is False (otherwise it's an empty string). """ # Ensure that the default arguments form a subset of the required # arguments if not set(instance.required_arguments_default_values.keys()).issubset( set(instance.required_arguments) ): return (False, "default arguments not a subset of required arguments") # Valid return (True, "")
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,348
saltant-org/saltant
refs/heads/master
/frontend/urls.py
"""Contains URLs for the front-end.""" from django.contrib.auth import views as auth_views from django.urls import path, reverse_lazy from frontend import views urlpatterns = [ path(r"", views.Home.as_view(), name="home"), path(r"about/", views.About.as_view(), name="about"), path(r"account/", views.UserUpdate.as_view(), name="account"), path( r"account/edit-profile/", views.UserUpdate.as_view(), name="account-edit-profile", ), path( r"account/change-password/", auth_views.PasswordChangeView.as_view( template_name="frontend/account_change_password.html", success_url=reverse_lazy("account"), ), name="account-change-password", ), path( r"containertaskinstances/", views.ContainerTaskInstanceList.as_view(), name="containertaskinstance-list", ), path( r"containertaskinstances/create/", views.ContainerTaskInstanceCreateTaskTypeMenu.as_view(), name="containertaskinstance-create-menu", ), path( r"containertaskinstances/<uuid:uuid>/", views.ContainerTaskInstanceDetail.as_view(), name="containertaskinstance-detail", ), path( r"containertaskinstances/<uuid:uuid>/rename/", views.ContainerTaskInstanceRename.as_view(), name="containertaskinstance-rename", ), path( r"containertaskinstances/<uuid:uuid>/clone/", views.ContainerTaskInstanceClone.as_view(), name="containertaskinstance-clone", ), path( r"containertaskinstances/<uuid:uuid>/state-override/", views.ContainerTaskInstanceStateUpdate.as_view(), name="containertaskinstance-stateupdate", ), path( r"containertaskinstances/<uuid:uuid>/terminate/", views.ContainerTaskInstanceTerminate.as_view(), name="containertaskinstance-terminate", ), path( r"containertaskinstances/<uuid:uuid>/delete/", views.ContainerTaskInstanceDelete.as_view(), name="containertaskinstance-delete", ), path( r"containertasktypes/", views.ContainerTaskTypeList.as_view(), name="containertasktype-list", ), path( r"containertasktypes/create/", views.ContainerTaskTypeCreate.as_view(), name="containertasktype-create", ), path( r"containertasktypes/<int:pk>/", views.ContainerTaskTypeDetail.as_view(), name="containertasktype-detail", ), path( r"containertasktypes/<int:pk>/create-taskinstance/", views.ContainerTaskInstanceCreate.as_view(), name="containertaskinstance-create", ), path( r"containertasktypes/<int:pk>/delete/", views.ContainerTaskTypeDelete.as_view(), name="containertasktype-delete", ), path( r"containertasktypes/<int:pk>/update/", views.ContainerTaskTypeUpdate.as_view(), name="containertasktype-update", ), path( r"executabletaskinstances/", views.ExecutableTaskInstanceList.as_view(), name="executabletaskinstance-list", ), path( r"executabletaskinstances/create/", views.ExecutableTaskInstanceCreateTaskTypeMenu.as_view(), name="executabletaskinstance-create-menu", ), path( r"executabletaskinstances/<uuid:uuid>/", views.ExecutableTaskInstanceDetail.as_view(), name="executabletaskinstance-detail", ), path( r"executabletaskinstances/<uuid:uuid>/rename/", views.ExecutableTaskInstanceRename.as_view(), name="executabletaskinstance-rename", ), path( r"executabletaskinstances/<uuid:uuid>/clone/", views.ExecutableTaskInstanceClone.as_view(), name="executabletaskinstance-clone", ), path( r"executabletaskinstances/<uuid:uuid>/state-override/", views.ExecutableTaskInstanceStateUpdate.as_view(), name="executabletaskinstance-stateupdate", ), path( r"executabletaskinstances/<uuid:uuid>/terminate/", views.ExecutableTaskInstanceTerminate.as_view(), name="executabletaskinstance-terminate", ), path( r"executabletaskinstances/<uuid:uuid>/delete/", views.ExecutableTaskInstanceDelete.as_view(), name="executabletaskinstance-delete", ), path( r"executabletasktypes/", views.ExecutableTaskTypeList.as_view(), name="executabletasktype-list", ), path( r"executabletasktypes/create/", views.ExecutableTaskTypeCreate.as_view(), name="executabletasktype-create", ), path( r"executabletasktypes/<int:pk>/", views.ExecutableTaskTypeDetail.as_view(), name="executabletasktype-detail", ), path( r"executabletasktypes/<int:pk>/create-taskinstance/", views.ExecutableTaskInstanceCreate.as_view(), name="executabletaskinstance-create", ), path( r"executabletasktypes/<int:pk>/delete/", views.ExecutableTaskTypeDelete.as_view(), name="executabletasktype-delete", ), path( r"executabletasktypes/<int:pk>/update/", views.ExecutableTaskTypeUpdate.as_view(), name="executabletasktype-update", ), path( r"login/", auth_views.LoginView.as_view(template_name="frontend/login.html"), name="login", ), path(r"logout/", auth_views.LogoutView.as_view(), name="logout"), path( r"taskinstances/", views.TaskInstanceRedirect.as_view(), name="taskinstance-redirect", ), path(r"taskqueues/", views.QueueList.as_view(), name="queue-list"), path( r"taskqueues/create/", views.QueueCreate.as_view(), name="queue-create" ), path( r"taskqueues/<int:pk>/", views.QueueDetail.as_view(), name="queue-detail", ), path( r"taskqueues/<int:pk>/update/", views.QueueUpdate.as_view(), name="queue-update", ), path( r"taskqueues/<int:pk>/delete/", views.QueueDelete.as_view(), name="queue-delete", ), path( r"taskwhitelists/", views.WhitelistList.as_view(), name="whitelist-list", ), path( r"taskwhitelists/create/", views.WhitelistCreate.as_view(), name="whitelist-create", ), path( r"taskwhitelists/<int:pk>/", views.WhitelistDetail.as_view(), name="whitelist-detail", ), path( r"taskwhitelists/<int:pk>/update/", views.WhitelistUpdate.as_view(), name="whitelist-update", ), path( r"taskwhitelists/<int:pk>/delete/", views.WhitelistDelete.as_view(), name="whitelist-delete", ), path( r"tasktypes/", views.TaskTypeRedirect.as_view(), name="tasktype-redirect", ), ]
{"/tasksapi/tests/execution_tests/executable_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/tasksapi/utils.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/frontend/views/taskinstances.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py", "/frontend/views/utils_logs.py"], "/tasksapi/admin.py": ["/tasksapi/models/__init__.py"], "/frontend/views/utils.py": ["/frontend/views/utils_stats.py"], "/tasksapi/serializers/task_instance_update.py": ["/tasksapi/constants.py"], "/tasksapi/serializers/users.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/execution_tests/container_execution_tests.py": ["/tasksapi/tasks/__init__.py"], "/frontend/views/whitelists.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"], "/frontend/views/utils_stats.py": ["/frontend/constants.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py"], "/tasksapi/tests/requests_tests/utils.py": ["/tasksapi/constants.py"], "/tasksapi/tests/models_tests/queue_whitelist_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/utils.py": ["/tasksapi/constants.py"], "/tasksapi/filters.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/task_queues.py": ["/tasksapi/models/users.py", "/tasksapi/models/utils.py"], "/tasksapi/tasks/__init__.py": ["/tasksapi/tasks/base_task.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/tasksapi/tests/requests_tests/basic_requests_tests.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/tasksapi/tests/requests_tests/utils.py"], "/tasksapi/models/container_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/tasksapi/serializers/container_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/serializers/abstract_tasks.py"], "/tasksapi/serializers/task_queues.py": ["/tasksapi/models/__init__.py"], "/tasksapi/models/abstract_tasks.py": ["/tasksapi/constants.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py", "/tasksapi/models/utils.py", "/tasksapi/models/validators.py"], "/tasksapi/serializers/__init__.py": ["/tasksapi/serializers/container_tasks.py", "/tasksapi/serializers/task_instance_update.py", "/tasksapi/serializers/task_queues.py", "/tasksapi/serializers/users.py"], "/frontend/views/accounts.py": ["/tasksapi/models/__init__.py"], "/tasksapi/views.py": ["/tasksapi/filters.py", "/tasksapi/models/__init__.py", "/tasksapi/paginators.py", "/tasksapi/permissions.py", "/tasksapi/serializers/__init__.py"], "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py": ["/tasksapi/tests/requests_tests/utils.py"], "/frontend/views/tasktypes.py": ["/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/mixins.py", "/frontend/views/utils.py"], "/saltant/urls.py": ["/frontend/views/__init__.py"], "/tasksapi/serializers/abstract_tasks.py": ["/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/saltant/__init__.py": ["/saltant/celery.py"], "/frontend/views/mixins.py": ["/frontend/constants.py", "/frontend/widgets.py", "/tasksapi/constants.py"], "/tasksapi/tasks/container_tasks.py": ["/tasksapi/tasks/utils.py"], "/saltant/celery.py": ["/saltant/__init__.py", "/tasksapi/tasks/__init__.py"], "/frontend/constants.py": ["/tasksapi/constants.py"], "/tasksapi/models/__init__.py": ["/tasksapi/models/abstract_tasks.py", "/tasksapi/models/container_tasks.py", "/tasksapi/models/executable_tasks.py", "/tasksapi/models/task_queues.py", "/tasksapi/models/users.py"], "/frontend/views/taskinstances_create.py": ["/frontend/forms.py", "/tasksapi/models/__init__.py", "/tasksapi/utils.py"], "/tasksapi/tasks/executable_tasks.py": ["/tasksapi/tasks/utils.py"], "/tasksapi/tests/__init__.py": ["/tasksapi/tests/execution_tests/container_execution_tests.py", "/tasksapi/tests/execution_tests/executable_execution_tests.py", "/tasksapi/tests/models_tests/queue_permission_attrs_tests.py", "/tasksapi/tests/models_tests/queue_whitelist_tests.py", "/tasksapi/tests/requests_tests/basic_requests_tests.py", "/tasksapi/tests/requests_tests/user_editing_permissions_requests_tests.py", "/tasksapi/tests/requests_tests/user_queue_permissions_requests_tests.py"], "/frontend/views/view_classes.py": ["/frontend/constants.py", "/tasksapi/constants.py"], "/frontend/views/__init__.py": ["/frontend/views/accounts.py", "/frontend/views/errors.py", "/frontend/views/misc.py", "/frontend/views/queues.py", "/frontend/views/taskinstances.py", "/frontend/views/taskinstances_create.py", "/frontend/views/tasktypes.py", "/frontend/views/whitelists.py"], "/tasksapi/tasks/base_task.py": ["/tasksapi/constants.py", "/tasksapi/tasks/container_tasks.py", "/tasksapi/tasks/executable_tasks.py"], "/frontend/templatetags/color_state.py": ["/frontend/constants.py"], "/frontend/views/misc.py": ["/frontend/forms.py", "/tasksapi/constants.py", "/tasksapi/models/__init__.py", "/frontend/views/utils_stats.py", "/frontend/views/view_classes.py"], "/frontend/forms.py": ["/tasksapi/models/__init__.py", "/frontend/widgets.py"], "/tasksapi/models/executable_tasks.py": ["/tasksapi/constants.py", "/tasksapi/tasks/__init__.py", "/tasksapi/models/abstract_tasks.py"], "/frontend/views/queues.py": ["/tasksapi/models/__init__.py", "/frontend/views/mixins.py"]}
56,349
NikoIina/discord_reddit_bot
refs/heads/main
/discord_bot.py
import discord from discord.ext import commands from config import bot_config, reddit_config from reddit import * bot = commands.Bot(command_prefix=bot_config['prefix']) @bot.event async def on_ready(): print(f'Bot connected as {bot.user}') @bot.event async def on_message(message): if message.content.startswith('-'): parts = message.content.split(' ') if parts[0] == '-top': text = await get_top(message, parts) for i in text: await message.channel.send(i) if parts[0] == '-hot': text = await get_hot(message, parts) for i in text: await message.channel.send(i) if parts[0] == '-new': text = await get_new(message, parts) for i in text: await message.channel.send(i) if parts[0] == '-help': await message.channel.send('Ask for reddit posts with -new/-top/-hot directory name number of posts. ' 'If you want to read specific post from those I sent you, send me a number') else: try: int(message.content) text = await get_body(message) if not text: await message.channel.send('This is it, that is the post!') else: await message.channel.send(text) except: if message.content == 'Try asking for help with -help': pass elif message.content == 'Ask for reddit posts with -new/-top/-hot directory name number of posts. ' \ 'If you want to read specific post from those I sent you, send me a number': pass else: await message.channel.send('Try asking for help with -help') bot.run(bot_config['token'])
{"/discord_bot.py": ["/config.py", "/reddit.py"], "/reddit.py": ["/config.py"]}
56,350
NikoIina/discord_reddit_bot
refs/heads/main
/config.py
bot_config = { 'token' : 'Your-Discord-Bot-Token', 'bot' : 'BotName', 'id' : id, 'prefix' : 'some-prefix' } reddit_config = { 'client_id' : 'your-app-client-id', 'secret' : 'your-app-secret', 'user_agent' : 'your-user-agent', 'username' : 'your-user-name', 'password' : 'your-password' }
{"/discord_bot.py": ["/config.py", "/reddit.py"], "/reddit.py": ["/config.py"]}
56,351
NikoIina/discord_reddit_bot
refs/heads/main
/reddit.py
import praw from config import reddit_config import pandas as pd reddit = praw.Reddit(client_id=reddit_config['client_id'], client_secret = reddit_config['secret'], user_agent = reddit_config['user_agent'], username= reddit_config['username'], password= reddit_config['password']) def create_topics(): global topics topics = {'title': [], 'url': [], 'body': [] } return topics def get_text(post): title = post.title url = post.url topics['title'].append(post.title) topics['url'].append(post.url) topics['body'].append(post.selftext) text = f'{title}, {url}' return text async def get_body(message): topics_data = pd.DataFrame(topics) body = topics_data['body'] text = body[int(message.content)] return text async def get_hot(message, parts): posts = reddit.subreddit(parts[1]) sends = [] create_topics() for post in posts.hot(limit=int(parts[2])): text = get_text(post) sends.append(text) return sends async def get_top(message, parts): posts = reddit.subreddit(parts[1]) sends = [] create_topics() for post in posts.top(limit=int(parts[2])): text = get_text(post) sends.append(text) return sends async def get_new(message, parts): posts = reddit.subreddit(parts[1]) sends = [] create_topics() for post in posts.new(limit=int(parts[2])): text = get_text(post) sends.append(text) return sends
{"/discord_bot.py": ["/config.py", "/reddit.py"], "/reddit.py": ["/config.py"]}
56,373
dkgee/tkspam3
refs/heads/master
/geo/cfg.py
""" 配置的config文件 """ # firefox config is_headless=False # user config username='15651025913' password='33183319ef' # url index_url=r'http://geo.ckcest.cn/' captcha_url=r'https://sso.ckcest.cn/portal/captchaCode' international_url=r'http://geo.ckcest.cn/scientific/InternationalData/list.html' literature_url=r'http://geo.ckcest.cn/scientific/literature/books.html' surveyreport_url=r'http://geo.ckcest.cn/scientific/literature/surveyreport/index.html' # international_status=True #是否开启 遥感影像 literature_status=False #是否开启 图书专著 surveyreport_status=False #是否开启 考察报告
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,374
dkgee/tkspam3
refs/heads/master
/pytorch/demo02/demo_02.py
# -*- coding: utf-8 -*- from __future__ import print_function, division import os import torch import pandas as pd from skimage import io, transform import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils #Ignore warnings import warnings warnings.filterwarnings("ignore") # interactive mode plt.ion() # 当前目录下data目录 landmarks_frame = pd.read_csv('data/faces/face_landmarks.csv') n=65 img_name = landmarks_frame.iloc[n, 0] landmarks = landmarks_frame.iloc[n, 1:].as_matrix() landmarks = landmarks.astype('float').reshape(-1, 2) print('Image name:{}'.format(img_name)) print('Landmarks shape:{}'.format(landmarks.shape)) print('First 4 Landmarks:{}'.format(landmarks[:4])) def show_landmarks(image, landmarks): """Show image with landmarks""" plt.imshow(image) plt.scatter(landmarks[:, 0], landmarks[:, 1], s=10, marker='.', c='r') plt.pause(0.001) # pause a bit so that plots are updated # plt.pause(0) # 暂停n秒后自动关闭,当n=0时不关闭窗口 # plt.figure() # show_landmarks(io.imread(os.path.join('data/faces', img_name)), landmarks) # plt.show() # # class FaceLandmarksDataset(Dataset): # """Face Landmarks dataset.""" # # def __init__(self, csv_file, root_dir, transform=None): # """ # :param csv_file: Path to the csv file with annotations. # :param root_dir: Directory with all the images. # :param transform: Optional transform to be applied on a sample. # """ # self.landmarks_frame = pd.read_csv(csv_file) # self.root_dir = root_dir # self.transform = transform # # def __len__(self): # return len(self.landmarks_frame) # # def __getitem__(self, idx): # img_name = os.path.join(self.root_dir, self.landmarks_frame.iloc[idx, 0]) # image = io.imread(img_name) # landmarks = self.landmarks_frame.iloc[idx, 1:].as_matrix() # landmarks = landmarks.astype('float').reshape(-1, 2) # sample = { 'image': image, 'landmarks': landmarks } # # if self.transform: # sample = self.transform(sample) # # return sample import pytorch.demo02.FaceLandmarksDataset as FaceLandmarksDataset face_dataset = FaceLandmarksDataset(csv_file='data/faces/face_landmarks.csv', root_dir='data/faces/') # fig = plt.figure() # for i in range(len(face_dataset)): # sample = face_dataset[i] # # print(i, sample['image'].shape, sample['landmarks'].shape) # # ax = plt.subplot(1, 4, i + 1) # plt.tight_layout() # ax.set_title('Sample #{}'.format(i)) # ax.axis('off') # show_landmarks(**sample) # # if i == 3: # plt.show() # # plt.pause(0) # break from pytorch.demo02.Rescale import Rescale, RandomCrop scale = Rescale(256) crop = RandomCrop(128) composed = transforms.Compose([Rescale(256), Rescale(224)]) # Apply each of the above transforms on sample. fig = plt.figure() sample = face_dataset[65] for i, tsfrm in enumerate([scale, crop, composed]): transforms_sample = tsfrm(sample) ax = plt.subplot(1, 3, i + 1) plt.tight_layout() ax.set_title(type(tsfrm).__name__) show_landmarks(**transforms_sample) plt.show()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,375
dkgee/tkspam3
refs/heads/master
/mlap/pca/test_logging.py
# -*- coding: utf-8 -*- import logging # path="name.log" # logging.basicConfig(level=logging.INFO,format='', filename=path, filemode='a') # format = logging.Formatter("%(asctime)s - %(message)s") # logging.info("this is error") logger = logging.getLogger() # logging对象 # fh = logging.FileHandler("test.log") # 文件对象 sh = logging.StreamHandler() # 输出流对象 fm = logging.Formatter('%(asctime)s-%(filename)s[line%(lineno)d]-%(levelname)s-%(message)s') # 格式化对象 # fh.setFormatter(fm) # 设置格式 sh.setFormatter(fm) # 设置格式 # logger.addHandler(fh) # logger添加文件输出流 logger.addHandler(sh) # logger添加标准输出流(std out) logger.setLevel(logging.DEBUG) # 设置从那个等级开始提示 logger.debug("debug Test") logger.info("info Test") logger.warning("warning Test") logger.error("error Test") logger.critical("critical Test")
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,376
dkgee/tkspam3
refs/heads/master
/dlcvae/rabbitmq/demo_producer.py
# -*- coding: utf-8 -*- import pika host_ip ="172.30.154.241" uport="8101" uuser="admin" upass="123456" virtual_host="/" credentials = pika.PlainCredentials(uuser, upass) connection = pika.BlockingConnection(pika.ConnectionParameters(host=host_ip,port=uport,virtual_host=virtual_host, credentials=credentials)) channel = connection.channel() queue_name = 'site:tool:trace' while True: channel.basic_publish(exchange='', routing_key=queue_name, body='Hello World!') print(" [x] Send 'Hello World!'") connection.close()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,377
dkgee/tkspam3
refs/heads/master
/dlcvae/vcode/csv_to_xls.py
# -*- coding: utf-8 -*- # py-version: Python 3.7 # requirement: csv、openpyxl # description:将csv文件导出至Excel保存,每超过65536行,新建一个sheet保存 # author: jht # date: 2018-12-12 09:34 import csv from openpyxl import Workbook csv_file_path = "D:/bootleg.csv" # csv文件保存路径 xls_file_path = "D:/target.xlsx" # Excel文件保存路径 sheet_max_number = 65536 # Excel每一个Sheet最大条数 with open(csv_file_path, "r") as csvfile: read = csv.reader(csvfile) workbook = Workbook() x = 1 page = 1 sheet = workbook.active sheet.title = str(page) print("First sheet:" + str(x)) for i in read: if x > sheet_max_number: page += 1 sheet = workbook.create_sheet(str(page), index=0) print("Create new sheet:" + str(page)) x = 1 else: x += 1 sheet.append(i) workbook.save(xls_file_path)
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,378
dkgee/tkspam3
refs/heads/master
/dlcvae/rabbitmq/demo_consumer.py
# -*- coding: utf-8 -*- import pika host_ip ="172.30.154.241" uport="8101" uuser="admin" upass="123456" virtual_host="/" credentials = pika.PlainCredentials(uuser, upass) connection = pika.BlockingConnection(pika.ConnectionParameters(host=host_ip,port=uport,virtual_host=virtual_host, credentials=credentials)) channel = connection.channel() queue_name = 'site:tool:trace' channel.queue_declare(queue=queue_name) # 如果队列没有创建,就创建这个队列 def callback(ch, method, properties, body): print(" [x] Received %r" % body.decode()) # import time # time.sleep(10) # print('ok') ch.basic_ack(delivery_tag=method.delivery_tag) # no_ack channel.basic_consume(callback, queue=queue_name, no_ack=False) print(' [*] Waiting for message. To exit press CTRL+C') channel.start_consuming()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,379
dkgee/tkspam3
refs/heads/master
/dlcvae/tf/tutorial/fashion_mnist_p2.py
# -*- coding: utf-8 -*- #基本训练 # Tensorflow and tf.keras import tensorflow as tf from tensorflow import keras import os # Helper libraries import numpy as np import matplotlib.pyplot as plt print('Tensorflow Version: %s'%tf.__version__) #step01:导入Fashion MNIST数据集 fashion_mnist = keras.datasets.fashion_mnist # 从文件中读取训练标签和图片数据及测试标签和图片,标签和图片的对应关系就是一一对应的。 # 这种一一对应关系建立的工程量大,是需要程序处理还是人工处理, (train_images, train_lables),(test_images, test_labels) = fashion_mnist.load_data() dirname = os.path.join('datasets', 'fashion-mnist') print("文件缓存目录:%s"%dirname) #自定义实际标签对象名称 class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] #step02:探索数据 print('训练数据集维度: %s'%str(train_images.shape)) print('训练数据集数量:%d'%len(train_lables)) print('测试数据集维度: %s'%str(test_images.shape)) print('测试数据集维度: %d'%len(test_labels)) #step03:预处理数据(将图像转换为浮点数,归一化处理) train_images = train_images / 255.0 test_images = test_images / 255.0 #显示训练集第一张图片 # plt.figure() # plt.imshow(train_images[0]) #显示训练集前25张图片 # plt.colorbar() # plt.grid(False) # plt.figure(figsize=(10,10)) # for i in range(25): # plt.subplot(5,5,i+1) # plt.xticks([]) # plt.yticks([]) # plt.grid(False) # plt.imshow(train_images[i], cmap=plt.cm.binary) # plt.xlabel(class_names[train_lables[i]]) # plt.show() #显示图片 #step04:构建模型(设置层、编译模型) 构建和训练网络 model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), #设置 keras.layers.Dense(128, activation=tf.nn.relu), keras.layers.Dense(10, activation=tf.nn.softmax) ]) model.compile(optimizer=tf.train.AdamOptimizer(), loss='sparse_categorical_crossentropy', metrics=['accuracy']) #step05:训练模型 model.fit(train_images, train_lables, epochs=5) #step06:评估准确率 # Test accuracy: 0.8727 # Test accuracy: 0.8749 # Test accuracy: 0.8771 test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test Loss:', test_loss) print('Test accuracy:', test_acc) # model_save_path = './fashion.model.h5' # model.save(model_save_path) #把模型保存为一个HDF5文件 ### 使用save方法保存模型后,下次加载时,按原路径加载配置,此外还需配置模型编译参数,才能预测 # model = keras.models.load_model(model_save_path) #加载保存的模型 # model.compile(optimizer=tf.train.AdamOptimizer(), #配置模型编译方法 # loss='sparse_categorical_crossentropy', # metrics=['accuracy']) #step07:作出预测 predictions = model.predict(test_images) # print('预测的置信度:%s'%str(predictions)) print('置信度最大值(标签值):%s'%str(np.argmax(predictions[0]))) print(test_labels[0]) # 绘制成图展示 def plot_image(i, predictions_array, true_label, img): predictions_array, true_label, img = predictions_array[i], true_label[i], img[i] plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(img, cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array) if predicted_label == true_label: color = 'blue' else: color = 'red' plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label], 100*np.max(predictions_array), class_names[true_label]), color=color) def plot_value_array(i, predictions_array, true_label): predictions_array, true_label = predictions_array[i], true_label[i] plt.grid(False) plt.xticks([]) plt.yticks([]) thisplot = plt.bar(range(10), predictions_array, color="#777777") plt.ylim([0, 1]) predicted_label = np.argmax(predictions_array) thisplot[predicted_label].set_color('red') thisplot[true_label].set_color('blue') i = 0 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions, test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions, test_labels) plt.show() # 即使置信度非常高,也有可能预测错误。 i = 12 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions, test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions, test_labels) plt.show() # Plot the first X test images, their predicted label, and the true label # Color correct predictions in blue, incorrect predictions in red num_rows = 5 num_cols = 3 num_images = num_rows*num_cols #15张图像训练 plt.figure(figsize=(2*2*num_cols, 2*num_rows)) for i in range(num_images): plt.subplot(num_rows, 2*num_cols, 2*i+1) plot_image(i, predictions, test_labels, test_images) plt.subplot(num_rows, 2*num_cols, 2*i+2) plot_value_array(i, predictions, test_labels) plt.show() # Grab an image from the test dataset img = test_images[0] print('单个图像尺寸:%s'%str(img.shape)) # 添加一个图片进批量处理集合中 img = (np.expand_dims(img,0)) print(img.shape) predictions_single = model.predict(img) print('单个图片预测结果集:%s'%str(predictions_single)) plot_value_array(0, predictions_single, test_labels) _ = plt.xticks(range(10), class_names, rotation=45) # model.predict返回一组列表,每个列表对应批次数据中的每张图像。(仅)获取批次数据中相应图像的预测结果 print(np.argmax(predictions_single[0])) # 此案例评价:通过这个案例,了解了Tensorflow中如何使用Keras深度学习框架API,借助图像库matplotlib进行结果展示 # 单个图像如何处理转换为 集合提供给模型预测 # # 面临的问题: # (1) 准备数据方面:如何运用Keras,在此处如何将数据转换为供keras分析的格式,如何将其和标签建立起关系? # (2) 探索数据(分析数据) # (3) 预处理数据 # (4) 构建模型(设置层、编译模型): # 4.1 模型是如何构建的?我该怎样知道我需要构建什么样的模型才能满足当前需求? # 4.2 层的种类有哪些?该如何决定使用哪种层?每层激活的训练函数该怎样选择? # 4.3 编译模型时,优化函数、loss参数及metric该怎样选择更好? # (5) 训练模型: 设置epoch的多少该怎样选择?有什么利弊? # (6) 评估准确率 # (7) 作出预测 #
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,380
dkgee/tkspam3
refs/heads/master
/geo/auto_gxr_v3.py
# -*- coding: utf-8 -*- """ Created on Thu May 10 14:33:16 2018 """ # import time import sys sys.path.append(r'../../tkspam3') import geo.cfg as cfg from splinter import Browser from pil.lib.geo_predict import crack_captcha class Geo: def __init__(self): if cfg.is_headless: self.driver=Browser("firefox", headless=True) else: self.driver=Browser("firefox") self.try_times = 0 def login(self): print("》》》》》》》》》》》》》》首页自动登录.....") br=self.driver br.visit(cfg.index_url) br.find_by_id('d-login').first.click() self.login_again() def login_again(self): br=self.driver # #username br.find_by_id('username').first.fill(cfg.username) # #password br.find_by_id('password').first.fill(cfg.password) # #imgVcode vcode = crack_captcha(cfg.captcha_url, br.cookies.all()) print('识别验证码完成:' + vcode) br.find_by_id('imageverifycode').first.fill(vcode) #br.find_by_css('input.login_button').first.click() br.find_by_xpath('//*[@id="fm1"]/div/div[6]').first.click() #msg msgs = br.find_by_id('msg') if len(msgs) > 0: self.try_times += 1 print('登录失败,验证码错误。') if self.try_times <= 5: print('第' + str(self.try_times) + '次登录') self.login_again() else: print(str(self.try_times) + '次登录均失败,请手动登录(30s等待用户输入时间)') time.sleep(30) else: print('自动登录成功') #遥感影像 def remoteImage(self): print("》》》》》》》》》》》》》》开始遥感影像下载") br=self.driver br.visit(cfg.international_url) time.sleep(5) linkspage = br.find_link_by_partial_href('remotedetail.html') pictureurls=[] for i in range(0,len(linkspage)): linkpage=linkspage[i] txt=linkpage.html if txt != '查看数据': linkpage.click() time.sleep(2) window = br.windows[1] if window.url.startswith('http://'): pictureurls.append(window.url) window.close() print("》》》》》》》》》》》》》》遥感影像下载地址获取完成") browser=self.driver for i in range(1,len(pictureurls)): browser.visit(pictureurls[i]) time.sleep(5) remotelist=browser.find_by_id('remotelist') within_elements = remotelist.first.find_by_tag('a') for j in range(0,len(within_elements)): within_elements[j].click() time.sleep(5) print("》》》》》》》》》》》》》》遥感影像文件下载完成.") def book(self): print("》》》》》》》》》》》》》》开始查看图书专著") browser=self.driver browser.visit(cfg.literature_url) time.sleep(3) paperurls = [] paperurl_first = browser.find_by_css('#DoiAbstract > a') first_size = len(paperurl_first) if first_size == 0: print("获取第一页链接失败,可能页面超时,暂停2s等待") time.sleep(2) paperurl_first = browser.find_by_css('#DoiAbstract > a') first_size = len(paperurl_first) if first_size > 0: print("成功获取第一页,%d,条数据,开始获取第二页"%first_size) for tag_a in paperurl_first: paperurls.append(tag_a['href']) browser.find_by_text('下一页').first.click() time.sleep(2) paperurl_second = browser.find_by_css('#DoiAbstract > a') if len(paperurl_second) > 0: print('成功获取第二页图书专著') for tag_b in paperurl_second: paperurls.append(tag_b['href']) print('本次任务共获取%d个图书专著链接,准备查看'%len(paperurls)) if len(paperurls) > 0: for href in paperurls: browser.visit(href) pp = browser.find_by_id('keyFullPaper') if len(pp) > 0: pp.first.click() time.sleep(6) if len(browser.windows) >= 2: window = browser.windows[1] window.close() print("》》》》》》》》》》》》》》图书专著查看完成") def surveyreport(self): print("》》》》》》》》》》》》》》开始查看考察报告") browser=self.driver browser.visit(cfg.surveyreport_url) time.sleep(3) papers_first = browser.find_link_by_partial_href('datadetails.html') paperurls=[] if len(papers_first) > 0: print('第一页获取%d个考察报告,'%len(papers_first)) for j in papers_first: paperurls.append(j['href']) browser.find_by_text('下一页').first.click() time.sleep(2) papers_second = browser.find_link_by_partial_href('datadetails.html') if len(papers_second) > 0: print('第二页获取%d个考察报告,'%len(papers_second)) for k in papers_second: paperurls.append(k['href']) print('本次任务共获取%d个考察报告链接,准备查看'%len(paperurls)) if len(paperurls) > 0: for href in paperurls: browser.visit(href) pp = browser.find_by_id('keyFullPaper') if len(pp) > 0: pp.first.click() time.sleep(6) if len(browser.windows) >= 2: window = browser.windows[1] window.close() print("》》》》》》》》》》》》》》考察报告查看完成") def close(self): print("本次任务结束,关闭浏览器") self.driver.quit() if __name__ == '__main__': geo=Geo() geo.login() if cfg.international_status: geo.remoteImage() if cfg.literature_status: geo.book() if cfg.surveyreport_status: geo.surveyreport() geo.close()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,381
dkgee/tkspam3
refs/heads/master
/mlap/pca/test_demo01.py
# -*- coding: utf-8 -*- import time import logging from sklearn.datasets import fetch_olivetti_faces from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt #logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') logger = logging.getLogger() sh = logging.StreamHandler() fm = logging.Formatter('%(asctime)s-%(filename)s[line%(lineno)d]-%(levelname)s-%(message)s') sh.setFormatter(fm) logger.addHandler(sh) # logger添加标准输出流(std out) logger.setLevel(logging.DEBUG) # 设置从那个等级开始提示 def plot_gallery(images, titles, h, w, n_row=2, n_col=5): """显示图片阵列""" plt.figure(figsize=(2 * n_col, 2.2 * n_row), dpi=144) plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.01) for i in range(n_row * n_col): plt.subplot(n_row, n_col, i+1) plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray) plt.title(titles[i]) plt.axis('off') plt.show() #主程序 data_home='datasets/' logger.info('Start to load dataset') faces = fetch_olivetti_faces(data_home=data_home) logger.info('Done with load dataset') X=faces.data y=faces.target targets = np.unique(faces.target) target_names = np.array(["c%d" % t for t in targets]) n_targets = target_names.shape[0] n_samples, h, w = faces.images.shape print(' Sample count:', n_samples) print(' Target count:', n_targets) print(' Image size:', w, 'x', h) print(' Dataset shape:', X.shape) n_row = 2 n_col = 6 sample_images = None sample_titles=[] for i in range(n_targets): people_images = X[y == i] people_sample_index = np.random.randint(0, people_images.shape[0], 1) people_sample_image = people_images[people_sample_index, :] if sample_images is not None: sample_images = np.concatenate((sample_images, people_sample_image), axis=0) else: sample_images = people_sample_image sample_titles.append(target_names[i]) plot_gallery(sample_images, sample_titles, h, w, n_row, n_col) x_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=4)
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,382
dkgee/tkspam3
refs/heads/master
/pil/lib/svm_train.py
""" SVM示例: - http://www.cnblogs.com/Finley/p/5329417.html """ from pil.lib.svm_lib.svm import svm_problem, svm_parameter from pil.lib.svm_lib.svmutil import * def svm_model_train(train_file_name, model_path): """ 使用图像的特征文件 来训练生成model文件 :return: """ y, x = svm_read_problem(train_file_name) model = svm_train(y, x) svm_save_model(model_path, model) def svm_model_test(test_feature_file, model_path, lable_to_type_path): """ 使用测试集测试模型 :return: """ yt, xt = svm_read_problem(test_feature_file) model = svm_load_model(model_path) p_label, p_acc, p_val = svm_predict(yt, xt, model) label_to_type = [] with open(lable_to_type_path) as f: for line in f: tt = line.split(',')[1] label_to_type.append(tt) cnt = 0 for item in p_label: # print('%d' % item, end=',') print(label_to_type[int(item)]) cnt += 1 if cnt % 8 == 0: print('') if __name__ == "__main__": print('svm demo') # svm_data_demo() # train_svm_model() # svm_model_test() #使用抽取出切图特征文件训练出模型文件 model_path='./train_data/svm_model_file' # train_file_name='./train_data/train_pix_feature_xy.txt' # svm_model_train(train_file_name, model_path) # 使用测试文件测试模型文件 test_feature_file='./test_data/last_test_pix_xy_241.txt' lable_to_type_path = './train_data/label_to_type.txt' svm_model_test(test_feature_file, model_path, lable_to_type_path)
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,383
dkgee/tkspam3
refs/heads/master
/dlcvae/vcode/gsxt_1811/generate_word_img.py
# -*- coding: utf-8 -*- import os import pygame import io from PIL import Image def yStart(grey): m,n = grey.size for j in range(n): for i in range(m): if grey.getpixel((i,j)) == 0: return j def yEnd(grey): m,n = grey.size for j in range(n-1,-1,-1): for i in range(m): if grey.getpixel((i,j)) == 0: return j def xStart(grey): m,n = grey.size for i in range(m): for j in range(n): if grey.getpixel((i,j)) == 0: return i def xEnd(grey): m,n = grey.size for i in range(m-1,-1,-1): for j in range(n): if grey.getpixel((i,j)) == 0: return i def xBlank(grey): m,n = grey.size blanks = [] for i in range(m): for j in range(n): if grey.getpixel((i,j)) == 0: break if j == n-1: blanks.append(i) return blanks def yBlank(grey): m,n = grey.size blanks = [] for j in range(n): for i in range(m): if grey.getpixel((i,j)) == 0: break if i == m-1: blanks.append(j) return blanks def getWordsList(): f = open('3500.txt') line = f.read().strip() wordslist = line.split(' ') f.close() return wordslist count = 0 wordslist = [] def getWordsByBlank(img,path): '''根据行列的空白取图片,效果不错''' global count global wordslist grey = img.split()[0] xblank = xBlank(grey) yblank = yBlank(grey) #连续的空白像素可能不止一个,但我们只保留连续区域的第一个空白像素和最后一个空白像素,作为文字的起点和终点 xblank = [xblank[i] for i in range(len(xblank)) if i == 0 or i == len(xblank)-1 or not (xblank[i]==xblank[i-1]+1 and xblank[i]==xblank[i+1]-1)] yblank = [yblank[i] for i in range(len(yblank)) if i == 0 or i == len(yblank)-1 or not (yblank[i]==yblank[i-1]+1 and yblank[i]==yblank[i+1]-1)] for j in range(len(yblank)/2): for i in range(len(xblank)/2): area = (xblank[i*2],yblank[j*2],xblank[i*2+1]+32,yblank[j*2]+32)#这里固定字的大小是32个像素 #area = (xblank[i*2],yblank[j*2],xblank[i*2+1],yblank[j*2+1]) word = img.crop(area) word.save(path+wordslist[count]+'.png') count += 1 if count >= len(wordslist): return def getWordsFormImg(imgName,path): png = Image.open(imgName,'r') img = png.convert('1') grey = img.split()[0] #先剪出文字区域 area = (xStart(grey)-1,yStart(grey)-1,xEnd(grey)+2,yEnd(grey)+2) img = img.crop(area) getWordsByBlank(img,path) def getWrods(): global wordslist wordslist = getWordsList() imgs = ["l1.png","l2.png","l3.png"] for img in imgs: getWordsFormImg(img,'words/') ##########生成文字 def pasteWord(word): '''输入一个文字,输出一张包含该文字的图片''' pygame.init() font = pygame.font.Font(os.path.join("./fonts", "a.ttf"), 22) im = Image.new("RGB", (300, 50), (255, 255, 255)) # text = word.decode('utf-8') # imgName = "D:/chinese/"+text+".png" # paste(text,font,imgName) rtext = font.render(word, True, (0, 0, 0), (255,255,255)) sio = io.StringIO() pygame.image.save(rtext, sio) sio.seek(0) line = Image.open(sio) im.paste(line, (10,5)) im.show() im.save("t.png") def paste(text,font,imgName,area = (0, -9)): '''根据字体,将一个文字黏贴到图片上,并保存''' im = Image.new("RGB", (32, 32), (255, 255, 255)) rtext = font.render(text, True, (0, 0, 0), (255, 255, 255)) sio = io.StringIO() pygame.image.save(rtext, sio) sio.seek(0) line = Image.open(sio) im.paste(line, area) #im.show() im.save(imgName) if __name__ == "__main__": # getWrods() word = '你好' pasteWord(word)
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,384
dkgee/tkspam3
refs/heads/master
/mlap/text_classification/test_jieba_classification.py
# -*- coding: utf-8 -*- import pickle import os import jieba from sklearn.datasets.base import Bunch from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import TfidfVectorizer def savefile(savepath, content): #保存至文件 fp = open(savepath, "w", encoding="utf-8") fp.write(content) fp.close() def readfile(path): #读取文件 fp = open(path, "rb") content = fp.read().decode('utf-8') fp.close() return content ## 读取bunch对象 def readbunchobj(path): file_obj = open(path, "rb") bunch = pickle.load(file_obj) file_obj.close() return bunch ##写入bunch对象 def writebunchobj(path, bunchobj): file_obj = open(path, "wb") pickle.dump(bunchobj, file_obj) file_obj.close() ###主程序 ### Train配置 # corpus_path = "data/corpus/" #未分词分类语料库路径【step01: 准备原始分类文件,将分类文件放在该目录下】 # seg_path = "data/seg/" #分词后的分类语料库路径【step02: 中间数据,存放分词后的分类文件】 # wordbag_path = "data/train_word_bag/" # 分词语料Bunch对象持久化文件路径【step03: 存放训练模型数据的目录】 # wordbag_file = "train_set.dat" # 分词语料Bunch对象持久化文件路径【step04: 训练模型数据文件】 # space_path = "data/train_word_bag/tfidfspace.dat" # 向量空间模型存放位置 ####Test配置 corpus_path = "data/test/" #未分词分类语料库路径【step01: 准备原始分类文件,将分类文件放在该目录下】 seg_path = "data/seg_test/" #分词后的分类语料库路径【step02: 中间数据,存放分词后的分类文件】 wordbag_path = "data/test_word_bag/" # 分词语料Bunch对象持久化文件路径【step03: 存放训练模型数据的目录】 wordbag_file = "test_set.dat" # 分词语料Bunch对象持久化文件路径【step04: 训练模型数据文件】 space_path = "data/test_word_bag/testspace.dat" # 向量空间模型存放位置 #读取停用词 stopword_path = "data/train_word_bag/hlt_stop_words.txt" stpwrdlist = readfile(stopword_path).splitlines() catelist = os.listdir(corpus_path) #获取所有子目录 #获取子目录下的所有文件 for mydir in catelist: class_path = corpus_path + mydir + "/" seg_dir = seg_path + mydir + "/" if not os.path.exists(seg_dir): os.makedirs(seg_dir) file_list = os.listdir(class_path) for file_path in file_list: fullname = class_path + file_path content = readfile(fullname).strip() content = content.replace("\r\n", "").strip() content_seg = jieba.cut(content) savefile(seg_dir + file_path, " ".join(content_seg)) print("==============first-01: 中文语料分词结束!") bunch = Bunch(target_name=[], label=[], filenames=[], contents=[]) catelist = os.listdir(seg_path) bunch.target_name.extend(catelist) #将类别信息保存到bunch对象中 for mydir in catelist: class_path = seg_path + mydir + "/" file_list = os.listdir(class_path) for file_path in file_list: fullname = class_path + file_path bunch.label.append(mydir) # 保存当前文件的分类标签 bunch.filenames.append(fullname) #保存当前文件的文件路径 bunch.contents.append(readfile(fullname).strip()) # 保存文件词向量 if not os.path.exists(wordbag_path): os.makedirs(wordbag_path) wordbag = wordbag_path + wordbag_file #bunch 对象持久化 file_obj = open(wordbag, "wb") pickle.dump(bunch, file_obj) #序列化bunch对象,将其写入到文件中 file_obj.close() print("==============second-02: 构建文本向量结束!") ##导入分词后的词向量bunch对象 bunch = readbunchobj(wordbag) ##构建tf-idf词向量空间对象 tfidfspace = Bunch(target_name=bunch.target_name, label=bunch.label, filenames=bunch.filenames, tdm=[], vocabulary={}) ##使用TfidVectorizer初始化向量空间模型 vectorizer = TfidfVectorizer(stop_words=stpwrdlist, sublinear_tf=True, max_df=0.5) transformer = TfidfTransformer() #该类会统计每个词语的tf-idf权值 #文本转为词频矩阵,单独保存字典文件 tfidfspace.tdm = vectorizer.fit_transform(bunch.contents) tfidfspace.vocabulary = vectorizer.vocabulary_ ##持久化词袋 writebunchobj(space_path, tfidfspace) print("==============third-03: 构建词袋模型结束!")
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,385
dkgee/tkspam3
refs/heads/master
/pil/lib/img_tools.py
# -*- coding: utf-8 -*- import cv2 def get_clear_bin_image(imgBuf): img = cv2.imdecode(imgBuf, cv2.IMREAD_COLOR) #step01 灰阶二值化处理 img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #灰值化 img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 1)#二值化 #step02 清理边框 h, w = img.shape[:2] for y in range(0, w): for x in range(0, h): if y < 4 or y > w -4: img[x, y] = 255 if x < 4 or x > h - 4: img[x, y] = 255 # step03 清除干扰线 h, w = img.shape[:2] for y in range(1, w - 1): for x in range(1, h - 1): count = 0 if img[x, y - 1] > 245: count = count + 1 if img[x, y + 1] > 245: count = count + 1 if img[x - 1, y] > 245: count = count + 1 if img[x + 1, y] > 245: count = count + 1 if count > 2: img[x, y] = 255 # step04 清理干扰点 img = interference_point(img) return img def get_crop_imgs(img): child_img_list = [] #geo登录验证码 for i in range(4): x = 18 + i * 16 # 见原理图 y = 0 child_img = img.crop((x, y, x + 16, y + 42)) child_img_list.append(child_img) return child_img_list def get_label_by_path(lable_to_type_path): label_to_type = [] #获取标签映射 with open(lable_to_type_path) as f: for line in f: tt = line.split(',')[1].replace("\n", "") label_to_type.append(tt) return label_to_type def interference_point(img, x = 0, y = 0): """点降噪 9邻域框,以当前点为中心的田字框,黑点个数,,, :param x: :param y: :return: """ #如果三面没有就去掉,如果上下没有或左右没有也去掉 cur_pixel = img[x,y]# 当前像素点的值 height,width = img.shape[:2] for y in range(0, width - 1): for x in range(0, height - 1): if y == 0: # 第一行 if x == 0: # 左上顶点,4邻域 # 中心点旁边3个点 sum = int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 2 * 245: img[x, y] = 0 elif x == height - 1: # 右上顶点 sum = int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) if sum <= 2 * 245: img[x, y] = 0 else: # 最上非顶点,6邻域 sum = int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 3 * 245: img[x, y] = 0 elif y == width - 1: # 最下面一行 if x == 0: # 左下顶点 # 中心点旁边3个点 sum = int(cur_pixel) \ + int(img[x + 1, y]) \ + int(img[x + 1, y - 1]) \ + int(img[x, y - 1]) if sum <= 2 * 245: img[x, y] = 0 elif x == height - 1: # 右下顶点 sum = int(cur_pixel) \ + int(img[x, y - 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y - 1]) if sum <= 2 * 245: img[x, y] = 0 else: # 最下非顶点,6邻域 sum = int(cur_pixel) \ + int(img[x - 1, y]) \ + int(img[x + 1, y]) \ + int(img[x, y - 1]) \ + int(img[x - 1, y - 1]) \ + int(img[x + 1, y - 1]) if sum <= 3 * 245: img[x, y] = 0 else: # y不在边界 if x == 0: # 左边非顶点 sum = int(img[x, y - 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y - 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 3 * 245: img[x, y] = 0 elif x == height - 1: # 右边非顶点 sum = int(img[x, y - 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x - 1, y - 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) if sum <= 3 * 245: img[x, y] = 0 else: # 具备9领域条件的 sum = int(img[x - 1, y - 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) \ + int(img[x, y - 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y - 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 4 * 245: img[x, y] = 0 return img
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,386
dkgee/tkspam3
refs/heads/master
/pil/lib/geo_predict.py
# -*- coding: utf-8 -*- """ 在训练结束后,一个完整的hack流程: 1. 从网站动态请求相应的验证文件 #. 进行图像预处理 #. 将图像进行分割成最小基本单位 #. 计算出本图像的特征 #. 使用SVM训练好的模型进行对新的验证图片来做结果预测 """ import time import requests import numpy as np import cv2 import random from PIL import Image from pil.lib.img_tools import get_clear_bin_image, get_crop_imgs, get_label_by_path from pil.lib.svm_lib.svmutil import svm_predict, svm_load_model from pil.lib.svm_features import get_feature_in_four_box, convert_feature_to_vector def crack_captcha(rand_captcha_url, cookies): """ 破解验证码,完整的演示流程 :return: """ # 向指定的url请求验证码图片 # rand_captcha_url = 'https://sso.ckcest.cn/portal/captchaCode' res = requests.get(rand_captcha_url, stream=True, cookies=cookies) cont = res.content imgBuf = np.asarray(bytearray(cont), dtype="uint8") # 需要修改 bin_clear_img = get_clear_bin_image(imgBuf) # 处理获得去噪的二值图 img_cache_path = '../pil/lib/cut_pic/temp.jpg' cv2.imwrite(img_cache_path,bin_clear_img) img = Image.open(img_cache_path) child_img_list = get_crop_imgs(img) # 切割图片为单个字符,保存在内存中,例如:4位验证码就可以分割成4个child # 加载SVM模型进行预测 model_path = '../pil/lib/train_data/svm_model_file' model = svm_load_model(model_path) #加载标签映射 lable_to_type_path='../pil/lib/train_data/label_to_type.txt' label_to_type = get_label_by_path(lable_to_type_path) img_ocr_name = '' # img_save_folder = '../pil/lib/crack_img_res' # uuid_tag = str(int(time.time())) + str(int(random.random()*100)) index = 0 for child_img in child_img_list: img_feature_list = get_feature_in_four_box(child_img) # 使用特征算法,将图像进行特征化降维 index +=1 yt = [0] # 测试数据标签 xt = convert_feature_to_vector(img_feature_list) # 将所有的特征转化为标准化的SVM单行的特征向量 p_label, p_acc, p_val = svm_predict(yt, xt, model) for item in p_label: img_ocr_label = label_to_type[int(item)] img_ocr_name +=img_ocr_label # child_img.save(img_save_folder + '/' + uuid_tag + '_' + str(index) + "_" + img_ocr_label + '.png') # img.save(img_save_folder + '/' + uuid_tag + img_ocr_name + '.png') return img_ocr_name def crack_100(): """ 直接从在线网上下载100张图片,然后识别出来 :return: """ for i in range(1): crack_captcha() if __name__ == '__main__': crack_100() # crack_captcha() pass
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,387
dkgee/tkspam3
refs/heads/master
/mlap/text_classification/bayes/Nbayes_lib.py
# -*- coding: utf-8 -*- import numpy as np def loadDataSet(): #训练集文本 postingList = [['my','dog','has','flea','problems','help','please'], ['maybe','not','take','him','to','dog','park','stupid'], ['my','dalmation','is','so','cute','I','love','him','my'], ['stop','posting','stupid','worthless','garbage'], ['mr','licks','ate','my','steak','how','to','stop','him'], ['quit','buying','worthless','dog','food','stupid']] classVec = [0, 1, 0, 1, 0, 1] #1 is abusive,0 not 每个文本对应的分类 return postingList, classVec # 贝叶斯算法类 class NBayes(object): def __init__(self): self.vocabulary=[] # 词典 self.idf = 0 # 词典的idf权值向量 self.tf = 0 # 训练集的权值矩阵 self.tdm = 0 # P(x|yi) self.Pcates = {} #P(yi)是个类别字典 self.labels = [] # 对应每个文本的分类,是个外部导入的列表 self.doclength = 0 # 训练集文本数 self.vocablen = 0 # 词典词长 self.testset = 0 #测试集 #导入和训练数据集,生成算法必须的参数和数据结构 def train_set(self, train_set, classVec): self.cate_prob(classVec) #计算每个分类在数据集中的概率:P(yi) self.doclength = len(train_set) tempset = set() [tempset.add(word) for doc in train_set for word in doc] # 生成词典 self.vocabulary = list(tempset) self.vocablen = len(self.vocabulary) self.calc_wordfreq(train_set) #计算词频数据集 self.bulid_tmd() #按分类累计向量空间的每维值:P(x|yi) # 计算每个分类在数据集中的概率 def cate_prob(self, classVec): self.labels = classVec labeltemps = set(self.labels) #获取全部分类 for labeltemp in labeltemps: # 统计列表中重复的分类: self.labels.count(labeltemp) self.Pcates[labeltemp] = float(self.labels.count(labeltemp))/float(len(self.labels)) # 生成普通词频向量 def calc_wordfreq(self,trainset): self.idf = np.zeros([1, self.vocablen]) #1,词典数 self.tf = np.zeros([self.doclength, self.vocablen]) # 训练集文件数*词典数 for index in range(self.doclength): #遍历所有的文本 for word in trainset[index]: #遍历文本中所有的词 self.tf[index, self.vocabulary.index(word)] += 1 #找到文本的词在字典中的位置+1 for singleword in set(trainset[index]): self.idf[0, self.vocabulary.index(singleword)] += 1 # 按分类累计向量空间的每维值 def bulid_tmd(self): self.tdm = np.zeros([len(self.Pcates), self.vocablen]) #类别行 词典列 sumlist = np.zeros([len(self.Pcates), 1]) # 统计每个分类的总值 for indx in range(self.doclength): self.tdm[self.labels[indx]] += self.tf[indx] # 将同一类别的词向量空间值加总 sumlist[self.labels[indx]] = np.sum(self.tdm[self.labels[indx]]) self.tdm = self.tdm/sumlist #生成P(x|yi) # 将测试集映射到当前词典 def map2vocab(self, testdata): self.testset = np.zeros([1, self.vocablen]) for word in testdata: self.testset[0, self.vocabulary.index(word)] += 1 def predict(self, testset): if np.shape(testset)[1] != self.vocablen: # 如果测试集长度与词典不相等,退出程序 print("输入错误") exit(0) predvalue = 0 # 初始化类别概率 predclass = "" #初始化类别名称 for tdm_vect,keyclass in zip(self.tdm, self.Pcates): # P(xlyi)P(yi) temp = np.sum(testset * tdm_vect * self.Pcates[keyclass]) # 变量tdm,计算最大分类 if temp > predvalue: predvalue = temp predclass = keyclass return predclass # 生成f-idf def calc_tfidf(self, trainset): self.idf=np.zeros([1,self.vocablen]) self.tf = np.zeros([self.doclength,self.vocablen]) for indx in range(self.doclength): for word in trainset[indx]: self.tf[indx,self.vocabulary.index(word)] += 1 # 消除不同句长导致的偏差 self.tf[indx] = self.tf[indx] / float(len(trainset[indx])) for singleword in set(trainset[indx]): self.idf[0,self.vocabulary.index(singleword)] += 1 self.idf=np.log(float(self.doclength) / self.idf) self.tf=np.multiply(self.tf,self.idf) # 矩阵与向量的点乘 tfxidf ## dataSet,listClasses = loadDataSet() #导入外部数据集 #dataset:句子的词向量, #listClass是句子所属的类别[0,1,0,1,0,1] nb = NBayes() #实例化 nb.train_set(dataSet, listClasses) #训练数据集 nb.map2vocab(dataSet[0]) #随机选择一个测试句 print(nb.predict(nb.testset)) # 输出分类结果
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,388
dkgee/tkspam3
refs/heads/master
/mlap/text_classification/test_lxml.py
# -*- coding: utf-8 -*- from lxml import html path = "D:\\test\\dream.html" content = open(path, "rb").read() page = html.document_fromstring(content) #解析文件 text = page.text_content() #去除所有标签 print(text)
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,389
dkgee/tkspam3
refs/heads/master
/pytorch/demo02/Rescale.py
# -*- coding: utf-8 -*- import torch import numpy as np import torchvision.transforms as transforms import matplotlib.pyplot as plt class Rescale(object): """Rescale the image in a sample to a given size. Args: output_size (tuple or int): Desired output size. If tuple, output is matched to output_size. If int, smaller of image edges is matched to output_size keeping aspect ratio the same. """ def __init__(self, output_size): assert isinstance(output_size, (int, tuple)) self.output_size = output_size def __call__(self, sample): image, landmarks = sample['image'], sample['landmarks'] h, w = image.shape[:2] new_h, new_w = self.output_size top = np.random.randint(0, h - new_h) left = np.random.randint(0, h - new_w) image = image[ top: top + new_h, left: left + new_w] landmarks = landmarks - [left, top] return { 'image': image, 'landmarks': landmarks } class RandomCrop(object): """Crop randomly the image in a sample. Args: output_size (tuple or int): Desired output size. If int, square crop is made. """ def __init__(self, output_size): assert isinstance(output_size, (int, tuple)) if isinstance(output_size, int): self.output_size = (output_size, output_size) else: assert len(output_size) == 2 self.output_size = output_size def __call__(self, sample): image, landmarks = sample['image'], sample['landmarks'] h, w = image.shape[:2] new_h, new_w = self.output_size top = np.random.randint(0, h - new_h) left = np.random.randint(0, w - new_w) image = image[ top: top + new_h, left: left + new_w] landmarks = landmarks - [left, top] return { 'image': image, 'landmarks': landmarks } class ToTensor(object): """Convert ndarrays in sample to Tensors.""" def __call__(self, sample): image, landmarks = sample['image'], sample['landmarks'] # swap color axis because # numpy image: H x W x C # torch image: C x H x W image = image.transpose((2, 0, 1)) return { 'image':torch.from_numpy(image), 'landmarks': torch.from_numpy(landmarks) } # def show_landmarks(image, landmarks): # """Show image with landmarks""" # plt.imshow(image) # plt.scatter(landmarks[:, 0], landmarks[:, 1], s=10, marker='.', c='r') # plt.pause(0.001) # pause a bit so that plots are updated # # plt.pause(0) # 暂停n秒后自动关闭,当n=0时不关闭窗口 # # import pytorch.demo02.FaceLandmarksDataset as FaceLandmarksDataset # face_dataset = FaceLandmarksDataset(csv_file='data/faces/face_landmarks.csv', root_dir='data/faces/') # # scale = Rescale(256) # crop = RandomCrop(128) # composed = transforms.Compose([Rescale(256), Rescale(224)]) # # # Apply each of the above transforms on sample. # fig = plt.figure() # sample = face_dataset[65] # for i, tsfrm in enumerate([scale, crop, composed]): # transforms_sample = tsfrm(sample) # # ax = plt.subplot(1, 3, i + 1) # plt.tight_layout() # ax.set_title(type(tsfrm).__name__) # show_landmarks(**transforms_sample) # # plt.show()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,390
dkgee/tkspam3
refs/heads/master
/faceai/test_detact_face.py
# -*- coding: utf-8 -*- import cv2 # filepath = 'data/angelababy.png' # 能够识别 # filepath = 'data/jp.png' # 能识别 # filepath = 'data/jp2.png' # 未识别出来,可能原因裸露皮肤太多 # filepath = 'data/jp3.png' # 识别错误,裸露皮肤太多 # filepath = 'data/jp22.png' # 未识别出来,可能原因是脸被头发遮挡 # filepath = 'data/jp33.png' # 未识别出来,可能原因是脸被头发遮挡 # filepath = 'data/zxc.png' # 能识别 # filepath = 'data/ldh.png' # 能识别 filepath = 'data/jht.jpg' # 能识别 img = cv2.imread(filepath) # 灰阶处理 img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #opencv 人脸识别分类器 classifier = cv2.CascadeClassifier( "D:\Anaconda3\envs\dev3.6\Lib\site-packages\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml" ) color = (0, 255, 0) #定义绘制颜色 #调用识别人脸 faceRects = classifier.detectMultiScale( img_gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32)) if len(faceRects): #大于0则检测到人脸 for faceRect in faceRects: # 单独框出每一张人脸 x, y, w, h = faceRect # 框出人脸 cv2.rectangle(img, (x, y), (x + h, y + w), color, 2) # 左眼 cv2.circle(img, (x + w//4, y + h//4 + 30), min(w // 8, h // 8), color) # 右眼 cv2.circle(img, (x + 3 * w // 4, y + h // 4 + 30), min(w // 8, h // 8), color) #嘴巴 cv2.rectangle(img, (x + 3 * w // 8, y + 3 * h // 4), (x + 5 * w // 8, y + 7 * h // 8), color) # x = y = 10 #坐标 # w = 100 #矩形大小(宽、高) # color = (90, 90, 87) #定义绘制颜色 # cv2.rectangle(img_gray, (x, y), (x + w, y + w), color, 1) #绘制矩形 # 显示图像 cv2.imshow("Image", img) c = cv2.waitKey(10) cv2.waitKey(0) cv2.destroyAllWindows()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,391
dkgee/tkspam3
refs/heads/master
/mlap/text_classification/test_wrd_testvector.py
# -*- coding: utf-8 -*- import pickle from sklearn.datasets.base import Bunch from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformer def readbunchobj(path): file_obj = open(path, "rb") bunch = pickle.load(file_obj) file_obj.close() return bunch ##写入bunch对象 def writebunchobj(path, bunchobj): file_obj = open(path, "wb") pickle.dump(bunchobj, file_obj) file_obj.close() def readfile(path): #读取文件 fp = open(path, "rb") content = fp.read().decode('utf-8') fp.close() return content #################################################################################################### # 导入分词后的词向量bunch对象 path = "data/test_word_bag/test_set.dat" #词向量空间保存路径 bunch = readbunchobj(path) # 构建测试集tfidf向量空间 testspace = Bunch(target_name=bunch.target_name, label=bunch.label, filenames=bunch.filenames, tdm=[], vocabulary={}) # 导入训练集的词袋 trainbunch = readbunchobj("data/train_word_bag/tfidfspace.dat") #读取停用词 stopword_path = "data/train_word_bag/hlt_stop_words.txt" stpwrdlist = readfile(stopword_path).splitlines() # 使用TfidfVectorizer初始化向量空间模型 vectorizer = TfidfVectorizer(stop_words=stpwrdlist, sublinear_tf=True, max_df=0.5, vocabulary=trainbunch.vocabulary) transformer = TfidfTransformer() # testspace.tdm = vectorizer.fit_transform(bunch.contents) testspace.tdm = vectorizer.transform(bunch.contents) testspace.vocabulary = trainbunch.vocabulary # 创建词袋的持久化 space_path = "data/test_word_bag/testspace.dat" writebunchobj(space_path, testspace) print("==============third-03: 构建测试空间模型完成") ####################################################################################################
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,392
dkgee/tkspam3
refs/heads/master
/pil/vcodepretreat.py
# -*- coding: utf-8 -*- from PIL import Image from fnmatch import fnmatch from os.path import join import cv2 import os # # pytesseract.pytesseract.tesseract_cmd = r'D:\\tesseract-ocr\\tesseract.exe' # tessdata_dir_config = '--tessdata-dir "D:\\tesseract-ocr\\tessdata" -psm 10' def _get_dynamic_binary_image(img_src_dir, img_out_dir, img_name): ''' 自适应阀值二值化 ''' #'./out_img/' + img_name.split('.')[0] + '.jpg' filename = join(img_out_dir, img_name.split('.')[0] + '-bin.jpg') # filedir + '/' + img_name img_name = join(img_src_dir, img_name) print('firname_path:' + filename) print('img_name_path:' + img_name) im = cv2.imread(img_name) im = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) #灰值化 #二值化 th1 = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 1) cv2.imwrite(filename,th1) return th1 def clear_border(img_out_dir, img, img_name): '''去除边框 ''' # filename = './out_img/' + img_name.split('.')[0] + '-clearBorder.jpg' filename = join(img_out_dir, img_name.split('.')[0] + '-nb.jpg') print('firname_path:' + filename) h, w = img.shape[:2] for y in range(0, w): for x in range(0, h): # if y ==0 or y == w -1 or y == w - 2: if y < 4 or y > w -4: img[x, y] = 255 # if x == 0 or x == h - 1 or x == h - 2: if x < 4 or x > h - 4: img[x, y] = 255 cv2.imwrite(filename,img) return img def interference_line(img_out_dir,img, img_name): ''' 干扰线降噪 ''' #filename = './out_img/' + img_name.split('.')[0] + '-interferenceline.jpg' filename = join(img_out_dir, img_name.split('.')[0] + '-nl.jpg') h, w = img.shape[:2] # !!!opencv矩阵点是反的 # img[1,2] 1:图片的高度,2:图片的宽度 for y in range(1, w - 1): for x in range(1, h - 1): count = 0 if img[x, y - 1] > 245: count = count + 1 if img[x, y + 1] > 245: count = count + 1 if img[x - 1, y] > 245: count = count + 1 if img[x + 1, y] > 245: count = count + 1 if count > 2: img[x, y] = 255 cv2.imwrite(filename,img) return img def interference_point(img_out_dir, img, img_name, x = 0, y = 0): """点降噪 9邻域框,以当前点为中心的田字框,黑点个数,,, :param x: :param y: :return: """ #如果三面没有就去掉,如果上下没有或左右没有也去掉 # filename = './out_img/' + img_name.split('.')[0] + '-interferencePoint.jpg' filename = join(img_out_dir, img_name.split('.')[0] + '-np.jpg') # todo 判断图片的长宽度下限 cur_pixel = img[x,y]# 当前像素点的值 print(cur_pixel) height,width = img.shape[:2] print("%s属性高:%s,宽:%s"%(filename,height,width)) for y in range(0, width - 1): for x in range(0, height - 1): if y == 0: # 第一行 if x == 0: # 左上顶点,4邻域 # 中心点旁边3个点 sum = int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 2 * 245: img[x, y] = 0 elif x == height - 1: # 右上顶点 sum = int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) if sum <= 2 * 245: img[x, y] = 0 else: # 最上非顶点,6邻域 sum = int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 3 * 245: img[x, y] = 0 elif y == width - 1: # 最下面一行 if x == 0: # 左下顶点 # 中心点旁边3个点 sum = int(cur_pixel) \ + int(img[x + 1, y]) \ + int(img[x + 1, y - 1]) \ + int(img[x, y - 1]) if sum <= 2 * 245: img[x, y] = 0 elif x == height - 1: # 右下顶点 sum = int(cur_pixel) \ + int(img[x, y - 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y - 1]) if sum <= 2 * 245: img[x, y] = 0 else: # 最下非顶点,6邻域 sum = int(cur_pixel) \ + int(img[x - 1, y]) \ + int(img[x + 1, y]) \ + int(img[x, y - 1]) \ + int(img[x - 1, y - 1]) \ + int(img[x + 1, y - 1]) if sum <= 3 * 245: img[x, y] = 0 else: # y不在边界 if x == 0: # 左边非顶点 sum = int(img[x, y - 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y - 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 3 * 245: img[x, y] = 0 elif x == height - 1: # 右边非顶点 sum = int(img[x, y - 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x - 1, y - 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) if sum <= 3 * 245: img[x, y] = 0 else: # 具备9领域条件的 sum = int(img[x - 1, y - 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) \ + int(img[x, y - 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y - 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 4 * 245: img[x, y] = 0 cv2.imwrite(filename,img) return filename ##################################################################### def cut_imgs_and_save(img, img_name, cut_pic_save_folder): """ 按照图片的特点,进行切割,这个要根据具体的验证码来进行工作. # 见本例验证图的结构原理图 分割图片是传统机器学习来识别验证码的重难点,如果这一步顺利的话,则多位验证码的问题可以转化为1位验证字符的识别问题 :param img: :return: """ child_img_list = [] #geo登录验证码 for i in range(4): x = 18 + i * 16 # 见原理图 y = 0 child_img = img.crop((x, y, x + 16, y + 42)) child_img_list.append(child_img) # 开源中国注册登录验证码 # for i in range(4): # x = 4 + i * (19 + 10) # 见原理图 # y = 0 # child_img = img.crop((x, y, x + 19, y + 40)) # child_img_list.append(child_img) i = 0 for child_img in child_img_list: cut_img_file_name = img_name.split('.')[0] + '-' + ("z%s.png" % i) child_img.save(join(cut_pic_save_folder, cut_img_file_name)) i += 1 def gif_split_to_img(): """ Split gif to image """ gifFileName = r'D:\vcode2\01.gif' #使用Image模块的open()方法打开gif动态图像时,默认是第一帧 im = Image.open(gifFileName) pngDir = gifFileName[:-4] print(pngDir) #创建存放每帧图片的文件夹 os.mkdir(pngDir) try: while True: #保存当前帧图片 current = im.tell() im.save(pngDir+'/'+str(current)+'.png') #获取下一帧图片 im.seek(current+1) except EOFError: pass ##################################################################### def main(): img_src_dir = './img/img_src' img_out_dir = './img/img_out' for file in os.listdir(img_src_dir): if fnmatch(file, '*.png'): img_name = file #print('step01: 自适应阈值二值化处理') # img_bin_save_dir='./img/img_bin' im = _get_dynamic_binary_image(img_src_dir, img_out_dir ,img_name) #print('step02: 去除边框') # img_no_border_dir = './img/img_no_border' im = clear_border(img_out_dir, im, img_name) #print('step03: 对图片进行干扰线降噪') # img_no_interfer_line = './img/img_no_interfer_line' im = interference_line(img_out_dir, im, img_name) #print('step04: 对图片进行点降噪') #img_no_interfer_point = './img/img_no_interfer_point' filename = interference_point(img_out_dir, im, img_name) #print('step04: 对图片进行切割') img = Image.open(filename) cut_imgs_and_save(img, img_name, img_out_dir) #print('step05: 对图片进行标记(最费时)') #print('step06: 标记完成后,进行SVM训练 ') #print('step07: SVM训练完成后,进行测试 ') # print('step07: SVM测试通过后可行 ') if __name__ == '__main__': main()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,393
dkgee/tkspam3
refs/heads/master
/mlap/text_classification/test_jieba.py
# -*- coding: utf-8 -*- import sys import os import jieba # seg_list=jieba.cut("小明1995年毕业于北京清华大学", cut_all=False) # print("DefaultMode:","".join(seg_list)) #默认切分 # # seg_list=jieba.cut("小明1995年毕业于北京清华大学") # print(" ".join(seg_list)) ##分析效果比较自然,相比较全切分,比较粗糙 # seg_list=jieba.cut("小明1995年毕业于北京清华大学", cut_all=True) # print("FullMode:","/".join(seg_list)) #全切分 # # seg_list=jieba.cut("小明1995年毕业于北京清华大学", cut_all=True) # print("FullMode:","/".join(seg_list)) #全切分 ##分词效果更详细 seg_list=jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造") #搜索引擎模式 print("/ ".join(seg_list)) #全切分 ##搜索引擎模式切分效果非常不错,一些组合词汇及组合基本词汇均包括
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,394
dkgee/tkspam3
refs/heads/master
/pil/vcode.py
# -*- coding: utf-8 -*- import numpy as np import requests import pytesseract import os import cv2 import lib.img_tools as imgtool pytesseract.pytesseract.tesseract_cmd = r'D:\\tesseract-ocr\\tesseract.exe' tessdata_dir_config = '--tessdata-dir "D:\\tesseract-ocr\\tessdata" -psm 10' #下载验证码图片 def downloads_pic(pic_name): # pic_name = kwargs.get('pic_name', None) pic_path = 'D:/vcode2/' #url = 'https://sso.ckcest.cn/portal/captchaCode' url = 'https://www.oschina.net/action/user/captcha' res = requests.get(url, stream=True) with open(pic_path + pic_name+'.gif', 'wb') as f: for chunk in res.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() f.close() def downloads_pic_test(): rand_captcha_url = r'https://sso.ckcest.cn/portal/captchaCode' res = requests.get(rand_captcha_url, stream=True) cont = res.content buf = np.asarray(bytearray(cont), dtype="uint8") img = cv2.imdecode(buf, cv2.IMREAD_COLOR) img_cache_path = './easy_img/ttt1.jpg' bin_clear_img = imgtool.get_clear_bin_image(img) # #step01 灰阶二值化处理 # img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #灰值化 # img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 1)#二值化 # # #step02 清理边框 # h, w = img.shape[:2] # for y in range(0, w): # for x in range(0, h): # if y < 4 or y > w -4: # img[x, y] = 255 # if x < 4 or x > h - 4: # img[x, y] = 255 # # # step03 清除干扰线 # h, w = img.shape[:2] # for y in range(1, w - 1): # for x in range(1, h - 1): # count = 0 # if img[x, y - 1] > 245: # count = count + 1 # if img[x, y + 1] > 245: # count = count + 1 # if img[x - 1, y] > 245: # count = count + 1 # if img[x + 1, y] > 245: # count = count + 1 # if count > 2: # img[x, y] = 255 # # # # step04 清理干扰点 # img = interference_point(img, img_cache_path) cv2.imwrite(img_cache_path,bin_clear_img) def create_cut_pic_dir(): """ 创建各个标记的训练样本目录 """ dir_name='0123456789abcdefghijklmnopqrstuvwxyz' parent_dir = './dataa/cut_pic/' label_to_type_path='./label_to_type.txt' # print(len(dir_name)) label_to_type_file = open(label_to_type_path, 'w') for i in range(36): child_dir = parent_dir + str(i) line = str(i) + "," + dir_name[i] label_to_type_file.write(line) label_to_type_file.write('\n') if not os.path.exists(child_dir): os.mkdir(child_dir) label_to_type_file.close() def interference_point(img, img_file, x = 0, y = 0): """点降噪 9邻域框,以当前点为中心的田字框,黑点个数,,, :param x: :param y: :return: """ #如果三面没有就去掉,如果上下没有或左右没有也去掉 cur_pixel = img[x,y]# 当前像素点的值 height,width = img.shape[:2] print("%s属性高:%s,宽:%s"%(img_file,height,width)) for y in range(0, width - 1): for x in range(0, height - 1): if y == 0: # 第一行 if x == 0: # 左上顶点,4邻域 # 中心点旁边3个点 sum = int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 2 * 245: img[x, y] = 0 elif x == height - 1: # 右上顶点 sum = int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) if sum <= 2 * 245: img[x, y] = 0 else: # 最上非顶点,6邻域 sum = int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 3 * 245: img[x, y] = 0 elif y == width - 1: # 最下面一行 if x == 0: # 左下顶点 # 中心点旁边3个点 sum = int(cur_pixel) \ + int(img[x + 1, y]) \ + int(img[x + 1, y - 1]) \ + int(img[x, y - 1]) if sum <= 2 * 245: img[x, y] = 0 elif x == height - 1: # 右下顶点 sum = int(cur_pixel) \ + int(img[x, y - 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y - 1]) if sum <= 2 * 245: img[x, y] = 0 else: # 最下非顶点,6邻域 sum = int(cur_pixel) \ + int(img[x - 1, y]) \ + int(img[x + 1, y]) \ + int(img[x, y - 1]) \ + int(img[x - 1, y - 1]) \ + int(img[x + 1, y - 1]) if sum <= 3 * 245: img[x, y] = 0 else: # y不在边界 if x == 0: # 左边非顶点 sum = int(img[x, y - 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y - 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 3 * 245: img[x, y] = 0 elif x == height - 1: # 右边非顶点 sum = int(img[x, y - 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x - 1, y - 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) if sum <= 3 * 245: img[x, y] = 0 else: # 具备9领域条件的 sum = int(img[x - 1, y - 1]) \ + int(img[x - 1, y]) \ + int(img[x - 1, y + 1]) \ + int(img[x, y - 1]) \ + int(cur_pixel) \ + int(img[x, y + 1]) \ + int(img[x + 1, y - 1]) \ + int(img[x + 1, y]) \ + int(img[x + 1, y + 1]) if sum <= 4 * 245: img[x, y] = 0 return img downloads_pic_test() # for i in range(1,10): # downloads_pic(str(i)) # create_cut_pic_dir()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,395
dkgee/tkspam3
refs/heads/master
/tw/tweet_test.py
# -*- coding: utf-8 -*- # from twitterscraper import query_tweets # import os # import socks # proxy=(socks.SOCKS5, "127.0.0.1", "1080") # os.environ["HTTPS_PROXY"] = "https://161.202.226.195:8123/" # os.environ["HTTPS_PROXY"] = "https://61.118.35.94:55725/" # if __name__ == '__main__': # list_of_tweets = query_tweets("Trump OR Clinton", 10) # print the retrieved tweets to the screen: # for tweet in query_tweets("Trump OR Clinton", 10): # print(tweet) # Or save the retrieved tweets to file: # file = open("output.txt", "w") # for tweet in query_tweets("Trump OR Clinton", 10): # file.write(str(tweet.text.encode('UTF-8'))) # file.close() from twitterscraper.query import query_tweets import datetime as dt def query(): list_of_tweets = query_tweets("秘密", 10, begindate=dt.date(2020, 3, 21)) for te in list_of_tweets: print(te.text) if __name__ == '__main__': query()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,396
dkgee/tkspam3
refs/heads/master
/geo/ygyx.py
# -*- coding: utf-8 -*- """ Created on Thu May 10 14:33:16 2018 @author: JIANGHOU """ import time from splinter import Browser from selenium import webdriver browser = Browser() url='http://geo.ckcest.cn/' browser.visit(url) #人工登陆 #遥感影像 browser.visit('http://geo.ckcest.cn/scientific/InternationalData/list.html') #然后跳转到一个页码 linkspage = browser.find_link_by_partial_href('#') paperurls=[] time.sleep(3) papers = browser.find_link_by_partial_href('remotedetail.html') browserurl=browser.url for j in range(0,10):#len(papers) papers[j].click() time.sleep(3) window = browser.windows[1] paperurls.append(window.url) window.close() for i in range(1,10): browser.visit(paperurls[i]) time.sleep(15) remotelist=browser.find_by_id('remotelist') within_elements = remotelist.first.find_by_tag('a') for j in range(1,len(within_elements)): within_elements[j].click() time.sleep(5) browser.windows[0].close() #144 76 30 655 905
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,397
dkgee/tkspam3
refs/heads/master
/geo/auto_gxr2.py
# -*- coding: utf-8 -*- """ Created on Thu May 10 14:33:16 2018 """ # import time from splinter import Browser from selenium import webdriver class Geo: # 输出用户名 xxxx # 输入密码 xxxxx # 验证码 xxxx def login(self): print("》》》》》》》》》》》》》》首页开始登录(您有 20s 时间输入用户名、密码、验证码).....") self.driver=Browser("firefox") br=self.driver br.visit("http://geo.ckcest.cn/") time.sleep(20) print("》》》》》》》》》》》》》》登录完成") #遥感影像 def remoteImage(self): print("》》》》》》》》》》》》》》开始遥感影像下载") br=self.driver br.visit('http://geo.ckcest.cn/scientific/InternationalData/list.html') time.sleep(5) linkspage = br.find_link_by_partial_href('remotedetail.html') pictureurls=[] for i in range(0,len(linkspage)): linkpage=linkspage[i] txt=linkpage.html if txt != '查看数据': linkpage.click() time.sleep(2) window = br.windows[1] if window.url.startswith('http://'): pictureurls.append(window.url) window.close() print("》》》》》》》》》》》》》》遥感影像下载地址获取完成") browser=self.driver for i in range(1,len(pictureurls)): browser.visit(pictureurls[i]) time.sleep(5) remotelist=browser.find_by_id('remotelist') within_elements = remotelist.first.find_by_tag('a') for j in range(0,len(within_elements)): within_elements[j].click() time.sleep(5) browser.windows[0].close() print("》》》》》》》》》》》》》》遥感影像文件下载完成.") def book(self): print("》》》》》》》》》》》》》》开始查看图书专著") driver=webdriver.Firefox() driver.get('http://geo.ckcest.cn/scientific/literature/books.html') time.sleep(3) papers=driver.find_elements_by_xpath("//*[@href]") paperurls=[] for paper in papers: link=paper.get_attribute('href') if 'books_bs.html' in link: paperurls.append(link) driver.quit() browser=self.driver browser.visit('http://geo.ckcest.cn/scientific/literature/books.html') time.sleep(3) for i in range(0,len(paperurls)): browser.visit(paperurls[i]) pp=browser.find_by_id('keyFullPaper') if len(pp) > 0: pp.first.click() time.sleep(5) window = browser.windows[1] window.close() print("》》》》》》》》》》》》》》图书专著查看完成") def surveyreport(self): print("》》》》》》》》》》》》》》开始查看考察报告") browser=self.driver browser.visit('http://geo.ckcest.cn/scientific/literature/surveyreport/index.html') #然后跳转到一个页码 time.sleep(3) papers = browser.find_link_by_partial_href('datadetails.html') paperurls=[] for j in range(0,len(papers)): papers[j].click() time.sleep(3) window = browser.windows[1] if window.url.startswith('http://'): paperurls.append(window.url) window.close() for i in range(1,len(paperurls)): browser.visit(paperurls[i]) pp=browser.find_by_id('keyFullPaper') if len(pp) > 0: pp.first.click() time.sleep(5) window = browser.windows[1] window.close() print("》》》》》》》》》》》》》》考察报告查看完成") def close(self): print("》》》》》》》》》》》》》》关闭浏览器") self.driver.windows[0].close() ########################################################### geo=Geo() #用户登录 geo.login() #遥感影像 geo.remoteImage() #图书专著 #geo.book() #考察报告 #geo.surveyreport() #关闭浏览器 geo.close()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,398
dkgee/tkspam3
refs/heads/master
/pil/lib/svm_features.py
""" 将图片的像素信息,利用特征工程,降维 为 特征列表文件 """ import os from os.path import join from PIL import Image def get_feature(img): """ 获取指定图片的特征值, 1. 按照每排的像素点,高度为10,然后宽度为6,总共16个维度 1. 按照每排的像素点,高度为42,然后宽度为16,总共58个维度 2. 计算每个维度(行 或者 列)上有效像素点的和 :type img: Image :return:一个维度为16的列表 """ width, height = img.size pixel_cnt_list = [] # width=16, height = 42 for y in range(height): pix_cnt_x = 0 for x in range(width): if img.getpixel((x, y)) == 0: # 黑色点 pix_cnt_x += 1 pixel_cnt_list.append(pix_cnt_x) for x in range(width): pix_cnt_y = 0 for y in range(height): if img.getpixel((x, y)) == 0: # 黑色点 pix_cnt_y += 1 pixel_cnt_list.append(pix_cnt_y) return pixel_cnt_list def get_feature_in_four_box(img): """ 获取指定图片的特征值, 1. 按照四方格平均值求向量,高度为42,然后宽度为16,总共21x8=168个维度 :type img: Image :return:一个维度为16的列表 """ width, height = img.size pixel_cnt_list = [] # width=16, height = 42 for y in range(0, height, 2): if (y+1) < height: for x in range(0, width, 2): if (x+1) < width: pix_cnt_1 = 0 pix_cnt_2 = 0 pix_cnt_3 = 0 pix_cnt_4 = 0 if img.getpixel((x, y)) == 0: pix_cnt_1 = 4 if img.getpixel((x+1, y)) == 0: pix_cnt_2 = 4 if img.getpixel((x, y+1)) == 0: pix_cnt_3 = 4 if img.getpixel((x+1, y+1)) == 0: pix_cnt_4 = 4 avg_pix = (pix_cnt_1 + pix_cnt_2 + pix_cnt_3 + pix_cnt_4)/4 pixel_cnt_list.append(int(avg_pix)) return pixel_cnt_list def convert_values_to_str(label, dif_list): """ 将特征值串转化为标准的svm输入向量: 9 1:4 2:2 3:2 4:2 5:3 6:4 7:1 8:1 9:1 10:3 11:5 12:3 13:3 14:3 15:3 16:6 最前面的是 标记值,后续是特征值 :param label: int :param dif_list: :type dif_list: list[int] :return: """ index = 1 line = '%d' % label for item in dif_list: fmt = ' %d:%d' % (index, item) line += fmt index += 1 # print(line) return line def convert_imgs_to_feature_file(label, svm_feature_file, img_folder): """ 将某个目录下二进制图片文件,转换成特征文件 :param dig:检查的数字 :param svm_feature_file: svm的特征文件完整路径 :type label:string :return: """ file_list = os.listdir(img_folder) if len(file_list) == 0: return # sample_cnt = 0 # right_cnt = 0 for file in file_list: img = Image.open(img_folder + '/' + file) #dif_list = get_feature(img) dif_list = get_feature_in_four_box(img) # sample_cnt += 1 line = convert_values_to_str(label, dif_list) svm_feature_file.write(line) svm_feature_file.write('\n') # 将识别的特征转换为向量 def convert_feature_to_vector(feature_list): """ :param feature_list: :return: """ index = 1 xt_vector = [] feature_dict = {} for item in feature_list: feature_dict[index] = item index += 1 xt_vector.append(feature_dict) return xt_vector def get_svm_train_txt(cut_pic_folder, train_file_name): """ 获取 测试集 的像素特征文件。 所有的数字的可能分类为36,分别放在以相应的字母命名的目录中 :return: """ svm_feature_file = open(train_file_name, 'w') for i in range(36): img_folder = join(cut_pic_folder, str(i)) convert_imgs_to_feature_file(i, svm_feature_file, img_folder) # 不断地以追加的方式写入到同一个文件当中 svm_feature_file.close() def get_svm_test_txt(label, test_cut_pic_folder,test_feature_file): """ 获取 测试集 的像素特征文件 :return: """ test_file = open(test_feature_file, 'w') convert_imgs_to_feature_file(label, test_file, test_cut_pic_folder) test_file.close() if __name__ == '__main__': print("start captcha app...") # img_path='../cut_pic/1-0.png' # img = Image.open(img_path) # pixel_cnt_list=get_feature(img) # line = convert_values_to_str(6, pixel_cnt_list) # print(line) # img_path='./cut_pic/2-z2.png' # img = Image.open(img_path) #img.show() # img.save('./cut_pic/tt.gif','GIF') #dig = 6 #img_folder='./cut_pic' #feature_file='./train_pix_feature_tt.txt' #test_file = open(feature_file, 'w') #convert_imgs_to_feature_file(dig, test_file, img_folder) # 使用样本模型,生成训练初始模型 # cut_pic_folder = '../data/cut_pic/' # train_file_name='./train_data/train_pix_feature_xy.txt' # get_svm_train_txt(cut_pic_folder, train_file_name) # 使用测试样本,生成测试模型 label = 241 test_cut_pic_folder='./cut_pic' test_feature_file='./test_data/last_test_pix_xy_241.txt' get_svm_test_txt(label, test_cut_pic_folder, test_feature_file)
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,399
dkgee/tkspam3
refs/heads/master
/faceai/test_detact_face_dlib.py
# -*- coding: utf-8 -*- import cv2 import dlib # path = "data/angelababy.png" #能识别 #path = "data/jp.png" #能识别 # path = "data/jp2.png" #能识别 # path = "data/jp3.png" #能识别 # path = "data/jp22.png" #能识别 # path = "data/jp33.png" #能识别 # path = "data/ldh.png" #能识别 # path = "data/zxc.png" #能识别 # path = "data/ldh.png" #能识别 path = "data/jht.jpg" #能识别 # dlib识别率高,采用人脸的68个标定点,在测试样本集中基本都能识别 img = cv2.imread(path) img_gray = cv2.cvtColor(img , cv2.COLOR_BGR2GRAY) #人脸分类器 detector = dlib.get_frontal_face_detector() #获取人脸检测器 predictor = dlib.shape_predictor( "D:\\Anaconda3\\envs\dev3.6\\Lib\site-packages\\dlib-datadlib-data\\shape_predictor_68_face_landmarks.dat" ) dets = detector(img_gray, 1) for face in dets: shape = predictor(img_gray,face) for pt in shape.parts(): pt_pos = (pt.x, pt.y) cv2.circle(img, pt_pos, 2, (0, 255, 0), 1) cv2.imshow("Image", img) cv2.waitKey(0) cv2.destroyAllWindows()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,400
dkgee/tkspam3
refs/heads/master
/dlcvae/ch06/opencv_demo1.py
# -*- coding: utf-8 -*- import cv2 #### demo1 # color_img = cv2.imread('test_120x40.jpg') # print(color_img.shape) # gray_img = cv2.imread('test_120x40.jpg', cv2.IMREAD_GRAYSCALE) # print(gray_img.shape) # cv2.imwrite('test_grayscale.jpg', gray_img) # reload_grayscale = cv2.imread('test_grayscale.jpg') # print(reload_grayscale.shape) # cv2.imwrite('test_imwrite.jpg', color_img, (cv2.IMWRITE_JPEG_QUALITY, 80)) # cv2.imwrite('test_imwrite2.jpg', color_img, (cv2.IMWRITE_PNG_COMPRESSION, 5)) ###### demo2 img = cv2.imread('test3.jpg') # img_200x200 = cv2.resize(img, (200, 200)) # img_200x300 = cv2.resize(img, (0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_NEAREST) # img_300x300 = cv2.copyMakeBorder(img, 50, 50, 0, 0, cv2.BORDER_CONSTANT, value=(0 , 0, 0)) # patch_tree = img[170:300, 300:480] # 高从180到290, 宽从300到480 # cv2.imwrite('cropped_car.jpg', patch_tree) # cv2.imwrite('resized_200x200.jpg', img_200x200) # cv2.imwrite('resized_200x300.jpg', img_200x300) # cv2.imwrite('resized_300x300.jpg', img_300x300) # img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # turn_green_hsv = img_hsv.copy() # turn_green_hsv[:, :, 0] = (turn_green_hsv[:, :, 0] + 15)%180 # turn_green_img = cv2.cvtColor(turn_green_hsv, cv2.COLOR_HSV2BGR) # cv2.imwrite('turn_green.jpg', turn_green_img) # colorless_hsv = img_hsv.copy() # colorless_hsv[:, :, 1] = 0.5 * colorless_hsv[:, :, 1] # colorless_img = cv2.cvtColor(colorless_hsv, cv2.COLOR_HSV2BGR) # cv2.imwrite('colorless.jpg', colorless_img) # darker_hsv = img_hsv.copy() # darker_hsv[:, :, 2] = 0.5 * darker_hsv[:, :, 2] # darker_img = cv2.cvtColor(darker_hsv, cv2.COLOR_HSV2BGR) # cv2.imwrite('darker.jpg', darker_img) # Gamma变换 # 分通道计算每个通道的直方图 # hist_b = cv2.calcHist([img], [0], None, [256], [0, 256]) # hist_g = cv2.calcHist([img], [1], None, [256], [0, 256]) # hist_r = cv2.calcHist([img], [2], None, [256], [0, 256]) # # import numpy as np # def gamma_trans(img, gamma): # gamma_table = [np.power(x/255.0, gamma) * 255.0 for x in range(256)] # gamma_table = np.round(np.array(gamma_table)).astype(np.uint8) # return cv2.LUT(img, gamma_table) # # img_corrected = gamma_trans(img, 0.5) # cv2.imwrite('gamma_corrected.jpg', img_corrected) # hist_b_corrected = cv2.calcHist([img_corrected], [0], None, [256], [0, 256]) # hist_g_corrected = cv2.calcHist([img_corrected], [1], None, [256], [0, 256]) # hist_r_corrected = cv2.calcHist([img_corrected], [2], None, [256], [0, 256]) # # import matplotlib.pyplot as plt # from mpl_toolkits.mplot3d import Axes3D # fig = plt.figure() # pix_hists = [ # [hist_b, hist_g, hist_r], # [hist_b_corrected, hist_g_corrected, hist_r_corrected] # ] # pix_vals = range(256) # for sub_plt, pix_hist in zip([121, 122], pix_hists): # ax = fig.add_subplot(sub_plt, projection='3d') # for c, z, channel_hist in zip(['b', 'g', 'r'], [20, 10, 0], pix_hist): # cs = [c] * 256 # ax.bar(pix_vals,channel_hist,zs=z,zdir='y',color=cs,alpha=0.618,edgecolor='none',lw=0) # # ax.set_xlabel('Pixel Values') # ax.set_xlim([0, 256]) # ax.set_ylabel('Counts') # ax.set_zlabel('Channels') # plt.show() # cv2.waitKey()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,401
dkgee/tkspam3
refs/heads/master
/dlcvae/ch05/numpy_demo.py
# -*- coding: utf-8 -*- import numpy as np import numpy.random as random # array 数组,numpy中最基本的数据结构 ## 一维数组 # a = [1,2,3,4] # b = np.array(a) # print(b) # print(type(b)) # print(b.shape) # b的维度 # print(b.argmax()) # b中最大值的索引 # print(b.max()) #返回b中最大值 # print(b.mean()) #返回b中平均值 ##二维数组 # c = [[1,7], [3,4], [5,6]] # d = np.array(c) #转换为np的数组 # print(d.shape) # 维度 # print(d.size) # 数组值数量 # print(d.max(axis=0)) # 旋转一圈,找出每个维度最大值,就是在数组上[1,7]\[3,4]\[5,6]组成的1,3,5和7,4,6两个维度中,每个维度中最大值 [5, 7] # print(d.max(axis=1)) # 旋转两圈,相当于没旋转,找出维度1,找出每个组数中的最大值, [7,4,6] # print(d.mean(axis=0)) # print(d.flatten()) #展开数组为1维数组 # print(np.ravel(c)) # 调用静态方法展开1维数组 ## 三维浮点型数组 # e = np.ones((3, 3), dtype=np.float) #创建一个3x3的1维浮点矩阵 # print(e) # f = np.repeat(3, 4) # 创建一个1维值为3的矩阵,重复4次 # print(f) # g = np.zeros((2, 2, 3), dtype=np.uint8) # print(g) # print(g.shape) # # h = np.astype(np.float) # # print(h) # l = np.arange(10) # print(l) # m = np.linspace(0, 6, 5) # print(m) # p = np.array([[1,2,3,4],[5,6,7,8]]) # np.save('p.npy',p) # q = np.load('p.npy') # print(q) ## 多为数组 a = np.arange(24).reshape((2, 3, 4)) # 此为嵌套矩阵,二维矩阵 # print(a) # print(a.shape) # b = a[1][1][1] # print(b) # c = a[:, 2, :] # 表示当前维度所有下表 # print(c) # d = a[:, :, 1] # print(d) # e = a[..., 1] #用以表明没有指明维度值 # print(e) # print('+++++++++++++++1') # f = a[:, 1:, 1:-1] # print(f) # g = np.split(np.arange(9), 3) # print(g) # print('+++++++++++++++2') # h = np.split(np.arange(9), [2, -3]) # print(h) # l0 = np.arange(6).reshape((2, 3)) # print(l0) # l1 = np.arange(6, 12).reshape((2, 3)) # print(l1) # # m = np.vstack((l0, l1)) # print(m) # p = np.hstack((l0, l1)) # print(p) # q = np.concatenate((l0,l1)) # print(q) # r = np.concatenate((l0, l1), axis = -1) # print(r) # s = np.stack((l0, l1)) # print(s) # t = s.transpose((2, 0 , 1)) # print(t) # u = a[0].transpose() # print(u) # v = np.rot90(u, 3) # print(v) # w = np.fliplr(u) # print(w) # x = np.flipud(u) # print(x) # y = np.roll(u, 1) # print(y) # z = np.roll(u, 1, axis=1) # print(z) ###数学运算 # a = np.abs(-1) # print(a) # b = np.sin(np.pi/2) # print(b) # c = np.arctanh(0.462118) # print(c) # d = np.exp(3) # print(d) # f = np.power(2,3) # print(f) # g = np.dot([1,2], [3, 4]) # print(g) # h = np.sqrt(25) # print(h) # l = np.sum([1,2,3,4]) # print(l) # m = np.mean([4, 5, 6, 7]) # print(m) # p = np.std([1, 2, 3, 2, 1, 3, 2, 0]) # print(p) ##位广播运算 # a = np.array([[1,2,3],[4,5,6]]) # b = np.array([[1,2,3],[1,2,3]]) # print(a + b) # print(a - b) # print(a * b) # print(a / b) # print(a ** 2) # print(a ** b) # c = np.array([ # [1,2,3], # [4,5,6], # [7,8,9], # [10, 11, 12] # ]) # d = np.array([2, 2, 2]) # print(c + d) # print(c * d) # print(c - 1) ###linalg # a = np.array([3, 4]) # np.linalg.norm(a) # b = np.array([ # [1,2,3], # [4,5,6], # [7,8,9] # ]) # c = np.array([1, 0, 1]) # print(np.dot(b, c)) # print(np.dot(c, b.T)) # print(np.trace(b)) # print(np.linalg.det(b)) # print(np.linalg.matrix_rank(b)) # d = np.array([ # [2, 1], # [1, 2] # ]) # u,v = np.linalg.eig(d) # print(u) # print(v) # l = np.linalg.cholesky(d) # print(l) # np.dot(l, l.T) # e = np.array([ # [1, 2], # [3, 4] # ]) # U, s, V = np.linalg.svd(e) # print(U) # print(s) # print(V) # print('===============') # S = np.array([ # [s[0], 0], # [0, s[1]] # ]) # print(S) # print(np.dot(U, np.dot(S, V))) # random.seed(42) # random.random(1, 3) # random.random() # random.random((3, 3)) # # random.sample((3, 3)) # # random.random_sample((3,3)) # random.ranf((3,3)) # 5*random.random(10) + 1 # random.uniform(1, 6, 10) # print(random.randint(1, 6, 10))
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,402
dkgee/tkspam3
refs/heads/master
/dlcvae/mxnet/ndarray_01.py
# -*- coding: utf-8 -*- from mxnet import nd x = nd.arange(12) print(x) print(x.shape) print(x.size) x = x.reshape((3, 4)) print(x) y = nd.zeros((2, 3, 4)) print(y) z = nd.ones((3, 4)) print(z) yy = nd.array([[2,1,4,3],[1,2,3,4],[4,3,2,1]]) print(yy) xx = nd.random.normal(0, 1, (3, 4)) print(xx) zz = x + yy print(zz) help(nd.ones_like)
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,403
dkgee/tkspam3
refs/heads/master
/faceai/test_ocr.py
# -*- coding: utf-8 -*- from PIL import Image import pytesseract path = "data/text-img.png" text = pytesseract.image_to_string(Image.open(path), lang='chi_sim') print(text)
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,404
dkgee/tkspam3
refs/heads/master
/dlcvae/tf/tutorial/fashion_mnist.py
# -*- coding: utf-8 -*- #基本训练 # Tensorflow and tf.keras import tensorflow as tf from tensorflow import keras import os # Helper libraries import numpy as np import matplotlib.pyplot as plt print('Tensorflow Version: %s'%tf.__version__) #step01:导入Fashion MNIST数据集 fashion_mnist = keras.datasets.fashion_mnist (train_images, train_lables),(test_images, test_labels) = fashion_mnist.load_data() dirname = os.path.join('datasets', 'fashion-mnist') print("文件缓存目录:%s"%dirname) class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] #step02:探索数据 print('训练数据集维度: %s'%str(train_images.shape)) print('训练数据集数量:%d'%len(train_lables)) print('测试数据集维度: %s'%str(test_images.shape)) print('测试数据集维度: %d'%len(test_labels)) #step03:预处理数据(将图像转换为浮点数,归一化处理) train_images = train_images / 255.0 test_images = test_images / 255.0 #显示训练集第一张图片 # plt.figure() # plt.imshow(train_images[0]) #显示训练集前25张图片 # plt.colorbar() # plt.grid(False) # plt.figure(figsize=(10,10)) # for i in range(25): # plt.subplot(5,5,i+1) # plt.xticks([]) # plt.yticks([]) # plt.grid(False) # plt.imshow(train_images[i], cmap=plt.cm.binary) # plt.xlabel(class_names[train_lables[i]]) # plt.show() #显示图片 #step04:构建模型(设置层、编译模型) 构建和训练网络 model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation=tf.nn.relu), keras.layers.Dense(10, activation=tf.nn.softmax) ]) model.compile(optimizer=tf.train.AdamOptimizer(), loss='sparse_categorical_crossentropy', metrics=['accuracy']) #step05:训练模型 model.fit(train_images, train_lables, epochs=5) model_weights_save_path = './fashion.weight' model_save_path = './fashion.model' model.save_weights(model_weights_save_path) #把模型参数保存为一个HDF5文件 model.save(model_save_path) #把模型保存为一个HDF5文件 # model = keras.models.load_model(model_file_save_path) #step06:评估准确率 # Test accuracy: 0.8727 # Test accuracy: 0.8749 # test_loss, test_acc = model.evaluate(test_images, test_labels) # print('Test Loss:', test_loss) # print('Test accuracy:', test_acc) #step07:作出预测 # predictions = model.predict(test_images) # print('预测的置信度:%s'%str(predictions)) # print('置信度最大值(标签值):%s'%str(np.argmax(predictions[0]))) # print(test_labels[0]) # def plot_image(i, predictions_array, true_label, img): # predictions_array, true_label, img = predictions_array[i], true_label[i], img[i] # plt.grid(False) # plt.xticks([]) # plt.yticks([]) # # plt.imshow(img, cmap=plt.cm.binary) # # predicted_label = np.argmax(predictions_array) # if predicted_label == true_label: # color = 'blue' # else: # color = 'red' # # plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label], # 100*np.max(predictions_array), # class_names[true_label]), # color=color) # # def plot_value_array(i, predictions_array, true_label): # predictions_array, true_label = predictions_array[i], true_label[i] # plt.grid(False) # plt.xticks([]) # plt.yticks([]) # thisplot = plt.bar(range(10), predictions_array, color="#777777") # plt.ylim([0, 1]) # predicted_label = np.argmax(predictions_array) # # thisplot[predicted_label].set_color('red') # thisplot[true_label].set_color('blue') # # i = 0 # plt.figure(figsize=(6,3)) # plt.subplot(1,2,1) # plot_image(i, predictions, test_labels, test_images) # plt.subplot(1,2,2) # plot_value_array(i, predictions, test_labels) # # i = 12 # plt.figure(figsize=(6,3)) # plt.subplot(1,2,1) # plot_image(i, predictions, test_labels, test_images) # plt.subplot(1,2,2) # plot_value_array(i, predictions, test_labels) # # # Plot the first X test images, their predicted label, and the true label # # Color correct predictions in blue, incorrect predictions in red # num_rows = 5 # num_cols = 3 # num_images = num_rows*num_cols # plt.figure(figsize=(2*2*num_cols, 2*num_rows)) # for i in range(num_images): # plt.subplot(num_rows, 2*num_cols, 2*i+1) # plot_image(i, predictions, test_labels, test_images) # plt.subplot(num_rows, 2*num_cols, 2*i+2) # plot_value_array(i, predictions, test_labels) # # # Grab an image from the test dataset # img = test_images[0] # print(img.shape) # # predictions_single = model.predict(img) # print(predictions_single) # # plot_value_array(0, predictions_single, test_labels) # _ = plt.xticks(range(10), class_names, rotation=45) # # np.argmax(predictions_single[0])
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,405
dkgee/tkspam3
refs/heads/master
/mlap/text_classification/test_wrd_naivebayes.py
# -*- coding: utf-8 -*- import pickle from sklearn.naive_bayes import MultinomialNB def readbunchobj(path): file_obj = open(path, "rb") bunch = pickle.load(file_obj) file_obj.close() return bunch ##写入bunch对象 def writebunchobj(path, bunchobj): file_obj = open(path, "wb") pickle.dump(bunchobj, file_obj) file_obj.close() def readfile(path): #读取文件 fp = open(path, "rb") content = fp.read().decode('utf-8') fp.close() return content # 测试数据训练到test_set.dat ,然后计算得出testspace.dat 然后使用训练的向量空间模型 tfidfspace.dat 两者运算得出结果 #导入训练集向量空间 trainpath = "data/train_word_bag/tfidfspace.dat" train_set = readbunchobj(trainpath) #导入测试集向量空间 testpath = "data/test_word_bag/testspace.dat" test_set = readbunchobj(testpath) #应用朴素贝叶斯算法 #alpha: 0.001 alpha越小,迭代次数越多,精度越高 clf = MultinomialNB(alpha=0.001).fit(train_set.tdm, train_set.label) #预测分类结果 predicted = clf.predict(test_set.tdm) total = len(predicted);rate=0 for flabel,file_name,expct_cate in zip(test_set.label, test_set.filenames, predicted): if flabel != expct_cate: rate += 1 print(file_name, ":实际类别:", flabel, "-->预测类别:", expct_cate) #精度 print("error rate:", float(rate) * 100/float(total), "%") ## 多项式贝叶斯算法的分类精度非常高
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,406
dkgee/tkspam3
refs/heads/master
/mlap/text_classification/test_jieba_bunch.py
# -*- coding: utf-8 -*- from sklearn.datasets.base import Bunch import os import pickle def readfile(path): #读取文件 fp = open(path, "rb") content = fp.read().decode('utf-8') fp.close() return content # Bunch类提供一种key,value的对象形式 # target_name:所有分类集名称列表 # label: 每个文件的分类标签列表 # filenames: 文件路径 # contents: 分词后文件词向量形式 bunch = Bunch(target_name=[], label=[], filenames=[], contents=[]) wordbag_path = "data/train_word_bag/" # 分词语料Bunch对象持久化文件路径 wordbag_file = "train_set.dat" # 分词语料Bunch对象持久化文件路径 #seg_path = "data/train_corpus_seg/" #分词后分类语料库路径 seg_path = "data/seg/" #分词后分类语料库路径 catelist = os.listdir(seg_path) bunch.target_name.extend(catelist) #将类别信息保存到bunch对象中 for mydir in catelist: class_path = seg_path + mydir + "/" file_list = os.listdir(class_path) for file_path in file_list: fullname = class_path + file_path bunch.label.append(mydir) # 保存当前文件的分类标签 bunch.filenames.append(fullname) #保存当前文件的文件路径 bunch.contents.append(readfile(fullname).strip()) # 保存文件词向量 if not os.path.exists(wordbag_path): os.makedirs(wordbag_path) wordbag = wordbag_path + wordbag_file #bunch 对象持久化 file_obj = open(wordbag, "wb") pickle.dump(bunch, file_obj) file_obj.close() print("构建文本向量结束")
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,407
dkgee/tkspam3
refs/heads/master
/mlap/text_classification/knn/test_knn.py
# -*- coding: utf-8 -*- from numpy import * import operator from mlap.text_classification.bayes.Nbayes_lib import * k = 3 #夹角余弦距离公式 def cosdist(vector1, vector2): return dot(vector1, vector2) /(linalg.norm(vector1) * linalg.norm(vector2)) #kNN分类器 #测试集:testdata;训练集:trainSet;类别标签:listClasses;k:k个邻居数 def classify(testdata, trainSet, listClasses, k): dataSetSize = trainSet.shape[0] #返回样本集的行数 distances = array(zeros(dataSetSize)) for indx in range(dataSetSize): #计算测试集与训练集之间的距离:夹角余弦 distances[indx] = cosdist(testdata, trainSet[indx]) #根据生成的夹角余弦按从大到小排序,结果为索引号 sortedDistIndicies = argsort(-distances) classCount = {} for i in range(k): #获取角度最小的前k项作为参考项 #按排序顺序返回样本集对应的类别标签 votellabel = listClasses[sortedDistIndicies[i]] #为字典classCount 赋值,相同key,其value加1 classCount[votellabel] = classCount.get(votellabel, 0) + 1 #对分类字典class Count 按value重新排序 # sorted(data.iteritems(), key = operator.itemgetter(1), reverse=True) #该句是按字典值排序的固定用法 #classCount.iteritems():字典迭代器函数 #key:排序参数;operator.itemgetter(1):多级排序 sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True) return sortedClassCount[0][0] #返回序最高的一项 dataSet, listClasses = loadDataSet() nb = NBayes() nb.train_set(dataSet, listClasses) #使用之前贝叶斯分类阶段的数据集,以及生成的tf向量进行分类 print(classify(nb.tf[3], nb.tf, listClasses, k))
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,408
dkgee/tkspam3
refs/heads/master
/faceai/test_img.py
# -*- coding: utf-8 -*- import cv2 filepath = "data/girl.png" img = cv2.imread(filepath) cv2.namedWindow('Girl') cv2.imshow('Girl', img) cv2.waitKey(0) cv2.destroyAllWindows()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,409
dkgee/tkspam3
refs/heads/master
/mlap/text_classification/test_wrd_vector.py
# -*- coding: utf-8 -*- from sklearn.datasets.base import Bunch import pickle from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import TfidfVectorizer def readfile(path): #读取文件 fp = open(path, "rb") content = fp.read().decode('utf-8') fp.close() return content ##1,定义基础函数 ## 读取bunch对象 def readbunchobj(path): file_obj = open(path, "rb") bunch = pickle.load(file_obj) file_obj.close() return bunch ##写入bunch对象 def writebunchobj(path, bunchobj): file_obj = open(path, "wb") pickle.dump(bunchobj, file_obj) file_obj.close() ##2.导入分词后的词向量bunch对象 path = "data/train_word_bag/train_set.dat" bunch = readbunchobj(path) ##3,构建tf-idf词向量空间对象 tfidfspace = Bunch(target_name=bunch.target_name, label=bunch.label, filenames=bunch.filenames, tdm=[], vocabulary={}) #读取停用词 stopword_path = "data/train_word_bag/hlt_stop_words.txt" stpwrdlist = readfile(stopword_path).splitlines() ##4,使用TfidVectorizer初始化向量空间模型 vectorizer = TfidfVectorizer(stop_words=stpwrdlist, sublinear_tf=True, max_df=0.5) transformer = TfidfTransformer() #该类会统计每个词语的tf-idf权值 #文本转为词频矩阵,单独保存字典文件 tfidfspace.tdm = vectorizer.fit_transform(bunch.contents) tfidfspace.vocabulary = vectorizer.vocabulary ##5, 持久化词袋 space_path = "data/train_word_bag/tfidfspace.dat" writebunchobj(space_path, tfidfspace)
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,410
dkgee/tkspam3
refs/heads/master
/geo/auto.py
# -*- coding: utf-8 -*- """ Created on Thu May 10 14:33:16 2018 """ import time from splinter import Browser from selenium import webdriver browser = Browser() url='http://geo.ckcest.cn/' browser.visit(url) #人工登陆 #文献下载#文献下载 browser.visit('http://geo.ckcest.cn/scientific/literature/techdoc_v.html') #然后跳转到一个页码 linkspage = browser.find_link_by_partial_href('#') paperurls=[] for i in range(16,19): page=linkspage[i] page.click() time.sleep(3) papers = browser.find_link_by_partial_href('techdoc_papers.html') browserurl=browser.url for j in range(0,len(papers)): papers[j].click() time.sleep(3) window = browser.windows[1] paperurls.append(window.url) window.close() for i in range(1,len(paperurls)): browser.visit(paperurls[i]) browser.find_by_id('downloadpape').click() time.sleep(15) window = browser.windows[1] browser.visit(window.url) window.close() browser.find_by_id('keyClick').click() #图书专著 driver=webdriver.Firefox() driver.get('http://geo.ckcest.cn/scientific/literature/books.html') time.sleep(3) papers=driver.find_elements_by_xpath("//*[@href]") paperurls=[] for paper in papers: link=paper.get_attribute('href') if 'books_bs.html' in link: paperurls.append(link) driver.quit() browser.visit('http://geo.ckcest.cn/scientific/literature/books.html') time.sleep(3) for i in range(0,len(paperurls)): browser.visit(paperurls[i]) browser.find_by_id('keyFullPaper').click() time.sleep(5) window = browser.windows[1] window.close() #考察报告 browser.visit('http://geo.ckcest.cn/scientific/literature/surveyreport/index.html') #然后跳转到一个页码 time.sleep(3) papers = browser.find_link_by_partial_href('datadetails.html') paperurls=[] for j in range(0,len(papers)): papers[j].click() time.sleep(3) window = browser.windows[1] paperurls.append(window.url) window.close() for i in range(1,len(paperurls)): browser.visit(paperurls[i]) browser.find_by_id('dkeyFullPaper').click() time.sleep(5) window = browser.windows[1] window.close() #遥感影像 browser.visit('http://geo.ckcest.cn/scientific/InternationalData/list.html') #然后跳转到一个页码 linkspage = browser.find_link_by_partial_href('#') paperurls=[] for i in range(11,12):#(10,15) page=linkspage[i] page.click() time.sleep(8) papers = browser.find_link_by_partial_href('remotedetail.html') browserurl=browser.url for j in range(0,len(papers)):#len(papers) papers[j].click() time.sleep(8) window = browser.windows[1] paperurls.append(window.url) window.close() for i in range(1,len(papers)): browser.visit(paperurls[i]) time.sleep(5) remotelist=browser.find_by_id('remotelist') within_elements = remotelist.first.find_by_tag('a') for j in range(0,len(within_elements)): within_elements[j].click() time.sleep(5) browser.windows[0].close()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,411
dkgee/tkspam3
refs/heads/master
/mlap/text_classification/test_jieba_file.py
# -*- coding: utf-8 -*- import os import sys import jieba def savefile(savepath, content): #保存至文件 fp = open(savepath, "w", encoding="utf-8") fp.write(content) fp.close() def readfile(path): #读取文件 fp = open(path, "rb") content = fp.read().decode('utf-8') fp.close() return content ###主程序 corpus_path = "data/corpus/" #未分词分类语料库路径 seg_path = "data/seg/" #分词后的分类语料库路径 catelist = os.listdir(corpus_path) #获取所有子目录 #获取子目录下的所有文件 for mydir in catelist: class_path = corpus_path + mydir + "/" seg_dir = seg_path + mydir + "/" if not os.path.exists(seg_dir): os.makedirs(seg_dir) file_list = os.listdir(class_path) for file_path in file_list: fullname = class_path + file_path content = readfile(fullname).strip() content = content.replace("\r\n", "").strip() content_seg = jieba.cut(content) savefile(seg_dir + file_path, " ".join(content_seg)) print("中文语料分词结束!!!")
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,412
dkgee/tkspam3
refs/heads/master
/geo/ttt.py
#coding=utf-8 import time from selenium import webdriver from splinter import Browser # driver=webdriver.Firefox() # driver.get("http://geo.ckcest.cn/") # print(dir(driver)) # remotelist=[1,2,3,4,5,6] # print("====" + str(len(remotelist))) # for i in range(0,len(remotelist)): # print(i) ####### Browser 功能测试 def testBrowser(url): br=Browser('firefox', headless=True) # open a url br.visit(url) #wait for a moment time.sleep(3) # br.screenshot("D:/csdn", ".png", True) br.execute_script('alert("Hello World")') br.screenshot("D:/baidu.png") br.quit() #find a link and click # br.find_by_text('账号登录').click() # time.sleep(2) # #find username input and fill # br.find_by_id('username').fill('xxxx') # #find password input and fill # br.find_by_id('password').fill('xxxx') # # find login button and click # br.find_by_css('input.logging').click() # time.sleep(2) # #find a link by text and click # br.find_by_text('以后再说').click() # time.sleep(2) # papertitle = br.find_by_css('ul.feedlist_mod >li > div > div.title >h2 > a') # if len(papertitle) > 0: # for title in papertitle: # print(title.html) # print('####################################') # # #imitate mouse scroll down # testBrowser('https://passport.csdn.net/account/login') # testBrowser('https://www.baidu.com/') pp = ['11','22'] pp2 = ['33','44'] tmp = [val for val in pp if not val in pp2] tt = set(pp).union(set(pp2)) print(tt) for x in tt: print(x)
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,413
dkgee/tkspam3
refs/heads/master
/pytorch/demo01/demo_tensor.py
# -*- coding: utf-8 -*- from __future__ import print_function import torch ## 声明一个5 x 3且初始值为0的向量 # x = torch.empty(5, 3) # print(x) ## 构建一个随机向量组,随机数是保留4位小数的浮点数 # x = torch.rand(5, 3) # print(x) ## 构建一个零向量,且数据类型为long的矩阵 # x = torch.zeros(5, 3, dtype=torch.long) # print(x) ## 从数据中直接构建一个向量矩阵, 会转换为保留4位浮点精度的数据 # x = torch.tensor([5.5, 3]) # print(x) ## 基于存在的张量创建矩阵,可以指定矩阵的数据类型 # x = x.new_ones(5, 3, dtype=torch.double) ## 创建所有值为1且为5 x 3的矩阵 # print(x) ## 创建要给像x一样的随机矩阵,且矩阵的数据类型为浮点类型 # x = torch.rand_like(x, dtype=torch.float) # print(x) ## 获取矩阵的尺寸 # print(x.size()) ## 创建一个y矩阵,并加上x矩阵 # y = torch.rand(5, 3) # print(x + y) #第一种加法 # # print(torch.add(x, y)) #第二种加法 ##提供一个输出向量作为参数 # result = torch.empty(5, 3) # torch.add(x, y, out=result) # print(result) ## x或y矩阵自带方法进行向量加法操作 # y.add_(x) # print(y) # print(x[:, 1]) #todo 没看懂 ## 如果需要重新调整向量的大小 x = torch.randn(4, 4) # y = x.view(16) # z = x.view(-1, 8) # print(x) # print(y) # print(z) # print(x.size(), y.size(), z.size()) ## 如果矩阵只有一个元素,使用.item()方法获取值 # x = torch.randn(1) # print(x) # print(x.item()) # a = torch.ones(5) #这是tensor(张量) # print(a) # # b = a.numpy() #这是numpy矩阵 # print(b) # # a.add_(1) #可以使用该方法,该方法使每个元素都加一,但基于该向量计算的所有都会加一 # print(a) # print(b) # import numpy as np # # a = np.ones(5) # 获取一个5维值为1的矩阵 # b = torch.from_numpy(a) # 将矩阵转换为tensor(张量) # np.add(a, 1, out=a) #将矩阵a加一并输出到a # print(a) #a==b都是基于内存计算 # print(b) if torch.cuda.is_available(): device = torch.device("cuda") y = torch.ones_like(x, device=device) x = x.to(device) z = x + y print(z) print(z.to("cpu", torch.double)) else: print("cuda is not available")
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,414
dkgee/tkspam3
refs/heads/master
/dlcvae/redis/redis_demo.py
# -*- coding: utf-8 -*- import redis # r = redis.Redis(host='172.30.154.242', port=7001) # r.set('name','tk') # print(r.get('name')) # pool = redis.ConnectionPool(host='172.30.154.242', port=7001) # r = redis.Redis(connection_pool=pool) # 1,键值对方式 # r.set('name', 'jht') # print(r.get('name').decode()) #解码redis中的字节值 # 2,管道方式(一次执行多个命令) # pipe = r.pipeline(transaction=True) # r.set('name', 'tk') # r.set('name', 'xiaoqiang') # pipe.execute() # print(r.get('name').decode()) # print(r.get('second').decode()) # 3,发布和订阅 class RedisHelper(object): def __init__(self): self.__conn = redis.Redis(host='172.30.154.242', port=7001) self.channel = 'monitor' def publish(self, msg): self.__conn.publish(self.channel, msg) return True def subscribe(self): pub = self.__conn.pubsub() pub.subscribe(self.channel) pub.parse_response() return pub obj = RedisHelper() # obj.publish('hello') # 发布 #订阅 redis_sub = obj.subscribe() while True: msg = redis_sub.parse_response() print(msg[2].decode()) # redis 单兵哨卫模式 # from redis.sentinel import Sentinel # sentinel = Sentinel([('172.30.154.242', 7001),('172.30.154.242', 7002)], socket_timeout=0.1) # redis 集群连接模式 # from rediscluster
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,415
dkgee/tkspam3
refs/heads/master
/mlap/text_classification/knn/test_vector_location.py
# -*- coding: utf-8 -*- import os from numpy import * import matplotlib.pyplot as plt import operator def createDataSet(): group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]]) labels = ['A', 'A', 'B', 'B'] return group, labels dataSet, labels = createDataSet() #绘图 fig = plt.figure() ax = fig.add_subplot(111) indx = 0 for point in dataSet: if labels[indx] == 'A': ax.scatter(point[0], point[1], c='blue', marker='o', linewidths=0, s=300) plt.annotate("(" + str(point[0]) + "," + str(point[1]) + ")", xy=(point[0], point[1])) else: ax.scatter(point[0], point[1], c='red', marker='^', linewidths=0, s=300) plt.annotate("(" + str(point[0]) + "," + str(point[1]) + ")", xy=(point[0], point[1])) indx += 1 #测试数据 testdata = [0.2, 0.2] # 测试该类 ax.scatter(testdata[0], testdata[1], c='green', marker='^', linewidths=0, s=300) plt.annotate("(" + str(testdata[0]) + "," + str(testdata[1]) + ")", xy=(testdata[0], testdata[1])) plt.show()
{"/pytorch/demo02/demo_02.py": ["/pytorch/demo02/Rescale.py"], "/geo/auto_gxr_v3.py": ["/geo/cfg.py", "/pil/lib/geo_predict.py"], "/pil/lib/geo_predict.py": ["/pil/lib/img_tools.py", "/pil/lib/svm_features.py"], "/mlap/text_classification/knn/test_knn.py": ["/mlap/text_classification/bayes/Nbayes_lib.py"]}
56,424
MaxyLee/Vision-Language-Transformer
refs/heads/main
/callbacks/learning_scheduler.py
from __future__ import absolute_import from __future__ import print_function from keras.callbacks import Callback import keras.backend as K class LearningRateScheduler(Callback): """Learning rate scheduler. # Arguments schedule: a function that takes an epoch index as input (integer, indexed from 0) and current learning rate and returns a new learning rate as output (float). verbose: int. 0: quiet, 1: update messages. """ def __init__(self, schedule, tensorboard, init_epoch=0, verbose=0): super(LearningRateScheduler, self).__init__() self.schedule = schedule self.verbose = verbose self.step = 0 self.epoch = init_epoch self.tensorboard = tensorboard self.lr = 0. def on_epoch_begin(self, epoch, logs=None): self.epoch += 1 self.lr = self.schedule(self.epoch) K.set_value(self.model.optimizer.lr, self.lr) if self.verbose > 0: print('\nEpoch %05d: LearningRateScheduler setting learning ' 'rate to %.4f' % (self.epoch, self.lr)) def on_batch_begin(self, batch, logs=None): self.step += 1 def lr_step_decay(lr_start=0.001, steps=[30, 40]): def get_lr(epoch): decay_rate = len(steps) for i, e in enumerate(steps): if epoch < e: decay_rate = i break lr = lr_start / (10 ** (decay_rate)) return lr return get_lr
{"/executor.py": ["/callbacks/eval.py", "/callbacks/learning_scheduler.py", "/loader/loader.py", "/model/vlt_model.py"], "/callbacks/eval.py": ["/loader/loader.py"], "/vlt.py": ["/executor.py"], "/model/vlt_model.py": ["/model/language_backbone.py", "/model/transfromer_model.py"]}
56,425
MaxyLee/Vision-Language-Transformer
refs/heads/main
/executor.py
import json import os from abc import abstractmethod from datetime import datetime import keras import keras.backend as K from keras.callbacks import ModelCheckpoint, TensorBoard from keras.layers import Input, Lambda from keras.models import Model from keras.optimizers import Adam from callbacks.common import RedirectModel from callbacks.eval import Evaluate from callbacks.learning_scheduler import LearningRateScheduler, lr_step_decay from loader.loader import Generator from model.vlt_model import yolo_body, yolo_loss class Executor(object): def __init__(self, config, GPUS=1, debug=False): # settings self.config = config self.debug = debug self.GPUS = GPUS self.input_shape = (self.config.input_size, self.config.input_size, 3) # multiple of 32, hw self.word_len = self.config.word_len self.embed_dim = self.config.embed_dim self.seg_out_stride = self.config.seg_out_stride self.start_epoch = self.config.start_epoch self.n_freeze = 185 + 12 # data init self.dataset = {} self.dataset_len = {} self.load_data() # create model self.yolo_model, self.yolo_body, self.yolo_body_single = self.create_model() # call_back_init self.callbacks = self.build_callbacks() def create_model(self): print('Creating model...') K.clear_session() # get a new session image_input = Input(shape=(self.input_shape)) q_input = Input(shape=[self.word_len, self.embed_dim], name='q_input') h, w, _ = self.input_shape seg_gt = Input(shape=(h//self.seg_out_stride, w//self.seg_out_stride, 1)) # mask_size = self.config.input_size // self.config.seg_out_stride model_body = yolo_body(image_input, q_input, self.config) print('Loading model...') self.load_model(model_body) if self.GPUS > 1: print("Using {} GPUs".format(self.GPUS)) model_body_para = keras.utils.multi_gpu_model(model_body, gpus=self.GPUS) else: print("Using SINGLE GPU Only") model_body_para = model_body model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss', arguments={'batch_size': self.config.batch_size})( [model_body_para.output, seg_gt]) model = Model([model_body_para.input[0], model_body_para.input[1], seg_gt], model_loss) print('Model created.') return model, model_body_para, model_body def load_dataset(self, split): with open(self.config[split], 'rb') as f: data_lines = json.load(f) if self.debug: data_lines = data_lines[:50] set_num = len(data_lines) print('Dataset Loaded: %s, Len: %d' % (split, set_num)) return data_lines, set_num @abstractmethod def build_callbacks(): pass @abstractmethod def load_model(): pass @abstractmethod def load_data(): pass class Trainer(Executor): def __init__(self, config, log_path, verbose=False, **kwargs): self.load_path = config.pretrained_weights self.log_path = log_path self.verbose = verbose self.model_path = os.path.join(self.log_path, 'models') if not os.path.exists(self.model_path): os.makedirs(self.model_path) json.dump(config, open(os.path.join(self.model_path, 'config.json'), 'w')) timestr = datetime.now().strftime('%m_%d_%H_%M_%S') self.tb_path = os.path.join(self.log_path, timestr) if not os.path.exists(self.tb_path): os.makedirs(self.tb_path) json.dump(config, open(os.path.join(self.tb_path, 'config.json'), 'w')) super(Trainer, self).__init__(config, **kwargs) def load_model(self, model_body): path = self.config.pretrained_weights model_body.load_weights(path, by_name=True, skip_mismatch=True) print('Loading weights from {}.'.format(path)) if self.config.free_body in [1, 2]: # Freeze darknet53 body or freeze all but 3 output layers. num = (self.n_freeze, len(model_body.layers) - 3)[self.config.free_body - 1] for i in range(num): model_body.layers[i].trainable = False print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers))) def load_data(self): self.dataset['val'], self.dataset_len['val'] = self.load_dataset('evaluate_set') self.dataset['train'], self.dataset_len['train'] = self.load_dataset('train_set') self.train_generator = Generator(self.dataset['train'], self.config) # self.train_generator.__getitem__(1) def build_callbacks(self): call_backs = [] logging = TensorBoard(log_dir=self.tb_path) call_backs.append(logging) model_evaluate = Evaluate(self.dataset['val'], self.config, tensorboard=logging) call_backs.append(RedirectModel(model_evaluate, self.yolo_body)) checkpoint_map = ModelCheckpoint(self.log_path + '/models/best_map.h5', verbose=1, save_best_only=True, save_weights_only=True, monitor="seg_iou", mode='max') call_backs.append(RedirectModel(checkpoint_map, self.yolo_body_single)) lr_schedue = LearningRateScheduler(lr_step_decay(self.config.lr, self.config.steps), logging, verbose=1, init_epoch=self.config.start_epoch) call_backs.append(lr_schedue) return call_backs def train(self): # Yolo Compile print('Compiling model... ') self.yolo_model.compile(loss={'yolo_loss': lambda y_true, y_pred: y_pred}, optimizer=Adam(lr=self.config.lr)) if self.config.workers > 0: use_multiprocessing = True else: use_multiprocessing = False print('Starting training:') self.yolo_model.fit_generator(self.train_generator, callbacks=self.callbacks, epochs=self.config.epoches, initial_epoch=self.config.start_epoch, verbose=True, workers=self.config.workers, use_multiprocessing=use_multiprocessing, max_queue_size=self.config.max_queue_size ) class Tester(Executor): def __init__(self, config, **kwargs): super(Tester, self).__init__(config, **kwargs) def build_callbacks(self): self.evaluator = RedirectModel(Evaluate(self.dataset['val'], self.config, phase='test'), self.yolo_body) self.evaluator.on_train_begin() def load_data(self): self.dataset['val'], self.dataset_len['val'] = self.load_dataset('evaluate_set') def load_model(self, model_body): model_body.load_weights(self.config.evaluate_model, by_name=False, skip_mismatch=False) print('Load weights {}.'.format(self.config.evaluate_model)) def eval(self): results = dict() self.evaluator.on_epoch_end(-1, results) seg_iou = results['seg_iou'] seg_prec = results['seg_prec'] # dump results to text file if not os.path.exists('result/'): os.mkdir('result/') from datetime import datetime timestr = datetime.now().strftime('%m_%d_%H_%M_%S') with open('result/result_%s.txt' % (timestr), 'w') as f_w: f_w.write('segmentation result:' + '\n') f_w.write('seg_iou: %.4f\n' % (seg_iou)) for item in seg_prec: f_w.write('prec@%.2f: %.4f' % (item, seg_prec[item])+'\n') f_w.write('\n') class Debugger(Executor): def __init__(self, config, **kwargs): self.config = config self.debug = True self.dataset, self.dataset_len = self.load_dataset('train_set') self.train_generator = Generator(self.dataset, self.config) self.train_generator.__getitem__(1) kwargs.update({'GPUS': 1, 'debug': True}) super(Debugger, self).__init__(config, **kwargs) def build_callbacks(self): return None def load_data(self): return None def load_model(self, model_body): return None def run(self): self.yolo_model.summary() self.yolo_model.compile(loss={'yolo_loss': lambda y_true, y_pred: y_pred}, optimizer=Adam(lr=self.config.lr))
{"/executor.py": ["/callbacks/eval.py", "/callbacks/learning_scheduler.py", "/loader/loader.py", "/model/vlt_model.py"], "/callbacks/eval.py": ["/loader/loader.py"], "/vlt.py": ["/executor.py"], "/model/vlt_model.py": ["/model/language_backbone.py", "/model/transfromer_model.py"]}
56,426
MaxyLee/Vision-Language-Transformer
refs/heads/main
/callbacks/eval.py
import keras import numpy as np from loader.loader import get_random_data import cv2 import keras.backend as K from matplotlib.pyplot import cm import spacy import progressbar class Evaluate(keras.callbacks.Callback): """ Evaluation callback for arbitrary datasets. """ def __init__( self, data, config, tensorboard=None, verbose=1, phase='train' ): self.val_data = data self.tensorboard = tensorboard self.verbose = verbose self.vis_id = [i for i in np.random.randint(0, len(data), 200)] self.batch_size = max(config.batch_size//2, 1) self.colors = np.array(cm.hsv(np.linspace(0, 1, 10)).tolist()) * 255 self.input_shape = (config.input_size, config.input_size) # multiple of 32, hw self.config = config self.word_embed = spacy.load(config.word_embed) self.word_len = config.word_len self.seg_min_overlap = config.segment_thresh if phase == 'test': self.log_images = config.log_images self.multi_thres = config.multi_thres else: self.log_images = 0 self.multi_thres = False self.input_image_shape = K.placeholder(shape=(2,)) self.sess = K.get_session() self.eval_save_images_id = [i for i in np.random.randint(0, len(self.val_data), 200)] super(Evaluate, self).__init__() def on_epoch_end(self, epoch, logs=None): if logs is None: logs = {} # run evaluation self.seg_iou, self.seg_prec = self.evaluate() if self.tensorboard is not None and self.tensorboard.writer is not None: import tensorflow as tf summary = tf.Summary() summary_value = summary.value.add() summary_value.simple_value = self.seg_iou summary_value.tag = "seg_iou" for item in self.seg_prec: summary_value = summary.value.add() summary_value.simple_value = self.seg_prec[item] summary_value.tag = "map@%.2f" % item self.tensorboard.writer.add_summary(summary, epoch) logs['seg_iou'] = self.seg_iou logs['seg_prec'] = self.seg_prec if self.verbose == 1: print('seg_iou: {:.4f}'.format(self.seg_iou)) def evaluate(self): prec_all = dict() img_id = 0 iou_all = 0. test_batch_size = self.batch_size for start in progressbar.progressbar(range(0, len(self.val_data), test_batch_size), prefix='evaluation: '): end = start + test_batch_size batch_data = self.val_data[start:end] images = [] images_ori = [] files_id = [] word_vecs = [] sentences = [] gt_segs = [] for data in batch_data: image_data, word_vec, image, sentence, seg_map = get_random_data(data, self.input_shape, self.word_embed, self.config, train_mode=False) # box is [1,5] sentences.extend(sentence) word_vecs.extend(word_vec) # evaluate each sentence corresponding to the same image for ___ in range(len(sentence)): images.append(image_data) images_ori.append(image) files_id.append(img_id) gt_segs.append(seg_map) img_id += 1 images = np.array(images) word_vecs = np.array(word_vecs) mask_outs = self.model.predict_on_batch([images, word_vecs]) mask_outs = self.sigmoid_(mask_outs) # logit to sigmoid batch_size = mask_outs.shape[0] for i in range(batch_size): ih = gt_segs[i].shape[0] iw = gt_segs[i].shape[1] w, h = self.input_shape scale = min(w / iw, h / ih) nw = int(iw * scale) nh = int(ih * scale) dx = (w - nw) // 2 dy = (h - nh) // 2 pred_seg = mask_outs[i, :, :, 0] pred_seg = cv2.resize(pred_seg, self.input_shape) pred_seg = pred_seg[dy:nh + dy, dx:nw + dx, ...] pred_seg = cv2.resize(pred_seg, (gt_segs[i].shape[1], gt_segs[i].shape[0])) pred_seg = np.reshape(pred_seg, [pred_seg.shape[0], pred_seg.shape[1], 1]) # segmentation eval iou, prec = self.cal_seg_iou(gt_segs[i], pred_seg, self.seg_min_overlap) iou_all += iou for item in prec: if prec_all.get(item): prec_all[item] += prec[item] else: prec_all[item] = prec[item] if self.log_images: sent = sentences[i]['sent'] cv2.imwrite('log/out_img/'+str(files_id[i])+'_'+sent+'_pred.png', pred_seg * 255) cv2.imwrite('log/out_img/'+str(files_id[i])+'_'+sent+'_gt.png', gt_segs[i]) cv2.imwrite('log/out_img/'+str(files_id[i])+'_'+sent+'_img.png', images[i][dy:nh + dy, dx:nw + dx, ...] * 255) pred_seg = iou_all / img_id for item in prec_all: prec_all[item] /= img_id return pred_seg, prec_all def cal_seg_iou(self, gt, pred, thresh=0.5): t = np.array(pred > thresh) p = gt > 0. intersection = np.logical_and(t, p) union = np.logical_or(t, p) iou = (np.sum(intersection > 0) + 1e-10) / (np.sum(union > 0) + 1e-10) prec = dict() thresholds = np.arange(0.5, 1, 0.05) for thresh in thresholds: prec[thresh] = float(iou > thresh) return iou, prec def sigmoid_(self, x): return (1. + 1e-9) / (1. + np.exp(-x) + 1e-9)
{"/executor.py": ["/callbacks/eval.py", "/callbacks/learning_scheduler.py", "/loader/loader.py", "/model/vlt_model.py"], "/callbacks/eval.py": ["/loader/loader.py"], "/vlt.py": ["/executor.py"], "/model/vlt_model.py": ["/model/language_backbone.py", "/model/transfromer_model.py"]}
56,427
MaxyLee/Vision-Language-Transformer
refs/heads/main
/data/data_process_v2.py
# encoding=utf8 import numpy as np import os from refer import REFER import cv2 import argparse from tqdm import tqdm import json parser = argparse.ArgumentParser(description='Data preparation') parser.add_argument('--data_root', type=str) parser.add_argument('--output_dir', type=str) parser.add_argument('--dataset', type=str, choices=['refcoco', 'refcoco+', 'refcocog', 'refclef'], default='refcoco') parser.add_argument('--split', type=str, default='umd') parser.add_argument('--generate_mask', action='store_true') args = parser.parse_args() img_path = os.path.join(args.data_root, 'images', 'train2014') h, w = (416, 416) refer = REFER(args.data_root, args.dataset, args.split) print('dataset [%s_%s] contains: ' % (args.dataset, args.split)) ref_ids = refer.getRefIds() image_ids = refer.getImgIds() print('%s expressions for %s refs in %s images.' % (len(refer.Sents), len(ref_ids), len(image_ids))) print('\nAmong them:') if args.dataset == 'refclef': if args.split == 'unc': splits = ['train', 'val', 'testA', 'testB', 'testC'] else: splits = ['train', 'val', 'test'] elif args.dataset == 'refcoco': splits = ['train', 'val', 'testA', 'testB'] elif args.dataset == 'refcoco+': splits = ['train', 'val', 'testA', 'testB'] elif args.dataset == 'refcocog': splits = ['train', 'val', 'test'] # we don't have test split for refcocog right now. for split in splits: ref_ids = refer.getRefIds(split=split) print('%s refs are in split [%s].' % (len(ref_ids), split)) def cat_process(cat): if cat >= 1 and cat <= 11: cat = cat - 1 elif cat >= 13 and cat <= 25: cat = cat - 2 elif cat >= 27 and cat <= 28: cat = cat - 3 elif cat >= 31 and cat <= 44: cat = cat - 5 elif cat >= 46 and cat <= 65: cat = cat - 6 elif cat == 67: cat = cat - 7 elif cat == 70: cat = cat - 9 elif cat >= 72 and cat <= 82: cat = cat - 10 elif cat >= 84 and cat <= 90: cat = cat - 11 return cat def bbox_process(bbox): x_min = int(bbox[0]) y_min = int(bbox[1]) x_max = x_min + int(bbox[2]) y_max = y_min + int(bbox[3]) return list(map(int, [x_min, y_min, x_max, y_max])) def prepare_dataset(dataset, splits, output_dir, generate_mask=False): ann_path = os.path.join(output_dir, 'anns', dataset) mask_path = os.path.join(output_dir, 'masks', dataset) if not os.path.exists(ann_path): os.makedirs(ann_path) if not os.path.exists(mask_path): os.makedirs(mask_path) for split in splits: dataset_array = [] ref_ids = refer.getRefIds(split=split) print('Processing split:{} - Len: {}'.format(split, np.alen(ref_ids))) for i in tqdm(ref_ids): ref_dict = {} refs = refer.Refs[i] bboxs = refer.getRefBox(i) sentences = refs['sentences'] image_urls = refer.loadImgs(image_ids=refs['image_id'])[0] cat = cat_process(refs['category_id']) image_urls = image_urls['file_name'] if dataset == 'refclef' and image_urls in ['19579.jpg', '17975.jpg', '19575.jpg']: continue box_info = bbox_process(bboxs) ref_dict['bbox'] = box_info ref_dict['cat'] = cat ref_dict['segment_id'] = i ref_dict['img_name'] = image_urls if generate_mask: cv2.imwrite(os.path.join(mask_path, str(i)+'.png'), refer.getMask(refs)['mask'] * 255) sent_dict = [] for i, sent in enumerate(sentences): sent_dict.append({ 'idx': i, 'sent_id': sent['sent_id'], 'sent': sent['sent'].strip()}) ref_dict['sentences'] = sent_dict ref_dict['sentences_num'] = len(sent_dict) dataset_array.append(ref_dict) print('Dumping json file...') with open(os.path.join(output_dir, 'anns', dataset, split + '.json'), 'w') as f: json.dump(dataset_array, f) prepare_dataset(args.dataset, splits, args.output_dir, args.generate_mask)
{"/executor.py": ["/callbacks/eval.py", "/callbacks/learning_scheduler.py", "/loader/loader.py", "/model/vlt_model.py"], "/callbacks/eval.py": ["/loader/loader.py"], "/vlt.py": ["/executor.py"], "/model/vlt_model.py": ["/model/language_backbone.py", "/model/transfromer_model.py"]}
56,428
MaxyLee/Vision-Language-Transformer
refs/heads/main
/loader/loader.py
import numpy as np import cv2 import os import spacy import keras class Generator(keras.utils.Sequence): """ Abstract generator class. """ def __init__( self, data, config, shuffle=True, train_mode=True, ): self.shuffle = shuffle self.data = data self.config = config self.train_mode = train_mode self.batch_size = config.batch_size self.embed = spacy.load(config.word_embed) self.input_shape = (config.input_size, config.input_size) self.on_epoch_end() def on_epoch_end(self): if self.shuffle: np.random.shuffle(self.data) self.group() def size(self): return len(self.data) def group(self): """ Order the images according to self.order and makes groups of self.batch_size. """ # divide into groups, one group = one batch self.groups = [[self.data[x % len(self.data)] for x in range(i, i + self.batch_size)] for i in range(0, len(self.data), self.batch_size)] def __len__(self): """ Number of batches for generator. """ return len(self.groups) def get_batch(self, datas): size = len(datas) image_data = np.empty([size, self.input_shape[0], self.input_shape[1], 3]) word_data = np.empty([size, self.config.word_len, self.config.embed_dim]) seg_data = np.empty([size, self.input_shape[0] // self.config.seg_out_stride, self.input_shape[1] // self.config.seg_out_stride, 1]) for (i, data) in enumerate(datas): image, word_vec, seg_map = get_random_data(data, self.input_shape, self.embed, self.config, train_mode=self.train_mode) word_data[i] = word_vec image_data[i] = image seg_data[i] = seg_map return image_data, word_data, seg_data def __getitem__(self, index): """ Keras sequence method for generating batches. """ group = self.groups[index] image_data, word_data, seg_data = self.get_batch(group) # print(np.shape(inputs)) return [image_data, word_data, seg_data], np.zeros(self.batch_size) def qlist_to_vec(max_length, q_list, embed, emb_size=300): ''' note: 2018.10.3 use for process sentences ''' q_list = q_list.split() glove_matrix = np.zeros((max_length, emb_size), dtype=float) q_len = min(max_length, len(q_list)) for i in range(q_len): glove_matrix[i, :] = embed(u'%s' % q_list[i]).vector return glove_matrix def get_random_data(ref, input_shape, embed, config, train_mode=True, max_boxes=1): '''random preprocessing for real-time data augmentation''' SEG_DIR = config.seg_gt_path h, w = input_shape seg_id = ref['segment_id'] # box = ref['bbox'] sentences = ref['sentences'] choose_index = np.random.choice(ref['sentences_num']) word_vec = qlist_to_vec(config.word_len, sentences[choose_index]['sent'], embed) image = cv2.imread(os.path.join(config.image_path, ref['img_name'])) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) ih, iw, _ = image.shape if not train_mode: ori_image = image.copy() scale = min(w / iw, h / ih) nw = int(iw * scale) nh = int(ih * scale) dx = (w - nw) // 2 dy = (h - nh) // 2 image = cv2.resize(image, (nw, nh), interpolation=cv2.INTER_CUBIC) image_data = np.full((w, h, 3), (0.5, 0.5, 0.5)) image_data[dy:dy+nh, dx:dx+nw, :] = image / 255. seg_map = cv2.imread(os.path.join(SEG_DIR, str(seg_id)+'.png'), flags=cv2.IMREAD_GRAYSCALE) if train_mode: seg_map = cv2.resize(seg_map, (nw, nh), interpolation=cv2.INTER_CUBIC) seg_map_data = np.zeros((w, h)) seg_map_data[dy:dy+nh, dx:dx+nw] = seg_map / 255 seg_map_data = cv2.resize(seg_map_data, ( w // config.seg_out_stride, h // config.seg_out_stride), interpolation=cv2.INTER_NEAREST) seg_map_data = seg_map_data[:, :, None] if not train_mode: word_vec = [qlist_to_vec(config.word_len, sent['sent'], embed) for sent in sentences] return image_data, word_vec, ori_image, sentences, seg_map[:, :, None] return image_data, word_vec, seg_map_data
{"/executor.py": ["/callbacks/eval.py", "/callbacks/learning_scheduler.py", "/loader/loader.py", "/model/vlt_model.py"], "/callbacks/eval.py": ["/loader/loader.py"], "/vlt.py": ["/executor.py"], "/model/vlt_model.py": ["/model/language_backbone.py", "/model/transfromer_model.py"]}
56,429
MaxyLee/Vision-Language-Transformer
refs/heads/main
/model/transfromer_model.py
from keras import layers as L from keras_transformer import get_encoder_component, get_decoder_component from keras_multi_head import MultiHeadAttention from keras_pos_embd import TrigPosEmbedding def ref_tf(encoder_input, decoder_input, feat_size, encoder_num=2, decoder_num=2, head_num=8, hidden_dim=256, num_query=32, attention_activation='relu', feed_forward_activation='relu', dropout_rate=0.1, trainable=True, balance=True): spatial_size = feat_size * feat_size encoder_embed = TrigPosEmbedding( mode=TrigPosEmbedding.MODE_ADD, name='Encoder-Embedding', )(encoder_input) encoded_layer = get_encoders( encoder_num=encoder_num, input_layer=encoder_embed, head_num=head_num, hidden_dim=hidden_dim, attention_activation=attention_activation, feed_forward_activation=feed_forward_activation, dropout_rate=dropout_rate, trainable=trainable, ) decoder_embed = TrigPosEmbedding( mode=TrigPosEmbedding.MODE_ADD, name='Decoder-Embedding', )(decoder_input) decoded_layer = get_decoders( decoder_num=decoder_num, input_layer=decoder_embed, encoded_layer=encoded_layer, head_num=head_num, hidden_dim=hidden_dim, attention_activation=attention_activation, feed_forward_activation=feed_forward_activation, dropout_rate=dropout_rate, trainable=trainable, ) if balance: query_proj = L.Dense(hidden_dim, activation='relu')(decoder_input) output_proj = L.Dense(hidden_dim, activation='relu')(decoded_layer) output_proj = L.Concatenate()([output_proj, query_proj]) output_proj = L.Dense(hidden_dim, activation='relu')(output_proj) query_confident = L.Dense(1, activation='sigmoid')(output_proj) weighted_output = L.Multiply()([query_confident, decoded_layer]) else: weighted_output = decoded_layer output_layer = L.Dense(spatial_size, activation='relu')(weighted_output) output_layer = L.Reshape((num_query, feat_size, feat_size))(output_layer) output_layer = L.Permute((2, 3, 1))(output_layer) return output_layer def lang_tf_enc(vision_input, lang_input, head_num=8, hidden_dim=256): decoder_embed_lang = TrigPosEmbedding( mode=TrigPosEmbedding.MODE_ADD, name='Fusion-Lang-Decoder-Embedding', )(lang_input) decoder_embed_vis = TrigPosEmbedding( mode=TrigPosEmbedding.MODE_ADD, name='Fusion-Vis-Decoder-Embedding', )(vision_input) q_inp = L.Dense(hidden_dim, activation='relu')(decoder_embed_vis) k_inp = L.Dense(hidden_dim, activation='relu')(decoder_embed_lang) v_inp = L.Dense(hidden_dim, activation='relu')(decoder_embed_lang) decoded_layer = MultiHeadAttention(head_num=head_num)( [q_inp, k_inp, v_inp]) add_layer = L.Add(name='Fusion-Add')([decoded_layer, vision_input]) return add_layer def get_encoders(encoder_num, input_layer, head_num, hidden_dim, attention_activation=None, feed_forward_activation='relu', dropout_rate=0.0, trainable=True, name_prefix=''): """Get encoders. :param encoder_num: Number of encoder components. :param input_layer: Input layer. :param head_num: Number of heads in multi-head self-attention. :param hidden_dim: Hidden dimension of feed forward layer. :param attention_activation: Activation for multi-head self-attention. :param feed_forward_activation: Activation for feed-forward layer. :param dropout_rate: Dropout rate. :param trainable: Whether the layers are trainable. :return: Output layer. """ last_layer = input_layer for i in range(encoder_num): last_layer = get_encoder_component( name=name_prefix+'Encoder-%d' % (i + 1), input_layer=last_layer, head_num=head_num, hidden_dim=hidden_dim, attention_activation=attention_activation, feed_forward_activation=feed_forward_activation, dropout_rate=dropout_rate, trainable=trainable, ) return last_layer def get_decoders(decoder_num, input_layer, encoded_layer, head_num, hidden_dim, attention_activation=None, feed_forward_activation='relu', dropout_rate=0.0, trainable=True, name_prefix=''): """Get decoders. :param decoder_num: Number of decoder components. :param input_layer: Input layer. :param encoded_layer: Encoded layer from encoder. :param head_num: Number of heads in multi-head self-attention. :param hidden_dim: Hidden dimension of feed forward layer. :param attention_activation: Activation for multi-head self-attention. :param feed_forward_activation: Activation for feed-forward layer. :param dropout_rate: Dropout rate. :param trainable: Whether the layers are trainable. :return: Output layer. """ last_layer = input_layer for i in range(decoder_num): last_layer = get_decoder_component( name=name_prefix+'Decoder-%d' % (i + 1), input_layer=last_layer, encoded_layer=encoded_layer, head_num=head_num, hidden_dim=hidden_dim, attention_activation=attention_activation, feed_forward_activation=feed_forward_activation, dropout_rate=dropout_rate, trainable=trainable, ) return last_layer
{"/executor.py": ["/callbacks/eval.py", "/callbacks/learning_scheduler.py", "/loader/loader.py", "/model/vlt_model.py"], "/callbacks/eval.py": ["/loader/loader.py"], "/vlt.py": ["/executor.py"], "/model/vlt_model.py": ["/model/language_backbone.py", "/model/transfromer_model.py"]}
56,430
MaxyLee/Vision-Language-Transformer
refs/heads/main
/vlt.py
import argparse import os import numpy as np import tensorflow as tf from tensorflow.python.client import device_lib from yacs.config import CfgNode as CN from executor import Tester, Trainer, Debugger MODES = ['train', 'test', 'debug'] parser = argparse.ArgumentParser() parser.add_argument('phase', choices=MODES) parser.add_argument('config_path') parser.add_argument('--debug', action='store_true') parser.add_argument('--verbose', action='store_true') args = parser.parse_args() assert (args.phase in MODES) if not args.verbose: os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' tf.get_logger().setLevel('ERROR') tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) with open('config/base.yaml', 'r') as f: _C = CN.load_cfg(f) if __name__ == "__main__": config = _C.clone() config.merge_from_file(args.config_path) config.freeze() print(config) print('\n\n--------------------------') print('PHASE:{}\n'.format(args.phase)) config_basename = os.path.basename(args.config_path) config_name = os.path.splitext(config_basename)[0] log_path = config.log_path + '_' + config_name np.random.seed(config.seed) tf.set_random_seed(config.seed) local_device_protos = device_lib.list_local_devices() gpu_devices = [x.name for x in local_device_protos if x.device_type == 'GPU'] GPU_COUNTS = len(gpu_devices) print("{} GPUs detected:".format(GPU_COUNTS)) print(gpu_devices) if __name__ == "__main__": if (args.phase == 'train'): trainer = Trainer(config, log_path, GPUS=GPU_COUNTS, debug=args.debug, verbose=args.verbose) trainer.train() elif (args.phase == 'test'): tester = Tester(config, GPUS=GPU_COUNTS, debug=args.debug) tester.eval() elif (args.phase == 'debug'): debugger = Debugger(config) debugger.run() print('Exited.')
{"/executor.py": ["/callbacks/eval.py", "/callbacks/learning_scheduler.py", "/loader/loader.py", "/model/vlt_model.py"], "/callbacks/eval.py": ["/loader/loader.py"], "/vlt.py": ["/executor.py"], "/model/vlt_model.py": ["/model/language_backbone.py", "/model/transfromer_model.py"]}
56,431
MaxyLee/Vision-Language-Transformer
refs/heads/main
/model/vlt_model.py
"""YOLO_v3 Model Defined in Keras.""" import tensorflow as tf from keras import backend as K from keras import layers as L from keras.models import Model from model.language_backbone import build_nlp_model from model.transfromer_model import ref_tf, lang_tf_enc from model import utils as utils from model import visual_backbone as V def simple_fusion(F_v, f_q, dim=1024): """ :param F_v: visual features (N,w,h,d) :param f_q: GRU output (N,d_q) :param dim: project dimensions default: 1024 :return: F_m: simple fusion of Fv and fq (N,w,h,d) """ out_size = K.int_shape(F_v)[1] # Fv project (use darknet_resblock get better performance) F_v_proj = V.darknet_resblock(F_v, dim//2) # fq_project f_q_proj = L.Dense(dim, activation='linear')(f_q) f_q_proj = L.advanced_activations.LeakyReLU(alpha=0.1)( L.normalization.BatchNormalization()(f_q_proj) ) f_q_proj = L.Lambda(utils.expand_and_tile, arguments={'outsize': out_size})(f_q_proj) # simple elemwise multipy F_m = L.Multiply()([F_v_proj, f_q_proj]) F_m = L.advanced_activations.LeakyReLU(alpha=0.1)( L.normalization.BatchNormalization()(F_m) ) return F_m def up_proj_cat_proj(x, y, di=256, do=256): x = L.UpSampling2D()(x) y = V.DarknetConv2D_BN_Leaky(di, (1, 1))(y) out = L.Concatenate()([x, y]) out = V.DarknetConv2D_BN_Leaky(do, (1, 1))(out) return out def proj_cat(x, y, di=256): if K.int_shape(x)[-1] > di: x = V.DarknetConv2D_BN_Leaky(di, (1, 1))(x) x = V.DarknetConv2D_BN_Leaky(di // 2, (1, 1))(x) x = V.DarknetConv2D_BN_Leaky(di, (3, 3))(x) out = L.Concatenate()([x, y]) return out def pool_proj_cat_proj(x, y, di=256, do=256): y = L.AveragePooling2D((2, 2))(y) y = V.DarknetConv2D_BN_Leaky(di, (1, 1))(y) out = L.Concatenate()([x, y]) out = V.DarknetConv2D_BN_Leaky(do, (1, 1))(out) return out def make_multitask_braches(Fv, fq, fq_word, config): # fq: bs, 1024 # fq_word: bs, 15, 1024 Fm = simple_fusion(Fv[0], fq, config.jemb_dim) # 13, 13, 1024 Fm_mid_query = up_proj_cat_proj(Fm, Fv[1], K.int_shape(Fv[1],)[-1], K.int_shape(Fm)[-1]//2) # 26, 26, 512 Fm_query = pool_proj_cat_proj(Fm_mid_query, Fv[2], K.int_shape(Fv[2])[-1], K.int_shape(Fm)[-1]//2) # 26, 26, 512 Fm_mid_tf = proj_cat(Fm_query, Fm_mid_query, K.int_shape(Fm)[-1]//2) # 26, 26, 1024 F_tf = up_proj_cat_proj(Fm, Fm_mid_tf, K.int_shape(Fm)[-1] // 2) F_tf = V.DarknetConv2D_BN_Leaky(config.hidden_dim, (1, 1))(F_tf) # Fm_query: bs, Hm, Wm, C (None, 26, 26, 512) # Fm_top_tf : bs, Hc, Wc, C (None, 26, 26, 512) query_out = vlt_querynet(Fm_query, config) mask_out = vlt_transformer(F_tf, fq_word, query_out, config) mask_out = vlt_postproc(mask_out, Fm_query, config) return mask_out def vlt_transformer(F_tf, fq_word, query_out, config): # F_tf: (None, 26, 26, 512) # query_out: (None, 26, 26, Nq) flatten_length = K.int_shape(F_tf)[1] * K.int_shape(F_tf)[2] F_tf_flat = L.Reshape([flatten_length, config.hidden_dim])(F_tf) # (None, 676, 512) query_flat = L.Reshape([flatten_length, config.num_query])(query_out) # (None, 676, Nq) query_flat = L.Permute((2, 1), input_shape=(676, config.num_query))(query_flat) # (None, Nq, 676) query_flat = L.Dense(config.hidden_dim, activation='relu')(query_flat) # (None, Nq, 512) lang_feat = L.Dense(config.hidden_dim, activation='relu')(fq_word) # (None, Nq, 512) query_input = lang_tf_enc(vision_input=query_flat, lang_input=lang_feat, hidden_dim=config.transformer_hidden_dim, head_num=config.transformer_head_num) tf_out = ref_tf(encoder_input=F_tf_flat, decoder_input=query_input, feat_size=26, encoder_num=config.transformer_encoder_num, decoder_num=config.transformer_decoder_num, hidden_dim=config.transformer_hidden_dim, head_num=config.transformer_head_num, num_query=config.num_query) tf_out = V.DarknetConv2D_BN_Leaky(config.hidden_dim, [3, 3])(tf_out) return tf_out # (None, 26, 26, 1) def vlt_postproc(tf_out, Fm_query, config): tf_out = V.DarknetConv2D_BN_Leaky(config.hidden_dim, [3, 3])(tf_out) # if config.concate_lower_feat: # tf_out = L.Concatenate()([tf_out, Fm_query]) tf_out = V.DarknetConv2D_BN_Leaky(config.hidden_dim, [3, 3])(tf_out) if config.seg_out_stride <= 8: tf_out = L.UpSampling2D()(tf_out) tf_out = V.DarknetConv2D_BN_Leaky(config.hidden_dim, [3, 3])(tf_out) if config.seg_out_stride <= 4: tf_out = L.UpSampling2D()(tf_out) tf_out = V.DarknetConv2D_BN_Leaky(config.hidden_dim, [3, 3])(tf_out) if config.seg_out_stride <= 2: tf_out = L.UpSampling2D()(tf_out) tf_out = V.DarknetConv2D_BN_Leaky(config.hidden_dim, [3, 3])(tf_out) tf_out = V.DarknetConv2D(1, [3, 3])(tf_out) return tf_out def vlt_querynet(x, config): x = L.Lambda(utils.concat_coord)(x) x = V.DarknetConv2D_BN_Leaky(K.int_shape(x)[-1], (3, 3))(x) x = V.DarknetConv2D_BN_Leaky(K.int_shape(x)[-1], (3, 3))(x) x = V.DarknetConv2D_BN_Leaky(K.int_shape(x)[-1], (3, 3))(x) x = V.DarknetConv2D(config.num_query, (1, 1))(x) return x # (bs, H, W, n_query) (None, 52, 52, config.num_query) def yolo_body(inputs, q_input, config): """ :param inputs: image :param q_input: word embeding :return: regresion , attention map """ """Create Multi-Modal YOLO_V3 model CNN body in Keras.""" darknet = Model(inputs, V.darknet_body(inputs)) Fv = [darknet.output, darknet.layers[152].output, darknet.layers[92].output] fq, fq_word = build_nlp_model(q_input=q_input, rnn_dim=config.rnn_hidden_size, bidirection=config.rnn_bidirectional, dropout=config.rnn_drop_out, lang_att=config.lang_att, return_raw=True) mask_out = make_multitask_braches(Fv, fq, fq_word, config) return Model([inputs, q_input], [mask_out]) def yolo_loss(args, batch_size, print_loss=False): mask_out = args[0] mask_gt = args[1] loss = 0 m = K.shape(mask_out)[0] # batch size, tensor mf = K.cast(m, K.dtype(mask_out)) mask_loss = K.binary_crossentropy(mask_gt, mask_out, from_logits=True) mask_loss = K.sum(mask_loss) / mf loss += mask_loss if print_loss: loss = tf.Print(loss, ['mask: ', mask_loss]) return K.expand_dims(loss, axis=0)
{"/executor.py": ["/callbacks/eval.py", "/callbacks/learning_scheduler.py", "/loader/loader.py", "/model/vlt_model.py"], "/callbacks/eval.py": ["/loader/loader.py"], "/vlt.py": ["/executor.py"], "/model/vlt_model.py": ["/model/language_backbone.py", "/model/transfromer_model.py"]}
56,432
MaxyLee/Vision-Language-Transformer
refs/heads/main
/model/language_backbone.py
import tensorflow as tf from keras.layers.recurrent import GRU from keras.layers import Bidirectional, Dense, Lambda, Masking, Dropout, Multiply import keras.backend as K def gru_rnn_module_a(word_embs, rnn_dim, dropout, return_seq): with tf.variable_scope('gru_module'): if dropout > 0.: lstm_cell = Bidirectional(GRU(rnn_dim, return_sequences=return_seq, dropout=dropout), merge_mode="sum")(word_embs) else: lstm_cell = Bidirectional(GRU(rnn_dim, return_sequences=return_seq), merge_mode="sum")(word_embs) return lstm_cell def gru_rnn_module_s(word_embs, rnn_dim, dropout, return_seq): with tf.variable_scope('gru_module'): if dropout > 0.: lstm_cell = GRU(rnn_dim, dropout=dropout, return_sequences=return_seq)(word_embs) else: lstm_cell = GRU(rnn_dim, return_sequences=return_seq)(word_embs) return lstm_cell def build_nlp_model(q_input, rnn_dim, bidirection=True, dropout=0.1, lang_att=True, return_raw=False): if not lang_att: q_input = Masking()(q_input) if bidirection: bi_rnn_raw = gru_rnn_module_a(q_input, rnn_dim, dropout, lang_att) else: bi_rnn_raw = gru_rnn_module_s(q_input, rnn_dim, dropout, lang_att) if lang_att: bi_rnn_weights = Dense(K.int_shape(bi_rnn_raw)[-1], activation='tanh')(bi_rnn_raw) bi_rnn_weights = Dropout(0.1)(bi_rnn_weights) bi_rnn_weights = Lambda(K.softmax, arguments={'axis': 1})(bi_rnn_weights) bi_rnn = Multiply()([bi_rnn_raw, bi_rnn_weights]) bi_rnn = Lambda(K.sum, arguments={'axis': 1})(bi_rnn) if return_raw: return bi_rnn, bi_rnn_raw else: return bi_rnn else: return bi_rnn_raw
{"/executor.py": ["/callbacks/eval.py", "/callbacks/learning_scheduler.py", "/loader/loader.py", "/model/vlt_model.py"], "/callbacks/eval.py": ["/loader/loader.py"], "/vlt.py": ["/executor.py"], "/model/vlt_model.py": ["/model/language_backbone.py", "/model/transfromer_model.py"]}
56,433
MaxyLee/Vision-Language-Transformer
refs/heads/main
/model/utils.py
import keras.backend as K import tensorflow as tf def expand_and_tile(x, outsize): x = K.expand_dims(x, axis=1) x = K.expand_dims(x, axis=1) x = K.tile(x, [1, outsize, outsize, 1]) return x def expand_and_tile_1(x, outchannels): x = K.expand_dims(x, axis=-1) x = K.tile(x, [1, 1, outchannels]) return x def normalize_by_dim(x, dim=1024.): d = tf.convert_to_tensor(dim) return x/K.sqrt(d) def split_dim_concat_batch(x, n): return tf.concat(tf.split(x, n, axis=-1), axis=0) def split_batch_concat_dim(x, n): return tf.concat(tf.split(x, n, axis=0), axis=-1) def normalize(x): x = (x+1.)/2. return K.clip(x, 1e-6, 1.-1e-6) def l2_normalize(x): return tf.nn.l2_normalize(x, axis=-1, epsilon=1e-6) def softmax(x): return K.softmax(x-tf.reduce_max(x), -1) def concat_coord(x): ins_feat = x # [N, h, w, c] batch_size = tf.shape(x)[0] h = tf.shape(x)[1] w = tf.shape(x)[2] float_h = K.cast(h, 'float32') float_w = K.cast(w, 'float32') y_range = K.arange(float_h, dtype='float32') # [h, ] y_range = 2.0 * y_range / (float_h - 1.0) - 1.0 x_range = K.arange(float_w, dtype='float32') # [w, ] x_range = 2.0 * x_range / (float_w - 1.0) - 1.0 x_range = x_range[None, :] # [1, w] y_range = y_range[:, None] # [h, 1] x = K.tile(x_range, [h, 1]) # [h, w] y = K.tile(y_range, [1, w]) # [h, w] x = x[None, :, :, None] # [1, h, w, 1] y = y[None, :, :, None] # [1, h, w, 1] x = K.tile(x, [batch_size, 1, 1, 1]) # [N, h, w, 1] y = K.tile(y, [batch_size, 1, 1, 1]) # [N, h, w, 1] ins_feat_out = K.concatenate([ins_feat, x, x, x, y, y, y]) # [N, h, w, c+6] return ins_feat_out
{"/executor.py": ["/callbacks/eval.py", "/callbacks/learning_scheduler.py", "/loader/loader.py", "/model/vlt_model.py"], "/callbacks/eval.py": ["/loader/loader.py"], "/vlt.py": ["/executor.py"], "/model/vlt_model.py": ["/model/language_backbone.py", "/model/transfromer_model.py"]}
56,434
MaxyLee/Vision-Language-Transformer
refs/heads/main
/model/visual_backbone.py
# from keras.layers import Conv2D, Add, ZeroPadding2D, ReLU, UpSampling2D, Flatten, Concatenate, MaxPooling2D, Multiply, Input, Lambda, Dense, Dropout, Dot, Reshape, Activation, GlobalAveragePooling2D, AveragePooling2D from functools import reduce from keras.layers import Conv2D, Add, ZeroPadding2D, ReLU from keras.layers.advanced_activations import LeakyReLU from keras.layers.normalization import BatchNormalization from keras.regularizers import l2 from functools import wraps def compose(*funcs): """Compose arbitrarily many functions, evaluated left to right. Reference: https://mathieularose.com/function-composition-in-python/ """ # return lambda x: reduce(lambda v, f: f(v), funcs, x) if funcs: return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs) else: raise ValueError('Composition of empty sequence not supported.') @wraps(Conv2D) def DarknetConv2D(*args, **kwargs): """Wrapper to set Darknet parameters for Convolution2D.""" darknet_conv_kwargs = {'kernel_regularizer': l2(5e-4)} darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides') == (2, 2) else 'same' darknet_conv_kwargs.update(kwargs) return Conv2D(*args, **darknet_conv_kwargs) def DarknetConv2D_BN_Leaky(*args, **kwargs): """Darknet Convolution2D followed by BatchNormalization and LeakyReLU.""" no_bias_kwargs = {'use_bias': False} no_bias_kwargs.update(kwargs) return compose( DarknetConv2D(*args, **no_bias_kwargs), BatchNormalization(), LeakyReLU(alpha=0.1)) def VGGnetConv2D(*args, **kwargs): """Wrapper to set Darknet parameters for Convolution2D.""" darknet_conv_kwargs = {'kernel_regularizer': l2(5e-4)} darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides') == (2, 2) else 'same' darknet_conv_kwargs.update(kwargs) return Conv2D(*args, **darknet_conv_kwargs) def VGGnetConv2D_BN_Relu(*args, **kwargs): """Darknet Convolution2D followed by BatchNormalization and LeakyReLU.""" no_bias_kwargs = {'use_bias': True} no_bias_kwargs.update(kwargs) return compose( VGGnetConv2D(*args, **no_bias_kwargs), ReLU()) def resblock_body(x, num_filters, num_blocks): '''A series of resblocks starting with a downsampling Convolution2D''' # Darknet uses left and top padding instead of 'same' mode x = ZeroPadding2D(((1, 0), (1, 0)))(x) x = DarknetConv2D_BN_Leaky(num_filters, (3, 3), strides=(2, 2))(x) for i in range(num_blocks): y = compose( DarknetConv2D_BN_Leaky(num_filters//2, (1, 1)), DarknetConv2D_BN_Leaky(num_filters, (3, 3)))(x) x = Add()([x, y]) return x def darknet_body(x): '''Darknent body having 52 Convolution2D layers''' x = DarknetConv2D_BN_Leaky(32, (3, 3))(x) x = resblock_body(x, 64, 1) x = resblock_body(x, 128, 2) x = resblock_body(x, 256, 8) x = resblock_body(x, 512, 8) x = resblock_body(x, 1024, 4) x = compose( DarknetConv2D_BN_Leaky(512, (1, 1)), DarknetConv2D_BN_Leaky(1024, (3, 3)), DarknetConv2D_BN_Leaky(512, (1, 1)), DarknetConv2D_BN_Leaky(1024, (3, 3)), DarknetConv2D_BN_Leaky(512, (1, 1)), DarknetConv2D_BN_Leaky(1024, (3, 3)))(x) return x def darknet_resblock(x, num_filters): y = compose( DarknetConv2D_BN_Leaky(num_filters, (1, 1)), DarknetConv2D_BN_Leaky(num_filters*2, (3, 3)))(x) x = Add()([x, y]) return x
{"/executor.py": ["/callbacks/eval.py", "/callbacks/learning_scheduler.py", "/loader/loader.py", "/model/vlt_model.py"], "/callbacks/eval.py": ["/loader/loader.py"], "/vlt.py": ["/executor.py"], "/model/vlt_model.py": ["/model/language_backbone.py", "/model/transfromer_model.py"]}
56,438
adrianomiranda14/framework-predictor
refs/heads/main
/cleaning.py
import pandas as pd from helpers import * from collections import Counter import numpy as np from sklearn.naive_bayes import BernoulliNB from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.metrics import balanced_accuracy_score from sklearn.metrics import plot_confusion_matrix from sklearn.metrics import confusion_matrix from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification import nltk from nltk.tokenize import MWETokenizer from nltk.collocations import * pd.set_option("max_colwidth", 1000) pd.set_option("display.max_rows", 200) csv_paths = ['csv for Predictor/April 2021 - Adriano_s copy - April 2021 Data for ML.csv', 'csv for Predictor/Copy of April 2020 data - April 2020 Data for ML.csv', 'csv for Predictor/Working Copy of October 2020 (updated 30_11_20) - Oct 2020 Data for ML.csv'] apr_21_df = clean_columns(csv_paths[0]) apr_20_df = clean_columns(csv_paths[1]) #grid_df = clean_columns(csv_paths[2]) oct_20_df = clean_columns(csv_paths[2]) #csjobs_df = clean_columns(csv_paths[4]) df_list = [apr_21_df,oct_20_df,apr_20_df] lower_case(df_list[0]) lower_case(df_list[1]) lower_case(df_list[2]) #lower_case(df_list[3]) #TODO Feature engineering stuff: #TODO create a function that, removes MOD, removes SCS, removes blank grades #TODO fix typos train_df = pd.concat([apr_21_df, oct_20_df, apr_20_df]) train_df = train_df.reset_index(drop=True) train_df['combo'] = train_df['dept_job_title'] + " " + train_df['department'] + " " + train_df['employee_grade'] train_df.to_csv('csv for Predictor/Training DF.csv')
{"/cleaning.py": ["/helpers.py"], "/main.py": ["/helpers.py"]}
56,439
adrianomiranda14/framework-predictor
refs/heads/main
/skill-model.py
import pandas as pd df = pd.read_csv('csv for Predictor/cshr-mappings.gs - Extracted DDaT Roles.csv') print(df)
{"/cleaning.py": ["/helpers.py"], "/main.py": ["/helpers.py"]}
56,440
adrianomiranda14/framework-predictor
refs/heads/main
/model.py
from sklearn.naive_bayes import BernoulliNB from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier vectorizer = CountVectorizer(stop_words='english', binary=True, min_df=0.0001) X = vectorizer.fit_transform(train_df['combo']) print(vectorizer.get_feature_names()) #This only builds the testing and training arrays X_train, X_test, Y_train, Y_test = train_test_split(X, train_df['job_role'], test_size=0.33, random_state=42) nb = BernoulliNB() lr = LogisticRegression(random_state=0, max_iter=1000) clf = RandomForestClassifier(max_depth=20, random_state=0) nb.fit(X_train, Y_train) lr.fit(X_train, Y_train) clf.fit(X_train, Y_train)
{"/cleaning.py": ["/helpers.py"], "/main.py": ["/helpers.py"]}
56,441
adrianomiranda14/framework-predictor
refs/heads/main
/main.py
# -*- coding: utf-8 -*- """from google.colab import drive drive.mount('/content/drive')""" import pandas as pd from helpers import * from collections import Counter import numpy as np from sklearn.naive_bayes import BernoulliNB from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.metrics import balanced_accuracy_score from sklearn.metrics import plot_confusion_matrix from sklearn.metrics import confusion_matrix from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification import nltk from nltk.tokenize import MWETokenizer from nltk.collocations import * pd.set_option("max_colwidth", 1000) pd.set_option("display.max_rows", 200) # Import a dataframe with cols for Dept Job title ['dept_job_title' and the framework role mapping train_df = pd.read_csv('csv for Predictor/Training DF.csv') # Split the dept job title into the individual words so that vectors can be applied Not currently used df2 = train_df['dept_job_title'].map(lambda x: x.split()) # This was the initial attempt to make bigrams before finding a function to do so within the CountVectorizer function bigram_measures = nltk.collocations.BigramAssocMeasures() finder = BigramCollocationFinder.from_documents(df2) finder.apply_freq_filter(5) bigrams = finder.nbest(bigram_measures.pmi, 50) # These are functions to create a variety of vectorizers to test changes in arguments for the most accurate method tough_vec = CountVectorizer(ngram_range=(1, 2), stop_words='english', binary=True, min_df=0.0006) X3 = tough_vec.fit_transform(train_df['combo']) print(tough_vec.get_feature_names()) len(tough_vec.get_feature_names()) vectorizer2 = CountVectorizer(ngram_range=(1, 2), stop_words='english', binary=True, min_df=0.0001) X2 = vectorizer2.fit_transform(train_df['combo']) print(vectorizer2.get_feature_names()) len(vectorizer2.get_feature_names()) vectorizer = CountVectorizer(stop_words='english', binary=True, min_df=0.0001) X = vectorizer.fit_transform(train_df['combo']) print(vectorizer.get_feature_names()) len(vectorizer.get_feature_names()) vecs = [X, X2, X3] for i in vecs: # This line splits the df into training and test data X_train, X_test, Y_train, Y_test = train_test_split(i, train_df['job_role'], test_size=0.33, random_state=42) # Naive Bayes Classifier nb = BernoulliNB() # Logistic Regression Classifier lr = LogisticRegression(random_state=0, max_iter=1000) # Random Forest Classifier clf = RandomForestClassifier(max_depth=20, random_state=0) nb.fit(X_train, Y_train) lr.fit(X_train, Y_train) clf.fit(X_train, Y_train) print(clf.score(X_test, Y_test)) print(nb.score(X_test, Y_test)) print(lr.score(X_test, Y_test)) #This only builds the testing and training arrays """nb_y_pred = nb.predict(X_test) lr_y_pred = lr.predict(X_test) clf_y_pred = clf.predict(X_test) # TODO https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html balanced_accuracy_score(Y_test, lr_y_pred) # TODO stick confusion matrix in a dataframe instead probs ###TODO - 1. remove symbols ###TODO - 2. create bigram tokens - ones with very high mutual relationship ###TODO - 3. Stemming words e.g. analysis and analyst - to treat these the same """
{"/cleaning.py": ["/helpers.py"], "/main.py": ["/helpers.py"]}