code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
import logging
import requests
import simplejson
from abc import ABC
from unittest.mock import patch
from rest_framework import status
from rest_framework.exceptions import ValidationError
from zs_utils.exceptions import CustomException
from django.utils.translation import gettext as _
from zs_utils.api.base_api import BaseAPI
from zs_utils.api.utils import response_keeper, SessionWithResponseKeeper
from zs_utils.api.constants import API_ERROR_REASONS
from zs_utils.api.services import ApiRequestLogService
__all__ = [
"APIAction",
"APIActionError",
]
class APIActionError(CustomException):
"""
Исключения для APIAction
"""
pass
class APIAction(ABC):
"""
Базовый класс экшенов.
"""
# Атрибуты
# ------------------------------------------------------------------------------
# Описание
description = "Действие с внешним API"
# Стандартное исключение
exception_class = APIActionError
# Предварительные экшены
ancestor_actions = {}
# Сущность
ENTITY_REQUIRED = False
entity_model = None
entity_name = None
# Параметры вызова
VALIDATE_PARAMS = False
required_params = []
allowed_params = []
# Логирование
SAVE_REQUEST_LOG = False
# Таймаут запроса к стороннему API
RESPONSE_TIMEOUT = 30
# Логирование запросов (получение requests.Response)
PATCH_REQUEST_WITH_RESPONSE_KEEPER = False
REQUEST_PATCH_TARGET = "requests.sessions.Session" # requests.Session для requests.request()
# Инициализация
# ------------------------------------------------------------------------------
def __init__(
self,
instance=None,
propagate_exception: bool = False,
raw_results: bool = False,
**kwargs,
):
self.logger = logging.getLogger()
self.instance = instance
if instance:
self.copy_instance(instance=instance)
else:
self.set_action_variables(**kwargs)
self.propagate_exception = propagate_exception
self.raw_results = raw_results
self.validate_action_variables()
def copy_instance(self, instance, **kwargs) -> None:
"""
Копирование экземпляра класса instance (вынесение его атрибутов в новый экземпляр)
"""
self.set_entity(**kwargs)
if (not self.entity) and (self.entity_model == instance.entity_model):
self.entity = instance.entity
if self.entity_name:
setattr(self, self.entity_name, self.entity)
# Ссылка на счетчик запросов к внешнему API
self.request_counter = instance.request_counter
def set_action_variables(self, **kwargs) -> None:
"""
Установка атрибутов экшена
"""
self.set_entity(**kwargs)
# Инициализация счетчика запросов к внешнему API
self.request_counter = 0
def set_entity(self, entity=None, entity_id: str = None, **kwargs) -> None:
"""
Установка объекта в атрибут
"""
self.entity = None
if self.entity_name:
if self.entity_name in kwargs:
entity = kwargs[self.entity_name]
if f"{self.entity_name}_id" in kwargs:
entity_id = kwargs[f"{self.entity_name}_id"]
if entity or entity_id:
if not self.entity_name:
raise ValueError("Необходимо определить атрибут 'entity_name'.")
if not self.entity_model:
raise ValueError("Необходимо определить атрибут 'entity_model'.")
if entity:
self.entity = entity
else:
self.entity = self.entity_model.objects.get(id=entity_id)
if self.entity_name:
setattr(self, self.entity_name, self.entity)
def validate_action_variables(self) -> None:
"""
Валидация атрибутов экземпляра
"""
self.validate_entity()
def validate_entity(self) -> None:
"""
Валидация объекта
"""
if self.entity:
if not isinstance(self.entity, self.entity_model):
raise ValueError(
f"Параметры 'entity' и '{self.entity_name}' должны быть экземплярами модели '{self.entity_model}'."
)
elif self.ENTITY_REQUIRED:
raise ValueError(
f"В конструкторе класса {self.__class__.__name__} необходимо задать один из следующих параметров: "
f"'entity', 'entity_id', '{self.entity_name}', '{self.entity_name}_id'."
)
# Вывод сообщения
# ------------------------------------------------------------------------------
def _get_message_template(self) -> str:
"""
Шаблон сообщения
"""
message = self.description
if message.endswith("."):
message = message[:-1]
return message
def get_success_internal_message(self) -> str:
return _("{message_template}: успешно выполнено.").format(message_template=self._get_message_template())
def get_failure_internal_message(self) -> str:
return _("{message_template}: возникла ошибка.").format(message_template=self._get_message_template())
def get_success_message(self, objects) -> str:
"""
Получение сообщения об успешной отработки экшена
"""
return self.get_success_internal_message()
def get_failure_message(self, error: Exception) -> str:
"""
Получение сообщения об ошибке error при выполнении экшена
"""
if isinstance(error, CustomException):
if error.message_dict and error.message_dict.get("external_message"):
external_message = error.message_dict["external_message"]
else:
external_message = error.message
# Стандартное сообщение для известного типа ошибок
if (not external_message) and (error.reason in API_ERROR_REASONS):
external_message = API_ERROR_REASONS[error.reason]
if not external_message:
external_message = ""
else:
external_message = str(error)
internal_message = self.get_failure_internal_message()
if internal_message:
message = internal_message + " " + external_message
else:
message = external_message
return message
# Пайплайн
# ------------------------------------------------------------------------------
def set_used_action(self, action_class: type["APIAction"], **kwargs) -> "APIAction":
"""
Инициализация используемого экшена.
"""
action = action_class(instance=self, propagate_exception=True, **kwargs)
if not hasattr(self, "used_actions"):
self.used_actions: list["APIAction"] = []
self.used_actions.append(action)
return action
def set_used_actions(self) -> None:
"""
Инициализация используемых экшенов.
"""
pass
def execute_ancestor_actions(self) -> None:
"""
Выполнение предварительных экшенов и передача их результатов в качестве параметров текущего экшена.
"""
for results_name, action_class in self.ancestor_actions.items():
if not self.params.get(results_name):
is_success, message, objects = action_class(instance=self, propagate_exception=True)(**self.params)
self.params[results_name] = objects.get("results", objects)
def __call__(self, **kwargs) -> tuple:
"""
Запуск экшена (контроллер)
"""
is_success = False
message = None
objects = {}
try:
# Инициализация используемых экшенов
self.set_used_actions()
# Обработка входных параметров
self.params = self.get_params(**kwargs)
# Действия перед началом выполнения данного экшена
self.before_request()
# Выполнение предварительных экшенов и передача их результатов в качестве параметров данного экшена
self.execute_ancestor_actions()
# Выполнение данного экшена
objects: dict = self.run_action(**self.params)
if not objects:
objects = {"results": {}, "response": None}
# Действия после успешного выполнения данного экшена
self.success_callback(objects=objects, **self.params)
except CustomException as error:
response: requests.Response = error.response
if not error.reason:
error.reason = API_ERROR_REASONS.unknown
is_success = False
message: str = self.get_failure_message(error=error)
objects = {
"results": {},
"errors": error,
"error_reason": error.reason,
"response": response,
}
# Действия после неудачного выполнения данного экшена
self.failure_callback(objects)
if self.propagate_exception:
raise
except ValidationError as error: # TODO: не обрабатывать ValidationError?
is_success = False
message: str = self.get_failure_message(error=error)
objects = {
"results": {},
"errors": error,
"error_reason": API_ERROR_REASONS.data_validation,
"response": None,
}
# Действия после неудачного выполнения данного экшена
self.failure_callback(objects)
if self.propagate_exception:
raise
else:
is_success = True
message = self.get_success_message(objects)
if is_success:
self.logger.info(message)
else:
self.logger.warning(message)
return is_success, message, objects
@classmethod
def simple_run(cls, **kwargs) -> dict:
"""
Вызов конструктора с propagate_exception=True, а затем вызов __call__ и возврат objects["results"].
"""
kwargs["propagate_exception"] = True
action = cls(**kwargs)
return action.__call__(**kwargs)[2].get("results", {})
# Методы, поддерживающие переопределение
# ------------------------------------------------------------------------------
def before_request(self, **kwargs) -> None:
"""
Действия перед выполнением запроса
"""
pass
def format_success_results(self, results: dict, **kwargs) -> dict:
"""
Форматирование результатов после успешного выполнения данного экшена.
"""
return results
def success_callback(self, objects: dict, **kwargs) -> None:
"""
Действия после успешного выполнения данного экшена.
"""
if (not self.raw_results) and isinstance(objects, dict) and ("results" in objects):
objects["results"] = self.format_success_results(results=objects["results"], objects=objects)
def failure_callback(self, objects: dict, **kwargs) -> None:
"""
Действия после неудачного выполнения данного экшена.
"""
pass
def get_params(self, **kwargs) -> dict:
"""
Определение параметров вызова экшена.
"""
return kwargs
@property
def possible_params(self):
"""
Возможные параметры (required_params + allowed_params)
"""
return self.required_params + self.allowed_params + ["size", "page"] # TODO: где нужны size и page?
def clean_api_request_params(self, raw_params: dict) -> dict:
"""
Валидация и отчистка параметров запроса к API
"""
# Проверка наличия обязательных параметров
for param in self.required_params:
if raw_params.get(param) is None:
raise self.exception_class(f"Обязательный параметр '{param}' не задан.")
# Фильтрация допустимых параметров
params = {param: raw_params[param] for param in self.possible_params if param in raw_params}
return params
def get_api_class_init_params(self, **kwargs) -> dict:
"""
Получение параметров для инициализации API класса
"""
raise NotImplementedError("Необходимо определить метод 'get_api_class_init_params'.")
def get_api(self, **kwargs) -> BaseAPI:
"""
Получение API класса
"""
if not getattr(self, "api_class", None):
raise NotImplementedError("Необходимо определить атрибут 'api_class'.")
init_params: dict = self.get_api_class_init_params(**kwargs)
init_params["response_timeout"] = self.RESPONSE_TIMEOUT
return self.api_class(**init_params)
def make_request(self, **kwargs) -> dict:
"""
Исполнение запроса через API класс к API сервиса
"""
self.api: BaseAPI = self.get_api(**kwargs)
try:
response = self.api.make_request(**kwargs)
except (requests.exceptions.Timeout, requests.exceptions.ConnectTimeout):
raise self.exception_class(reason=API_ERROR_REASONS.timeout)
results = self.get_response_results(response=response)
return {"results": results, "response": response}
def get_response_results(self, response: requests.Response) -> dict:
"""
Извлечение результатов выполнения запроса из response
"""
if response is not None:
try:
return response.json()
except simplejson.JSONDecodeError:
pass
return {}
def run_action(self, **kwargs) -> dict:
"""
Запрос к API сервиса с последующей обработкой ответа
"""
if self.VALIDATE_PARAMS:
params = self.clean_api_request_params(raw_params=kwargs)
else:
params = kwargs
# Инкрементирование счетчика запросов к API маркетплейса
self.incr_request_counter()
exception = None
try:
if self.PATCH_REQUEST_WITH_RESPONSE_KEEPER:
with patch(self.REQUEST_PATCH_TARGET, SessionWithResponseKeeper):
response_data: dict = self.make_request(**params)
# Извлекаем из декоратора сохраненный response
response_attr = "raw_response"
response: requests.Response = getattr(response_keeper, response_attr, None)
if response is not None:
response_data["response"] = response
setattr(response_keeper, response_attr, None)
else:
response_data: dict = self.make_request(**params)
except self.exception_class as error:
response: requests.Response = error.response
if response is None:
results = {}
else:
results = self.get_response_results(response=response)
if (not results) and error.message_dict:
results = error.message_dict
exception = error
else:
results: dict = response_data["results"]
response: requests.Response = response_data.get("response")
response_is_success: bool = self.response_is_success(results=results, response=response, exception=exception)
if response_is_success:
results: dict = self.format_success_response_results(results=results, response=response)
exception = None
else:
error_message = self.get_error_message(results=results, response=response)
if (not error_message) and exception:
error_message = exception.message
if exception is None:
exception = self.exception_class(message=error_message, response=response)
# Определение типа ошибки
if not exception.reason:
exception.reason = self.get_error_reason(
results=results,
response=response,
error_message=error_message,
)
# Сохранение лога
if (not response_is_success) or self.SAVE_REQUEST_LOG:
try:
self.save_request_log(results=results, response=response)
except Exception as error:
self.logger.critical(f"Не удалось сохранить лог запроса к внешнему API: {str(error)}")
if exception is not None:
raise exception
return {"results": results, "response": response}
def incr_request_counter(self) -> None:
"""
Увеличение счётчика запросов
"""
self.request_counter += 1
if self.instance:
self.instance.incr_request_counter()
def response_is_success(
self,
results: dict,
response: requests.Response,
exception: CustomException = None,
) -> bool:
"""
Проверка, что запрос успешный
"""
if exception is not None:
return False
if response is not None:
return status.is_success(response.status_code)
return True
def format_success_response_results(self, results: dict, response: requests.Response) -> dict:
"""
Форматирование данных ответа успешного запроса
"""
return results
def get_error_message(self, results: dict, response: requests.Response) -> str:
"""
Получение сообщения об ошибке из ответа response или results
"""
return ""
def get_error_reason(self, results: dict, response: requests.Response, error_message: str) -> API_ERROR_REASONS:
"""
Получение причины ошибки
"""
if (response is not None) and getattr(response, "status_code", None):
code: int = response.status_code
if str(code).startswith("5"):
return API_ERROR_REASONS.system
elif code in [401, 403]:
return API_ERROR_REASONS.invalid_token
elif code == 404:
return API_ERROR_REASONS.object_not_found
elif response.status_code == 429:
return API_ERROR_REASONS.request_limit
def get_apirequest_log_extra_data(self) -> dict:
return {}
def save_request_log(self, results: dict, response: requests.Response):
if (response is not None) and isinstance(response, requests.Response):
ApiRequestLogService.save_api_request_log_by_response(
response=response,
**self.get_apirequest_log_extra_data(),
) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/base_action.py | base_action.py |
import requests
import simplejson
from urllib.parse import parse_qs, urlparse
from rest_framework import status
from django.apps import apps
from django.conf import settings
from zs_utils.api import models
__all__ = [
"ApiRequestLogService",
]
class ApiRequestLogService:
"""
Сервис для работы с моделью APIRequestLog
"""
@classmethod
def get_request_log_model(cls) -> type[models.AbstractAPIRequestLog] | None:
if getattr(settings, "API_REQUEST_LOG_MODEL", None):
app_label, model_name = settings.API_REQUEST_LOG_MODEL.split(".")
return apps.get_model(app_label=app_label, model_name=model_name)
else:
return models.APIRequestLog
@classmethod
def save_api_request_log(
cls,
status_code: int,
url: str,
method: str,
request_headers: dict = None,
response_headers: dict = None,
request_body: dict = None,
response_body: dict = None,
response_time: float = None,
user: settings.AUTH_USER_MODEL = None,
save_if_is_success: bool = True,
**extra_fields,
) -> models.AbstractAPIRequestLog:
"""
Создание экземпляра модели AbstractAPIRequestLog по переданным данным (сохранение данных)
"""
if (not save_if_is_success) and status.is_success(status_code):
return None
request_log_model = cls.get_request_log_model()
if not request_log_model:
raise ValueError("Необходимо задать настройку API_REQUEST_LOG_MODEL (путь к модели).")
return request_log_model.objects.create(
user=user,
# Данные запроса
url=url,
method=method,
params=parse_qs(urlparse(url).query),
request_headers=request_headers,
request_body=request_body,
# Данные ответа
response_time=response_time,
status_code=status_code,
response_headers=response_headers,
response_body=response_body,
**extra_fields,
)
@classmethod
def save_api_request_log_by_response(
cls,
response: requests.Response,
user: settings.AUTH_USER_MODEL = None,
save_if_is_success: bool = True,
**extra_fields,
) -> models.AbstractAPIRequestLog:
"""
Создание экземпляра модели AbstractAPIRequestLog по переданному requests.Response (сохранение данных)
"""
request = response.request
request_body = request.body
if isinstance(request_body, bytes):
try:
request_body = request_body.decode()
except UnicodeDecodeError:
request_body = str(request_body)
if isinstance(request_body, str):
try:
request_body = simplejson.loads(request_body)
except simplejson.JSONDecodeError:
pass
try:
response_body = response.json()
except simplejson.JSONDecodeError:
response_body = None
return cls.save_api_request_log(
user=user,
status_code=response.status_code,
url=request.url,
method=request.method,
request_headers=dict(request.headers),
response_headers=dict(response.headers),
request_body=request_body,
response_body=response_body,
response_time=response.elapsed.microseconds / 1000,
save_if_is_success=save_if_is_success,
**extra_fields,
) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/services.py | services.py |
import logging
import requests
import re
from abc import ABC
__all__ = [
"BaseAPI",
]
class BaseAPI(ABC):
required_params = []
allowed_params = []
# Тело запроса -- список, а не словарь
array_payload = False
# Отбрасывать параметры с пустым значением (None или "")
drop_empty_params = False
http_method = None
resource_method = None
production_api_url = None
sandbox_api_url = None
def __init__(
self,
logger=None,
is_sandbox: bool = False,
response_timeout: float = 30,
**kwargs,
):
self.logger = logger or logging.getLogger(self.__class__.__name__)
self.is_sandbox = is_sandbox
self.response_timeout = response_timeout
self.validate_attrs()
def validate_attrs(self) -> None:
"""
Валидация обязательных атрибутов у дочерних классов
"""
for attr in [
"http_method",
"resource_method",
"production_api_url",
]:
if not getattr(self, attr, None):
raise ValueError(f"Необходимо определить атрибут '{attr}'.")
if self.is_sandbox and (not self.sandbox_api_url):
raise ValueError("Для использования тестового режима необходимо указать 'sandbox_api_url'")
if self.array_payload:
if (self.required_params and (self.required_params != ["array_payload"])) or self.allowed_params:
raise ValueError(
"Если стоит флаг 'array_payload', то единственным возможным и обязательным параметром является параметр 'array_payload'."
)
self.required_params = ["array_payload"]
@property
def headers(self) -> dict:
"""
Headers для запросов к API
"""
return {}
@property
def path_params(self) -> list[str]:
return re.findall(pattern=r"\{([^\}]+)\}", string=self.resource_method)
def build_url(self, params: dict) -> str:
"""
Составление url для запросов к API (подстановка эндпоинта и url-параметром в url)
"""
url = self.sandbox_api_url if self.is_sandbox else self.production_api_url
url += self.resource_method
path_params = {}
for param in self.path_params:
if params.get(param):
path_params[param] = params[param]
else:
raise ValueError(f"Отсутствует обязательный параметр '{param}'.")
if path_params:
url = url.format(**path_params)
if url[-1] == "/":
url = url[:-1]
return url
def get_clean_params(self, params: dict) -> dict:
"""
Отчистка и валидация параметров запроса
В итоговый запрос попадут только ключи из required_params и allowed_param
"""
clean_params = {}
files = {}
for req_param in self.required_params:
if req_param not in params:
raise ValueError(f"Обязательный параметр запроса '{req_param}' не задан.")
if isinstance(params[req_param], bytes):
files[req_param] = params[req_param]
else:
clean_params[req_param] = params[req_param]
for allowed_param in self.allowed_params:
if allowed_param in params:
if isinstance(params[allowed_param], bytes):
files[allowed_param] = params[allowed_param]
else:
clean_params[allowed_param] = params[allowed_param]
if self.drop_empty_params:
clean_params = {k: v for k, v in clean_params.items() if ((v is not None) and (v != ""))}
clean_params["files"] = files if files else None
return clean_params
def get_payload(self, params: dict) -> dict | list:
"""
Получение body для POST запросов
"""
if self.array_payload:
return params["array_payload"]
return params
def get_request_params(self, **kwargs) -> dict:
"""
Получение всех параметров, необходимых для запроса (url, headers, params, json, files)
"""
request_params = {
"url": self.build_url(kwargs),
"headers": self.headers,
}
clean_params = self.get_clean_params(kwargs)
files = clean_params.pop("files", None)
if files:
request_params["files"] = files
if self.http_method in ["POST", "PUT", "PATCH"]:
request_params["json"] = self.get_payload(params=clean_params)
else:
request_params["params"] = clean_params
return request_params
def make_request(self, **kwargs) -> requests.Response:
"""
Непосредственный запрос к API
"""
return requests.request(
method=self.http_method,
timeout=self.response_timeout,
**self.get_request_params(**kwargs),
) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/base_api.py | base_api.py |
from model_utils.models import TimeStampedModel, UUIDModel
from rest_framework import status
from django.db import models
from django.conf import settings
from zs_utils.json_utils import CustomJSONEncoder
from zs_utils.api import constants
__all__ = [
"AbstractAPIRequestLog",
"APIRequestLog",
]
class AbstractAPIRequestLog(TimeStampedModel, UUIDModel):
"""
Хранение запросов к внешним сервисам
"""
user = models.ForeignKey(
to=settings.AUTH_USER_MODEL,
null=True,
on_delete=models.CASCADE,
related_name="api_request_logs",
related_query_name="api_request_log",
verbose_name="Пользователь",
)
# Данные запроса
url = models.TextField(verbose_name="URL запроса")
method = models.CharField(choices=constants.HTTP_METHODS, max_length=6, verbose_name="Метод запроса")
params = models.JSONField(
blank=True,
null=True,
encoder=CustomJSONEncoder,
verbose_name="Параметры URL",
)
request_headers = models.JSONField(
blank=True,
null=True,
encoder=CustomJSONEncoder,
verbose_name="Хедеры запроса",
)
request_body = models.JSONField(
blank=True,
null=True,
encoder=CustomJSONEncoder,
verbose_name="Тело запроса",
)
# Данные ответа
response_time = models.IntegerField(verbose_name="Время ответа (миллисекунда)")
status_code = models.IntegerField(verbose_name="Код ответа")
response_headers = models.JSONField(
blank=True,
null=True,
encoder=CustomJSONEncoder,
verbose_name="Хедеры ответа",
)
response_body = models.JSONField(
blank=True,
null=True,
encoder=CustomJSONEncoder,
verbose_name="Тело ответа",
)
@property
def is_success(self) -> bool:
return status.is_success(code=self.status_code)
class Meta:
abstract = True
class APIRequestLog(AbstractAPIRequestLog):
class Meta:
ordering = ["-created"] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/models.py | models.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
import uuid
import zs_utils.json_utils
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="APIRequestLog",
fields=[
(
"created",
model_utils.fields.AutoCreatedField(
default=django.utils.timezone.now, editable=False, verbose_name="created"
),
),
(
"modified",
model_utils.fields.AutoLastModifiedField(
default=django.utils.timezone.now, editable=False, verbose_name="modified"
),
),
(
"id",
model_utils.fields.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
),
("url", models.TextField(verbose_name="URL запроса")),
(
"method",
models.CharField(
choices=[
("GET", "GET"),
("POST", "POST"),
("DELETE", "DELETE"),
("PUT", "PUT"),
("PATCH", "PATCH"),
],
max_length=6,
verbose_name="Метод запроса",
),
),
(
"params",
models.JSONField(
blank=True,
encoder=zs_utils.json_utils.CustomJSONEncoder,
null=True,
verbose_name="Параметры URL",
),
),
(
"request_headers",
models.JSONField(
blank=True,
encoder=zs_utils.json_utils.CustomJSONEncoder,
null=True,
verbose_name="Хедеры запроса",
),
),
(
"request_body",
models.JSONField(
blank=True,
encoder=zs_utils.json_utils.CustomJSONEncoder,
null=True,
verbose_name="Тело запроса",
),
),
("response_time", models.IntegerField(verbose_name="Время ответа (миллисекунда)")),
("status_code", models.IntegerField(verbose_name="Код ответа")),
(
"response_headers",
models.JSONField(
blank=True,
encoder=zs_utils.json_utils.CustomJSONEncoder,
null=True,
verbose_name="Хедеры ответа",
),
),
(
"response_body",
models.JSONField(
blank=True, encoder=zs_utils.json_utils.CustomJSONEncoder, null=True, verbose_name="Тело ответа"
),
),
(
"user",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="api_request_logs",
related_query_name="api_request_log",
to=settings.AUTH_USER_MODEL,
verbose_name="Пользователь",
),
),
],
options={
"ordering": ["-created"],
},
),
] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/migrations/0001_initial.py | 0001_initial.py |
from model_utils import Choices
from django.utils.translation import gettext_lazy as _
YOOKASSA_PAYMENT_STATUSES = Choices(
("pending", _("Ожидание подтверждения")),
("succeeded", _("Успешно выполнено")),
("canceled", _("Отменено")),
("waiting_for_capture", _("Ожидание списания")),
)
YOOKASSA_PAYMENT_CANCELLATION_PARTIES = Choices(
("yandex_checkout", _("Яндекс.Касса")),
("payment_network", _("Внешние участники платежного процесса")),
("merchant", _("Продавец товаров и услуг")),
)
YOOKASSA_CANCELLATION_REASONS = Choices(
("3d_secure_failed", _("Не пройдена аутентификация по 3-D Secure")),
("call_issuer", _("Оплата данным платежным средством отклонена по неизвестным причинам")),
("canceled_by_merchant", _("Платеж отменен по API при оплате в две стадии")),
("card_expired", _("Истек срок действия банковской карты")),
("country_forbidden", _("Нельзя заплатить банковской картой, выпущенной в этой стране")),
("expired_on_capture", _("Истек срок списания оплаты у двухстадийного платежа")),
(
"expired_on_confirmation",
_("Истек срок оплаты: пользователь не подтвердил платеж за время, отведенное на оплату выбранным способом"),
),
("fraud_suspected", _("Платеж заблокирован из-за подозрения в мошенничестве")),
("general_decline", _("Причина не детализирована")),
("identification_required", _("Превышены ограничения на платежи для кошелька в Яндекс.Деньгах")),
("insufficient_funds", _("Не хватает денег для оплаты")),
(
"internal_timeout",
_("Технические неполадки на стороне Яндекс.Кассы: не удалось обработать запрос в течение 30 секунд"),
),
("invalid_card_number", _("Неправильно указан номер карты")),
("invalid_csc", _("Неправильно указан код CVV2 (CVC2, CID)")),
("issuer_unavailable", _("Организация, выпустившая платежное средство, недоступна")),
("payment_method_limit_exceeded", _("Исчерпан лимит платежей для данного платежного средства или магазина")),
("payment_method_restricted", _("Запрещены операции данным платежным средством")),
("permission_revoked", _("Нельзя провести безакцептное списание: пользователь отозвал разрешение на автоплатежи")),
)
YOOKASSA_RECEIPT_REGISTRATION_STATUSES = Choices(
("pending", _("Ожидание")),
("succeeded", _("Успешно выполнено")),
("canceled", _("Отменено")),
)
YOOKASSA_RECEIPT_TYPES = Choices("payment", "refund")
YOOKASSA_TAX_SYSTEM_CODES = Choices(
(1, "n1", "Общая система налогообложения"),
(2, "n2", "Упрощенная (УСН, доходы)"),
(3, "n3", "Упрощенная (УСН, доходы минус расходы)"),
(4, "n4", "Единый налог на вмененный доход (ЕНВД)"),
(5, "n5", "Единый сельскохозяйственный налог (ЕСН)"),
(6, "n6", "Патентная система налогообложения"),
)
YOOKASSA_VAT_CODES = Choices(
(1, "n1", "Без НДС"),
(2, "n2", "НДС по ставке 0%"),
(3, "n3", "НДС по ставке 10%"),
(4, "n4", "НДС чека по ставке 20%"),
(5, "n5", "НДС чека по расчетной ставке 10/110"),
(6, "n6", "НДС чека по расчетной ставке 20/120"),
)
YOOKASSA_PAYMENT_SUBJECTS = Choices(
("service", "Услуга"),
)
YOOKASSA_PAYMENT_MODES = Choices(
("full_prepayment", "Полная предоплата"),
("partial_prepayment", "Частичная предоплата"),
("advance", "Аванс"),
("full_payment", "Полный расчет"),
("partial_payment", "Частичный расчет и кредит"),
("credit", "Кредит"),
("credit_payment", "Выплата по кредиту"),
)
YOOKASSA_SETTLEMENT_TYPES = Choices(
("cashless", "Безналичный расчет"),
("prepayment", "Предоплата (аванс)"),
("postpayment", "Постоплата (кредит)"),
("consideration", "Встречное предоставление"),
)
YOOKASSA_AGENT_TYPES = Choices(
("banking_payment_agent", "Банковский платежный агент"),
("banking_payment_subagent", "Банковский платежный субагент"),
("payment_agent", "Платежный агент"),
("payment_subagent", "Платежный субагент"),
("attorney", "Поверенный"),
("commissioner", "Комиссионер"),
("agent", "Агент"),
)
YOOKASSA_PURPOSE = Choices(
("CARD_SETUP", "Подключение карты"),
) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/yookassa/constants.py | constants.py |
from yookassa import Configuration
from yookassa.domain.common import ResponseObject
from zs_utils.api.base_action import APIAction
class YooKassaAction(APIAction):
description = "Взаимодействие с API Yoo Kassa"
save_notifications = True
api_method = None
VALIDATE_PARAMS = True
def __init__(self, instance=None, propagate_exception: bool = False, **kwargs):
super().__init__(instance, propagate_exception, **kwargs)
self.configured = False
def copy_instance(self, instance, **kwargs) -> None:
super().copy_instance(instance, **kwargs)
self.user = instance.user
self.test_mode = instance.test_mode
self.credentials = instance.credentials
def set_action_variables(self, **kwargs) -> None:
super().set_action_variables(**kwargs)
self.user = kwargs.get("user")
self.credentials = kwargs.get("credentials")
self.test_mode = kwargs.get("test_mode")
@classmethod
def clean_data(cls, data: dict):
cleaned_data = {}
for key, value in data.items():
if value or type(value) in [bool, int]:
if isinstance(value, dict):
cleaned_data.update({key: cls.clean_data(value)})
else:
cleaned_data.update({key: value})
return cleaned_data
def get_params(self, **kwargs) -> dict:
if "params" in self.required_params:
if kwargs.get("params"):
kwargs["params"] = self.clean_data(data=kwargs["params"])
else:
kwargs["params"] = {}
return super().get_params(**kwargs)
def configure_yookassa(self):
if self.test_mode:
account_id = self.credentials["test"]["account_id"]
secret_key = self.credentials["test"]["secret_key"]
else:
account_id = self.credentials["production"]["account_id"]
secret_key = self.credentials["production"]["secret_key"]
Configuration.configure(account_id, secret_key)
self.configured = True
def before_request(self, **kwargs):
super().before_request(**kwargs)
self.configure_yookassa()
def make_request(self, **kwargs):
if not getattr(self, "api_method", None):
raise NotImplementedError("Для обращения к API YooKassa необходимо задать атрибут 'api_method'.")
assert self.configured, "Метод Configuration.configure не был вызван."
try:
response: ResponseObject = self.api_method(**kwargs)
except Exception as error:
if error.args and isinstance(error.args[0], dict):
errors: dict = error.args[0]
message = f'{errors["description"]}. Code: {errors["code"]}.'
raise self.exception_class(message=message, message_dict=errors)
else:
raise self.exception_class(message=str(error))
return {"results": dict(response)} | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/yookassa/base_action.py | base_action.py |
from zs_utils.api.yookassa import constants, core
from zs_utils.data.enums import CURRENCIES
from zs_utils.exceptions import CustomException
from zs_utils.user.models import AbstractZonesmartUser
__all__ = [
"YooKassaException",
"BaseYooKassaService",
]
class YooKassaException(CustomException):
pass
class BaseYooKassaService:
YOOKASSA_CREDENTIALS = None
YOOKASSA_TEST_MODE = None
@staticmethod
def validate_amount(amount: float) -> None:
"""
Валидация суммы amount (должна быть положительной)
"""
if amount <= 0:
raise YooKassaException("Значение 'amount' должно быть положительным.")
@classmethod
def convert_currency(cls, amount: float, from_currency: str) -> float:
# TODO?
# Always into CURRENCIES.RUB
return amount
@classmethod
def get_receipt_template(
cls,
product_description: str,
product_price: float,
product_price_currency: CURRENCIES,
user: AbstractZonesmartUser = None,
inn: str = None,
email: str = None,
phone: str = None,
) -> dict:
if user:
email = user.email
phone = getattr(user, "phone", None)
organization = getattr(user, "user_organization", None)
if organization:
inn = organization.itn
else:
inn = None
if product_price_currency != CURRENCIES.RUB:
product_price = cls.convert_currency(amount=product_price, from_currency=product_price_currency)
data = {
"customer": {
"inn": inn,
"email": email,
"phone": phone,
},
"items": [
{
"description": product_description,
"quantity": 1,
"amount": {"value": product_price, "currency": "RUB"},
"vat_code": constants.YOOKASSA_VAT_CODES.n1,
"payment_subject": constants.YOOKASSA_PAYMENT_SUBJECTS.service,
"payment_mode": constants.YOOKASSA_PAYMENT_MODES.full_prepayment,
"agent_type": constants.YOOKASSA_AGENT_TYPES.payment_agent,
},
],
"tax_system_code": constants.YOOKASSA_TAX_SYSTEM_CODES.n3,
}
return data
@classmethod
def remote_setup_card(cls, user: AbstractZonesmartUser, return_url: str, extra_metadata: dict = {}) -> tuple:
"""
Создание платежа для подключения карты
"""
call_params = {
"user": user,
"amount": 1,
"description": "Подключение банковской карты.",
"purpose": constants.YOOKASSA_PURPOSE.CARD_SETUP,
"return_url": return_url,
"extra_metadata": extra_metadata,
}
return cls.remote_create_payment(**call_params)
@classmethod
def remote_create_payment(
cls,
user: AbstractZonesmartUser,
amount: float,
return_url: str,
purpose: str,
description: str,
payment_method_id: str = None,
extra_metadata: dict = {},
) -> tuple:
"""
Создание платежа через YooKassa
"""
cls.validate_amount(amount)
call_params = {
"payment_method_id": payment_method_id,
"amount": amount,
"currency": "RUB",
"description": description,
"extra_metadata": {
"purpose": purpose,
**extra_metadata,
},
"return_url": return_url,
}
return core.RemoteCreateYooKassaPayment(
credentials=cls.YOOKASSA_CREDENTIALS, test_mode=cls.YOOKASSA_TEST_MODE, user=user, propagate_exception=True
)(**call_params)
@classmethod
def remote_create_refund(cls, user: AbstractZonesmartUser, payment_id: str, amount: float) -> tuple:
"""
Запрос на возврат средств через YooKassa
"""
cls.validate_amount(amount)
return core.RemoteCreateYooKassaRefund(
credentials=cls.YOOKASSA_CREDENTIALS, test_mode=cls.YOOKASSA_TEST_MODE, user=user, propagate_exception=True
)(payment_id=payment_id, amount=amount)
# Process webhook events
@classmethod
def process_webhook(cls, user: AbstractZonesmartUser, event_type: str, event_data: dict) -> None:
"""
Обработка вебхук-уведомления от YooKassa
"""
is_card_setup = False
if event_data.get("metadata"):
is_card_setup = event_data["metadata"].get("purpose") == constants.YOOKASSA_PURPOSE.CARD_SETUP
if is_card_setup and event_type == "payment.canceled":
action = cls.card_setup_canceled
elif is_card_setup and event_type == "payment.succeeded":
action = cls.card_setup_succeeded
elif event_type == "payment.canceled":
action = cls.payment_canceled
elif event_type == "payment.succeeded":
action = cls.payment_succeeded
elif event_type == "refund.succeeded":
action = cls.payment_refunded
else:
raise YooKassaException("Для данного события обработчик не найден.")
action(user=user, raw_data=event_data)
@classmethod
def card_setup_succeeded(cls, user: AbstractZonesmartUser, raw_data: dict):
return cls.create_or_update_payment_instance(user=user, raw_data=raw_data)
@classmethod
def payment_canceled(cls, user: AbstractZonesmartUser, raw_data: dict):
return cls.create_or_update_payment_instance(user=user, raw_data=raw_data)
@classmethod
def payment_succeeded(cls, user: AbstractZonesmartUser, raw_data: dict):
return cls.create_or_update_payment_instance(user=user, raw_data=raw_data)
@classmethod
def card_setup_canceled(cls, user: AbstractZonesmartUser, raw_data: dict):
raise NotImplementedError("Необходимо определить метод обработки неудачной попытки подключить карту.")
@classmethod
def create_or_update_card_instance(cls, user: AbstractZonesmartUser, raw_data: dict):
raise NotImplementedError("Необходимо определить метод создания и обновления банковской карты.")
@classmethod
def create_or_update_payment_instance(cls, user: AbstractZonesmartUser, raw_data: dict):
raise NotImplementedError("Необходимо определить метод создания и обновления объекта платежа.")
@classmethod
def payment_refunded(cls, user: AbstractZonesmartUser, raw_data: dict):
raise NotImplementedError("Необходимо определить метод обработки удачного возврата платежа.") | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/yookassa/services.py | services.py |
from yookassa.domain.notification import WebhookNotification
from rest_framework import status
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
from zs_utils.api.yookassa.services import BaseYooKassaService
from zs_utils.views import CustomAPIView
__all__ = [
"BaseYooKassaWebhookView",
]
class BaseYooKassaWebhookView(CustomAPIView):
"""
View для получения уведомлений от YooKassa.
"""
IP_VALIDATION = False
YOOKASSA_WEBHOOK_IP_WHITELIST = []
YOOKASSA_SERVICE = BaseYooKassaService
@staticmethod
def validation(event_type: str, event_data: dict, metadata: dict):
pass
@property
def request_ip(self) -> str:
return None
def get_user(self, user_id: str = None, payment_id: str = None):
raise NotImplementedError("Необходимо определить метод получения пользователя.")
def post(self, request: Request, *args, **kwargs):
# IP validation
if self.IP_VALIDATION and self.request_ip not in self.YOOKASSA_WEBHOOK_IP_WHITELIST:
return Response(status=status.HTTP_403_FORBIDDEN)
# Валидация ключей
for key in ["event", "object"]:
if not request.data.get(key):
raise ValidationError({key: "Это поле обязательно."})
# Разбор данных
notification = WebhookNotification(request.data)
event_type = notification.event
event_data = dict(notification.object)
metadata = event_data.get("metadata", {})
self.validation(event_type=event_type, event_data=event_data, metadata=metadata)
# Определяем пользователя
user_id = metadata.get("user_id")
payment_id = request.data["object"].get("payment_id", event_data.get("id"))
event_data["payment_id"] = payment_id
user = self.get_user(user_id=user_id, payment_id=payment_id)
if not user:
return Response({"detail": "Не удалось определить пользователя"}, status.HTTP_400_BAD_REQUEST)
# Обработка данных
self.YOOKASSA_SERVICE.process_webhook(user=user, event_type=event_type, event_data=event_data)
return Response(status=status.HTTP_200_OK) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/yookassa/views.py | views.py |
from yookassa import Refund
from .payment_get import RemoteGetYooKassaPayment
from zs_utils.api.yookassa.base_action import YooKassaAction
from zs_utils.api.yookassa import services
__all__ = [
"RemoteGetYooKassaRefund",
"RemoteGetYooKassaRefundList",
"RemoteCreateYooKassaRefund",
]
class RemoteGetYooKassaRefund(YooKassaAction):
description = "Получение возврата платежа в Яндекс.Кассе"
api_method = Refund.find_one
required_params = ["refund_id"]
class RemoteGetYooKassaRefundList(YooKassaAction):
description = "Получение всех возвратов платежей в Яндекс.Кассе"
api_method = Refund.list
required_params = ["params"]
class RemoteCreateYooKassaRefund(YooKassaAction):
description = "Создание возврата платежа в Яндекс.Кассе"
USER_REQUIRED = True
api_method = Refund.create
required_params = ["params"]
def set_used_actions(self) -> None:
self.remote_get_payment = self.set_used_action(action_class=RemoteGetYooKassaPayment)
def get_params(
self,
payment_id: str,
amount: float = None,
description: str = None,
receipt: dict = None,
extra_metadata: dict = None,
**kwargs,
):
# Получение информации из сервиса
payment_data = self.remote_get_payment(payment_id=payment_id)[2]["results"]
currency = payment_data["amount"]["currency"]
if not description:
description = payment_data["description"]
if not amount:
amount = payment_data["amount"]["value"]
if not receipt:
receipt = services.BaseYooKassaService.get_receipt_template(
product_description=description,
product_price=amount,
product_price_currency=currency,
user=self.user,
)
kwargs["params"] = {
"amount": {"value": amount, "currency": currency},
"payment_id": payment_id,
"receipt": receipt,
"metadata": extra_metadata,
}
return super().get_params(**kwargs) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/yookassa/core/payment_refund.py | payment_refund.py |
from yookassa import Payment
from zs_utils.api.yookassa.base_action import YooKassaAction
from zs_utils.api.yookassa import services
__all__ = [
"RemoteCreateYooKassaPayment",
]
class RemoteCreateYooKassaPayment(YooKassaAction):
description = "Создание платежа в Яндекс.Кассе"
USER_REQUIRED = True
api_method = Payment.create
required_params = ["params"]
def get_params(
self,
amount: float,
currency: str,
description: str = None,
payment_method_id: str = None,
receipt: dict = None,
extra_metadata: dict = None,
return_url: str = None,
**kwargs,
):
# Описание платежа
if description and (len(description) > 128):
description = description[:125] + "..."
# Метаданные
metadata = {
"user_id": self.user.id,
}
if extra_metadata:
metadata.update(extra_metadata)
if len(metadata.keys()) > 16:
raise self.exception_class("Словарь 'metadata' должен содержать не более 16 ключей.")
kwargs["params"] = {
"amount": {"value": amount, "currency": currency},
"description": description,
"capture": True,
"metadata": metadata,
"confirmation": {
"type": "redirect", # или "embedded"
"return_url": return_url,
"enforce": False,
},
}
if payment_method_id:
# Автоплатеж
kwargs["params"]["payment_method_id"] = payment_method_id
else:
# Подключение карты
kwargs["params"].update(
{
"save_payment_method": True,
"payment_method_data": {"type": "bank_card"},
}
)
if not receipt:
kwargs["params"]["receipt"] = services.BaseYooKassaService.get_receipt_template(
product_description=description,
product_price=amount,
product_price_currency=currency,
user=self.user,
)
return super().get_params(**kwargs)
def success_callback(self, objects: dict, **kwargs) -> None:
super().success_callback(objects, **kwargs)
data = objects["results"]
objects["results"] = {
"backend": "yandex_checkout",
"status": data["status"],
"confirmation_token": None,
"redirect_to_url": None,
}
if data.get("confirmation"):
if data["confirmation"]["type"] == "redirect":
objects["results"]["redirect_to_url"] = data["confirmation"]["confirmation_url"]
elif data["confirmation"]["type"] == "embedded":
objects["results"]["confirmation_token"] = data["confirmation"]["confirmation_token"] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/yookassa/core/payment_create.py | payment_create.py |
from zs_utils.api.shopify.base_api import ShopifyAPI
class GetShopifyOrderListAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/order#get-orders?status=any
"""
http_method = "GET"
resource_method = "orders.json"
allowed_params = [
"attribution_app_id",
"created_at_max",
"created_at_min",
"fields",
"financial_status",
"fulfillment_status",
"ids",
"limit",
"processed_at_max",
"processed_at_min",
"since_id",
"status",
"updated_at_max",
"updated_at_min",
"page_info",
]
class GetShopifyOrderAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/order#get-orders-count?status=any
"""
http_method = "GET"
resource_method = "orders/{order_id}.json"
required_params = ["order_id"]
class UpdateShopifyOrderAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/order#put-orders-order-id
"""
http_method = "PUT"
resource_method = "orders/{order_id}.json"
payload_key = "order"
required_params = ["order_id"]
allowed_params = [
"note",
"note_attributes",
"email",
"phone",
"buyer_accepts_marketing",
"shipping_address",
"customer",
"tags",
"metafields",
]
class CreateShopifyOrderAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/order#post-orders
"""
http_method = "POST"
resource_method = "orders.json"
payload_key = "order"
required_params = ["line_items"]
allowed_params = [
"email",
"phone",
"fulfillment_status",
"inventory_behaviour",
"send_receipt",
"send_fulfillment_receipt",
"fulfillments",
"total_tax",
"currency",
"tax_lines",
"customer",
"financial_status",
"billing_address",
"shipping_address",
"discount_codes",
"note",
"note_attributes",
"buyer_accepts_marketing",
"tags",
"transactions",
"metafields",
]
class DeleteShopifyOrderAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/order#delete-orders-order-id
"""
http_method = "DELETE"
resource_method = "orders/{order_id}.json"
required_params = ["order_id"]
class GetShopifyOrdersCountAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/order#get-orders-count?status=any
"""
http_method = "GET"
resource_method = "orders/count.json"
payload_key = "order"
allowed_params = [
"created_at_max",
"created_at_min",
"financial_status",
"fulfillment_status",
"status",
"updated_at_max",
"updated_at_min",
] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/shopify/core/order.py | order.py |
from zs_utils.api.shopify.base_api import ShopifyAPI
class GetShopifyProductListAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/product#get-products
"""
http_method = "GET"
resource_method = "products.json"
allowed_params = [
"collection_id",
"created_at_max",
"created_at_min",
"fields",
"handle",
"ids",
"limit", # <= 250
"presentment_currencies",
"product_type",
"published_at_max",
"published_at_min",
"published_status",
"since_id",
"status",
"title",
"updated_at_max",
"updated_at_min",
"vendor",
"page_info",
]
class GetShopifyProductCountAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/product#get-products-count
"""
http_method = "GET"
resource_method = "products/count.json"
allowed_params = [
"collection_id",
"created_at_max",
"created_at_min",
"product_type",
"published_at_max",
"published_at_min",
"published_status",
"updated_at_max",
"updated_at_min",
"vendor",
]
class GetShopifyProductAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/product#get-products-product-id
"""
http_method = "GET"
resource_method = "products/{product_id}.json"
required_params = ["product_id"]
allowed_params = ["fields"]
class DeleteShopifyProductAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/product#delete-products-product-id
"""
http_method = "DELETE"
resource_method = "products/{product_id}.json"
required_params = ["product_id"]
class UpdateShopifyProductAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/product#put-products-product-id
"""
http_method = "PUT"
resource_method = "products/{product_id}.json"
payload_key = "product"
required_params = ["product_id"]
allowed_params = [
"title",
"status",
"tags",
"images",
"variants",
"metafields_global_title_tag",
"metafields_global_description_tag",
"published",
"metafields",
]
class CreateShopifyProductAPI(ShopifyAPI):
"""
https://shopify.dev/api/admin-rest/2022-01/resources/product#post-products
"""
http_method = "POST"
resource_method = "products.json"
payload_key = "product"
required_params = [
"title",
]
allowed_params = [
"body_html",
"vendor",
"product_type",
"tags",
"status",
"variants",
"options",
"handle",
"images",
"template_suffix",
"metafields_global_title_tag",
"metafields_global_description_tag",
"metafields",
] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/shopify/core/listing/product.py | product.py |
import requests
from zs_utils.api.constants import API_ERROR_REASONS
from zs_utils.api.base_action import APIAction
from zs_utils.api.amocrm import services
class AmocrmAction(APIAction):
description = "Взаимодествие с API amoCRM"
VALIDATE_PARAMS = True
CUSTOM_FIELDS_MAPPING = None
def __init__(self, app_id: str = None, **kwargs):
super().__init__(**kwargs)
# ID приложения
self.app_id = app_id
if app_id:
self.app = services.AmocrmService.get_amocrm_app(app_id=app_id)
else:
self.app = services.AmocrmService.get_default_amocrm_app()
def get_api_class_init_params(self, **kwargs) -> dict:
if (not self.app.access_token) or self.app.access_token_expired:
if (not self.app.refresh_token) or self.app.refresh_token_expired:
raise self.exception_class("Токен обновления приложения amoCRM недействителен.")
access_token = services.AmocrmService.refresh_amocrm_access_token(app_id=self.app_id)
else:
access_token = self.app.access_token
return {"access_token": access_token}
def get_params(self, **kwargs) -> dict:
if self.CUSTOM_FIELDS_MAPPING:
kwargs = self.process_custom_fields(data=kwargs, fields_mapping=self.CUSTOM_FIELDS_MAPPING)
return super().get_params(**kwargs)
def clean_api_request_params(self, raw_params: dict) -> dict:
params = super().clean_api_request_params(raw_params)
if getattr(self, "api_class", None) and self.api_class.array_payload:
params = {"array_payload": [params]}
return params
def get_error_message(self, results: dict, response: requests.Response) -> str:
message = ""
if results.get("detail"):
message = results["detail"]
elif results.get("title"):
message = results["title"]
if results.get("hint"):
message += ". " + results["hint"]
if results.get("validation-errors"):
for item in results["validation-errors"]:
if item.get("errors"):
for error in item["errors"]:
message += error["path"] + ": " + error["detail"] + ". "
return message
def get_error_reason(self, results: dict, response: requests.Response, error_message: str) -> API_ERROR_REASONS:
if results and results.get("hint") and (results["hint"] == "Token has expired"):
return API_ERROR_REASONS.invalid_token
return super().get_error_reason(results, response, error_message)
@staticmethod
def process_custom_fields(data: dict, fields_mapping: dict):
result = {"custom_fields_values": []}
for key, value in data.items():
if key in fields_mapping:
if isinstance(value, list):
if not value:
continue
values = [{"value": item} for item in value]
else:
if (value is None) or (value == ""):
continue
values = [{"value": value}]
result["custom_fields_values"].append({"field_id": fields_mapping[key], "values": values})
else:
result[key] = value
if not result["custom_fields_values"]:
result.pop("custom_fields_values")
return result | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/amocrm/base_action.py | base_action.py |
import requests
from django.db import transaction
from django.db.models import QuerySet
from django.apps import apps
from django.conf import settings
from django.utils import timezone
from zs_utils.api.amocrm import models
__all__ = [
"AmocrmService",
]
class AmocrmService:
@classmethod
def get_amocrm_app_model(cls, raise_exception: bool = True) -> type[models.AbstractAmocrmApp] | None:
if getattr(settings, "AMOCRM_APP_MODEL", None):
app_label, model_name = settings.AMOCRM_APP_MODEL.split(".")
model = apps.get_model(app_label=app_label, model_name=model_name)
else:
model = models.AmocrmApp
if (not model) and raise_exception:
raise ValueError("Необходимо задать настройку 'AMOCRM_APP_MODEL'.")
return model
@classmethod
def get_amocrm_app(cls, app_id: str) -> models.AbstractAmocrmApp:
return cls.get_amocrm_app_model(raise_exception=True).objects.get(id=app_id)
@classmethod
def get_default_amocrm_app(cls) -> models.AbstractAmocrmApp:
return cls.get_amocrm_app_model(raise_exception=True).objects.get(is_default=True)
@classmethod
def retrieve_amocrm_tokens(
cls,
client_id: str,
client_secret: str,
redirect_uri: str,
refresh_token: str = None,
code: str = None,
) -> dict:
"""
Получение новых токенов доступа и обновления либос помощью текущего токена обновления,
либо с помощью одноразового кода.
Docs: https://www.amocrm.ru/developers/content/oauth/step-by-step#get_access_token
"""
assert bool(refresh_token) != bool(code), "Необходимо задать либо 'refresh_token', либо 'code'."
payload = {
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": redirect_uri,
}
if refresh_token:
payload.update({"grant_type": "refresh_token", "refresh_token": refresh_token})
else:
payload.update({"grant_type": "authorization_code", "code": code})
response = requests.post(url=settings.AMOCRM_API_URL + "oauth2/access_token", json=payload)
response.raise_for_status()
return response.json()
@classmethod
@transaction.atomic()
def refresh_amocrm_access_token(cls, app_id: str = None) -> str:
"""
Получение токена доступа amoCRM
"""
app_qs: QuerySet[models.AbstractAmocrmApp] = cls.get_amocrm_app_model(
raise_exception=True
).objects.select_for_update()
if app_id:
app = app_qs.get(id=app_id)
else:
app = app_qs.get(is_default=True)
if not app.refresh_token:
raise ValueError("Отсутствует токен обновления AmoCRM.")
# Получение новых токенов
response_data: dict = cls.retrieve_amocrm_tokens(
client_id=app.client_id,
client_secret=app.client_secret,
redirect_uri=app.redirect_uri,
refresh_token=app.refresh_token,
)
# Сохранение нового refresh_token
app.access_token = response_data["access_token"]
app.access_token_expiry = timezone.now() + timezone.timedelta(seconds=response_data["expires_in"])
app.refresh_token = response_data["refresh_token"]
app.refresh_token_expiry = timezone.now() + timezone.timedelta(days=90)
app.save()
return app.access_token
@classmethod
def refresh_amocrm_apps(cls) -> None:
if not settings.AMOCRM_APPS:
return None
for app_config in settings.AMOCRM_APPS:
for key in [
"name",
"is_default",
"client_id",
"client_secret",
"redirect_uri",
]:
if app_config.get(key) is None:
raise ValueError(f"У конфига приложения amoCRM не задан ключ '{key}'.")
if sum(int(app_config["is_default"]) for app_config in settings.AMOCRM_APPS) != 1:
raise ValueError("Среди приложений amoCRM ровно одно должно быть приложением по умолчанию.")
app_model = cls.get_amocrm_app_model(raise_exception=True)
for app_config in settings.AMOCRM_APPS:
app_model.objects.update_or_create(name=app_config["name"], defaults=app_config) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/amocrm/services.py | services.py |
from django.utils import timezone
from django.conf import settings
from zs_utils.api.amocrm.base_action import AmocrmAction
from zs_utils.api.amocrm import core
__all__ = [
"RemoteGetAmocrmContactByLead",
"RemoteCreateAmocrmContact",
"RemoteCreateAmocrmLead",
"RemoteUpdateAmocrmLead",
"RemoteCreateAmocrmTask",
]
class RemoteGetAmocrmContactByLead(AmocrmAction):
description = "Получение информации о сделке amoCRM"
api_class = core.GetAmocrmLeadAPI
required_params = ["lead_id"]
allowed_params = ["with"]
def get_params(self, **kwargs) -> dict:
kwargs["with"] = "contacts"
return super().get_params(**kwargs)
def format_success_results(self, results: dict, **kwargs) -> dict:
return {"contact_id": results["_embedded"]["contacts"][0]["id"]}
class RemoteCreateAmocrmContact(AmocrmAction):
description = "Создание контакта на amoCRM"
api_class = core.CreateAmocrmContactAPI
SAVE_REQUEST_LOG = True
CUSTOM_FIELDS_MAPPING = settings.AMOCRM_CONTACT_CUSTOM_FIELDS
required_params = []
allowed_params = [
"name",
"first_name",
"last_name",
"custom_fields_values",
"responsible_user_id",
]
def get_params(self, responsible_user_id: int = None, **kwargs) -> dict:
if not responsible_user_id:
responsible_user_id = settings.AMOCRM_DEFAULT_MANAGER_ID
return super().get_params(responsible_user_id=responsible_user_id, **kwargs)
def format_success_results(self, results: dict, **kwargs) -> dict:
return {"contact_id": results["_embedded"]["contacts"][0]["id"]}
class RemoteCreateAmocrmLead(AmocrmAction):
description = "Создание сделки на amoCRM"
api_class = core.CreateAmocrmLeadAPI
SAVE_REQUEST_LOG = True
CUSTOM_FIELDS_MAPPING = settings.AMOCRM_LEAD_CUSTOM_FIELDS
required_params = [
"pipeline_id",
"_embedded",
]
allowed_params = [
"created_by",
"updated_by",
"status_id",
"custom_fields_values",
"name",
"price",
"responsible_user_id",
]
def get_params(
self,
pipeline_id: int,
contact_id: int,
status_id: int,
responsible_user_id: int = None,
**kwargs,
) -> dict:
if not responsible_user_id:
responsible_user_id = settings.AMOCRM_DEFAULT_MANAGER_ID
kwargs.update(
{
"pipeline_id": pipeline_id,
"status_id": status_id,
"responsible_user_id": responsible_user_id,
"_embedded": {
"contacts": [{"id": contact_id}],
"tags": [],
},
}
)
# Теги
tags = kwargs.pop("tags", [])
for tag in tags:
kwargs["_embedded"]["tags"].append({"name": tag})
return super().get_params(**kwargs)
def format_success_results(self, results: dict, **kwargs) -> dict:
return {"lead_id": results["_embedded"]["leads"][0]["id"]}
class RemoteUpdateAmocrmLead(AmocrmAction):
description = "Обновление сделки amoCRM"
api_class = core.UpdateAmocrmLeadAPI
SAVE_REQUEST_LOG = True
CUSTOM_FIELDS_MAPPING = settings.AMOCRM_LEAD_CUSTOM_FIELDS
required_params = [
"id",
]
allowed_params = [
"name",
"price",
"pipeline_id",
"_embedded",
"status_id",
"created_by",
"updated_by",
"responsible_user_id",
"loss_reason_id",
"custom_fields_values",
]
def get_params(self, lead_id: int, **kwargs) -> dict:
kwargs["id"] = lead_id
return super().get_params(**kwargs)
class RemoteCreateAmocrmTask(AmocrmAction):
description = "Создание задачи на amoCRM"
api_class = core.CreateAmocrmTaskAPI
SAVE_REQUEST_LOG = True
required_params = [
"text",
"complete_till",
]
allowed_params = [
"responsible_user_id",
"created_by",
"updated_by",
"entity_id",
"entity_type",
"is_completed",
"task_type_id",
"duration",
"result",
]
def get_params(
self,
lead_id: str,
responsible_user_id: int = None,
created_user_id: int = None,
complete_till: timezone.datetime = None,
**kwargs,
) -> dict:
if not responsible_user_id:
responsible_user_id = settings.AMOCRM_DEFAULT_MANAGER_ID
if not created_user_id:
created_user_id = settings.AMOCRM_MAIN_MANAGER_ID
kwargs.update(
{
"responsible_user_id": responsible_user_id,
"created_by": created_user_id,
"complete_till": int(complete_till.timestamp()),
"entity_id": lead_id,
"entity_type": "leads",
}
)
return super().get_params(**kwargs)
def format_success_results(self, results: dict, **kwargs) -> dict:
return {"task_id": results["_embedded"]["tasks"][0]["id"]} | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/amocrm/actions.py | actions.py |
from zs_utils.api.wildberries.base_api import WildberriesAPI
class GetWildberriesNomenclatureList(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Kontent-Prosmotr/paths/~1content~1v1~1cards~1cursor~1list/post
"""
http_method = "POST"
resource_method = "content/v1/cards/cursor/list"
required_params = ["sort"]
class GetWildberriesNomenclatureByVendorCode(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Kontent-Prosmotr/paths/~1content~1v1~1cards~1filter/post
"""
http_method = "POST"
resource_method = "content/v1/cards/filter"
required_params = ["vendorCodes"]
class GetWildberriesPrices(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Ceny/paths/~1public~1api~1v1~1info/get
"""
http_method = "GET"
resource_method = "public/api/v1/info"
allowed_params = ["quantity"]
class UpdateWildberriesPrices(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Ceny/paths/~1public~1api~1v1~1prices/post
"""
http_method = "POST"
resource_method = "public/api/v1/prices"
array_payload = True
class UpdateWildberriesDiscounts(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Promokody-i-skidki/paths/~1public~1api~1v1~1updateDiscounts/post
"""
http_method = "POST"
resource_method = "public/api/v1/updateDiscounts"
array_payload = True
class RevokeWildberriesDiscounts(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Promokody-i-skidki/paths/~1public~1api~1v1~1revokeDiscounts/post
"""
http_method = "POST"
resource_method = "public/api/v1/revokeDiscounts"
array_payload = True
class CreateWildberriesBarcodes(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Kontent-Prosmotr/paths/~1content~1v1~1barcodes/post
"""
http_method = "POST"
resource_method = "content/v1/barcodes"
required_params = ["count"]
class GetWildberriesFailedToUploadNomenclatureList(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Kontent-Prosmotr/paths/~1content~1v1~1cards~1error~1list/get
"""
http_method = "GET"
resource_method = "content/v1/cards/error/list"
class CreateWildberriesNomenclature(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Kontent-Zagruzka/paths/~1content~1v1~1cards~1upload/post
"""
http_method = "POST"
resource_method = "content/v1/cards/upload"
array_payload = True
class UpdateWildberriesNomenclature(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Kontent-Zagruzka/paths/~1content~1v1~1cards~1update/post
"""
http_method = "POST"
resource_method = "content/v1/cards/update"
array_payload = True
class AddWildberriesNomenclaturesToCard(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Kontent-Zagruzka/paths/~1content~1v1~1cards~1upload~1add/post
"""
http_method = "POST"
resource_method = "content/v1/cards/upload/add"
required_params = [
"vendorCode",
"cards",
]
class UpdateWildberriesNomenclatureImages(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Kontent-Mediafajly/paths/~1content~1v1~1media~1save/post
"""
http_method = "POST"
resource_method = "content/v1/media/save"
required_params = [
"vendorCode",
"data",
] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/wildberries/core/listing.py | listing.py |
from zs_utils.api.wildberries.base_api import WildberriesAPI
class GetWildberriesOrders(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1orders/get
"""
http_method = "GET"
resource_method = "api/v3/orders"
required_params = [
"limit", # 1000
"next", # offset, 0 for the first request
]
allowed_params = [
"dateFrom",
"dateTo",
]
class GetWildberriesNewOrders(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1orders~1new/get
"""
http_method = "GET"
resource_method = "api/v3/orders/new"
class CancelWildberriesOrder(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1orders~1%7BorderId%7D~1cancel/patch
"""
http_method = "PATCH"
resource_method = "api/v3/orders/{order_id}/cancel"
required_params = [
"order_id",
]
class GetWildberriesOrdersStatus(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1orders~1status/post
"""
http_method = "POST"
resource_method = "api/v3/orders/status"
required_params = [
"orders",
]
class DeleteWildberriesSupply(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1supplies~1%7BsupplyId%7D/delete
"""
http_method = "DELETE"
resource_method = "api/v3/supplies/{supply_id}"
required_params = [
"supply_id",
]
class GetWildberriesSupplies(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1supplies/get
"""
http_method = "GET"
resource_method = "api/v3/supplies"
required_params = [
"limit", # Up to 1000
"next", # offset, 0 for the first request
]
class GetWildberriesSupplyOrders(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1supplies~1%7BsupplyId%7D~1orders/get
"""
http_method = "GET"
resource_method = "api/v3/supplies/{supply_id}/orders"
required_params = [
"supply_id",
]
class GetWildberriesSupplyBarcode(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1supplies~1%7BsupplyId%7D~1barcode/get
"""
http_method = "GET"
resource_method = "api/v3/supplies/{supply_id}/barcode"
required_params = [
"supply_id",
"type",
]
class GetWildberriesOrdersStickers(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1orders~1stickers/post
"""
http_method = "POST"
resource_method = "api/v3/orders/stickers"
required_params = [
"type",
"width",
"height",
"orders",
]
class CreateWildberriesSupply(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1supplies/post
"""
http_method = "POST"
resource_method = "api/v3/supplies"
allowed_params = ["name"]
class AddOrdersToWildberriesSupply(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1supplies~1%7BsupplyId%7D~1orders~1%7BorderId%7D/patch
"""
http_method = "PATCH"
resource_method = "api/v3/supplies/{supply_id}/orders/{order_id}"
required_params = [
"supply_id",
"order_id",
]
class CloseWildberriesSupply(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1supplies~1%7BsupplyId%7D~1deliver/patch
"""
http_method = "PATCH"
resource_method = "api/v3/supplies/{supply_id}/deliver"
required_params = [
"supply_id",
]
class AddWildberriesSgtinToOrder(WildberriesAPI):
"""
https://openapi.wb.ru/#tag/Marketplace-Sborochnye-zadaniya/paths/~1api~1v3~1orders~1%7BorderId%7D~1meta~1sgtin/post
"""
http_method = "POST"
resource_method = "api/v3/orders/{order_id}/meta/sgtin"
required_params = [
"order_id",
"sgtin",
] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/wildberries/core/order.py | order.py |
from zs_utils.api.aliexpress_russia.base_api import AliexpressRussiaAPI
class GetAliexpressListingListAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/product-list#heading-poluchit-otfiltrovannii-spisok-tovarov
"""
resource_method = "/api/v1/scroll-short-product-by-filter"
required_params = ["limit"] # 50
allowed_params = [
"filter",
"last_product_id",
]
class GetAliexpressListingAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/product-list#heading-poluchit-informatsiyu-o-tovare
"""
resource_method = "/api/v1/product/get-seller-product"
required_params = ["product_id"]
class CreateAliexpressListingAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/local-create-products
"""
resource_method = "/api/v1/product/create"
required_params = ["products"]
class UpdateAliexpressListingAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/post-products#heading-obnovit-vse-polya-tovara
"""
resource_method = "/api/v1/product/edit"
required_params = ["products"]
class SetPublishedAliexpressListingAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/post-products#heading-vernut-tovari-v-prodazhu
"""
resource_method = "/api/v1/product/online"
required_params = ["productIds"] # 20
class SetUnpublishedAliexpressListingAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/post-products#heading-snyat-tovari-s-prodazhi
"""
resource_method = "/api/v1/product/offline"
required_params = ["productIds"] # 20
class GetAliexpressListingStatusAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/post-products#heading-poluchit-statusi-zagruzkiobnovleniya-tovara
"""
http_method = "GET"
resource_method = "/api/v1/tasks"
required_params = ["group_id"]
class GetAliexpressProductStocksAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/manage-stocks#heading-poluchit-ostatki-tovara
"""
resource_method = "/api/v1/stocks"
required_params = ["stocks"]
class UpdateAliexpressProductStocksAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/manage-stocks#heading-obnovit-ostatki-tovara-po-sku-kodu
"""
resource_method = "/api/v1/product/update-sku-stock"
required_params = ["products"]
class UpdateAliexpressProductPriceAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/manage-stocks#heading-obnovit-tsenu-tovara-po-sku-kodu
"""
resource_method = "/api/v1/product/update-sku-price"
required_params = ["products"]
class GetAliexpressShippingTemplatesAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/local-get-shipping-templates
"""
http_method = "GET"
resource_method = "/api/v1/sellercenter/get-count-product-on-onboarding-template" | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/aliexpress_russia/core/product.py | product.py |
from zs_utils.api.aliexpress_russia.base_api import AliexpressRussiaAPI
class CreateAliexpressShipmentAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/local-logistic-orders#heading-sozdat-otpravlenie
"""
resource_method = "/seller-api/v1/logistic-order/create"
required_params = ["orders"]
class DeleteAliexpressShipmentAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/local-logistic-orders#heading-udalit-otpravlenie
"""
resource_method = "/seller-api/v1/logistic-order/delete"
required_params = ["logistic_order_ids"]
class GetAliexpressLabelAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/local-logistic-orders#heading-napechatat-etiketki-dlya-otpravlenii
"""
resource_method = "/seller-api/v1/labels/orders/get"
required_params = ["logistic_order_ids"]
# Лист передач (накладная)
class GetAliexpressHandoverListsAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/local-handover-list#heading-poluchit-spisok-listov-peredachi
"""
resource_method = "/seller-api/v1/handover-list/get-by-filter"
required_params = ["page_size", "page_number"]
allowed_params = [
"statuses",
"handover_list_ids",
"logistic_order_ids",
"gmt_create_from",
"gmt_create_to",
"arrival_date_sort",
"gmt_create_sort",
]
class CreateAliexpressHandoverListAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/local-handover-list#heading-sozdat-list-peredachi
"""
resource_method = "/seller-api/v1/handover-list/create"
required_params = ["logistic_order_ids"]
class CloseAliexpressHandoverListAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/local-handover-list#heading-zakrit-list-peredachi
"""
resource_method = "/seller-api/v1/handover-list/transfer"
required_params = ["handover_list_id"]
class AddAliexpressShipmentToHandoverListAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/local-handover-list#heading-dobavit-otpravlenie-v-list-peredachi
"""
resource_method = "/seller-api/v1/handover-list/add-logistic-orders"
required_params = ["handover_list_id", "order_ids"]
class DeleteAliexpressShipmentFromHandoverListAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/local-handover-list#heading-udalit-otpravlenie-iz-lista-peredachi
"""
resource_method = "/seller-api/v1/handover-list/remove-logistic-orders"
required_params = ["handover_list_id", "order_ids"]
class GetAliexpressHandoverListLabelAPI(AliexpressRussiaAPI):
"""
https://business.aliexpress.ru/docs/local-handover-list#heading-napechatat-list-peredachi
"""
resource_method = "/seller-api/v1/labels/handover-lists/get"
required_params = ["handover_list_id"] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/aliexpress_russia/core/shipment.py | shipment.py |
from zs_utils.api.ozon.base_api import OzonAPI
class OzonGetProductListAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/ProductAPI_GetProductList
"""
resource_method = "v2/product/list"
allowed_params = [
"filter",
"last_id",
"limit",
]
class OzonGetProductsInfoAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/ProductAPI_GetProductInfoListV2
"""
resource_method = "v2/product/info/list"
allowed_params = ["offer_id", "product_id", "sku"]
class OzonGetProductsAttributeAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/ProductAPI_GetProductAttributesV3
"""
resource_method = "v3/products/info/attributes"
required_params = ["limit"]
allowed_params = [
"filter",
"last_id",
"sort_by",
"sort_dir",
]
class OzonGetProductsFBSStocksAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/ProductAPI_ProductStocksByWarehouseFbs
"""
resource_method = "v1/product/info/stocks-by-warehouse/fbs"
required_params = ["fbs_sku"]
class OzonGetProductStatusAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/ProductAPI_GetImportProductsInfo
"""
resource_method = "v1/product/import/info"
required_params = ["task_id"]
class OzonCreateProductAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/ProductAPI_ImportProductsV2
"""
resource_method = "v2/product/import"
required_params = ["items"]
class OzonUpdateProductStocksAPI(OzonAPI):
resource_method = "v1/product/import/stocks"
required_params = ["stocks"]
class OzonUpdateProductWarehouseStocksAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/ProductAPI_ProductsStocksV2
"""
resource_method = "v2/products/stocks"
required_params = ["stocks"]
class OzonArchiveProductAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/ProductAPI_ProductArchive
"""
resource_method = "v1/product/archive"
required_params = ["product_id"]
class OzonDeleteProductFromArchiveAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/ProductAPI_DeleteProducts
"""
resource_method = "v2/products/delete"
required_params = ["products"]
class OzonReturnProductFromArchiveAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/ProductAPI_ProductUnarchive
"""
resource_method = "v1/product/unarchive"
required_params = ["product_id"]
class OzonUpdateProductPricesAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/ProductAPI_ImportProductsPrices
"""
resource_method = "v1/product/import/prices"
required_params = ["prices"] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ozon/core/listing.py | listing.py |
from zs_utils.api.ozon.base_api import OzonAPI
# --------------------------- FBO ---------------------------
# Отправления, которые обрабатывает Озон
class OzonGetFBOShipmentListAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/PostingAPI_GetFboPostingList
"""
resource_method = "v2/posting/fbo/list"
required_params = [
"limit",
]
allowed_params = ["offset", "dir", "filter"]
# --------------------------- FBS ---------------------------
# Отправления, которые обрабатывает пользователь
class OzonGetFBSShipmentListAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/PostingAPI_GetFbsPostingListV3
"""
resource_method = "v3/posting/fbs/list"
required_params = [
"limit",
]
allowed_params = ["offset", "dir", "filter"]
class OzonGetFBSShipmentAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/PostingAPI_GetFbsPostingV3
"""
resource_method = "v3/posting/fbs/get"
required_params = [
"posting_number",
]
allowed_params = ["with"]
class OzonCreateFBSShipmentAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/PostingAPI_ShipFbsPostingV3
"""
resource_method = "v3/posting/fbs/ship"
required_params = [
"packages",
"posting_number",
]
allowed_params = ["with"]
class OzonGetLabelAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/PostingAPI_PostingFBSPackageLabel
"""
resource_method = "v2/posting/fbs/package-label"
required_params = ["posting_number"]
class OzonShipmentDeliveringAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/PostingAPI_FbsPostingDelivering
"""
resource_method = "v2/fbs/posting/delivering"
required_params = ["posting_number"]
class OzonShipmentDeliveredAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/PostingAPI_FbsPostingDelivered
"""
resource_method = "v2/fbs/posting/delivered"
required_params = ["posting_number"]
class OzonShipmentLastMileAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/PostingAPI_FbsPostingLastMile
"""
resource_method = "v2/fbs/posting/last-mile"
required_params = ["posting_number"]
class OzonSetShipmentTrackingNumberAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/PostingAPI_FbsPostingTrackingNumberSet
"""
resource_method = "v2/fbs/posting/tracking-number/set"
required_params = ["tracking_numbers"]
class OzonCancelShipmentAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/PostingAPI_CancelFbsPosting
"""
resource_method = "v2/posting/fbs/cancel"
required_params = [
"posting_number",
"cancel_reason_id",
]
allowed_params = ["cancel_reason_message"]
class OzonGetShipmentCancelReasonsAPI(OzonAPI):
"""
Docs: https://docs.ozon.ru/api/seller/#operation/PostingAPI_GetPostingFbsCancelReasonList
"""
resource_method = "v2/posting/fbs/cancel-reason/list" | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ozon/core/shipment.py | shipment.py |
import json
from datetime import datetime
from hashlib import md5
from zs_utils.api.base_api import BaseAPI
class AliexpressAPI(BaseAPI):
production_api_url = "http://gw.api.taobao.com/router/rest"
sandbox_url = "http://gw.api.tbsandbox.com/router/rest"
http_method = "POST"
def __init__(self, app_key: str, app_secret: str, access_token: str, **kwargs):
super().__init__(**kwargs)
self.app_key = app_key
self.app_secret = app_secret
self.access_token = access_token
def build_url(self, params: dict) -> str:
return self.sandbox_api_url if self.is_sandbox else self.production_api_url
@property
def headers(self) -> dict:
return {
"Content-Type": "application/x-www-form-urlencoded",
}
def add_sign(self, params):
params.update(
{
"session": self.access_token,
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"app_key": self.app_key,
"format": "json",
"v": "2.0",
"sign_method": "md5",
"method": self.resource_method,
}
)
params = dict(sorted(params.items()))
for_sign = self.app_secret + str().join([key + value for key, value in params.items()]) + self.app_secret
sign = md5(for_sign.encode("utf-8")).hexdigest().upper()
params["sign"] = sign
return params
def get_clean_params(self, params):
clean_params = super().get_clean_params(params=params)
for key, value in clean_params.items():
if (not isinstance(value, str)) and (value is not None):
clean_params[key] = json.dumps(value)
files = clean_params.pop("files", None)
params_with_sign = self.add_sign(clean_params)
params_with_sign["files"] = files # TODO: это нужно?
return params_with_sign
def get_request_params(self, **kwargs) -> dict:
clean_params = self.get_clean_params(kwargs)
return dict(
url=self.build_url(kwargs),
headers=self.headers,
data=clean_params,
) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/aliexpress/base_api.py | base_api.py |
from zs_utils.api.aliexpress.base_api import AliexpressAPI
# PRODUCT
class CreateProductAPI(AliexpressAPI):
resource_method = "aliexpress.solution.product.post"
required_params = ["post_product_request"]
class EditProductAPI(AliexpressAPI):
resource_method = "aliexpress.solution.product.edit"
required_params = ["edit_product_request"]
class GetProductAPI(AliexpressAPI):
"""
Docs: https://developers.aliexpress.com/en/doc.htm?docId=42383&docType=2
"""
resource_method = "aliexpress.solution.product.info.get"
required_params = ["product_id"]
class GetProductListAPI(AliexpressAPI):
"""
Docs: https://developers.aliexpress.com/en/doc.htm?docId=42384&docType=2
"""
resource_method = "aliexpress.solution.product.list.get"
required_params = ["aeop_a_e_product_list_query"]
class GetSkuAttributeAPI(AliexpressAPI):
resource_method = "aliexpress.solution.sku.attribute.query"
allowed_params = ["query_sku_attribute_info_request"]
# В доках нет
# class EditProductSkuInventoryAPI(AliexpressAPI):
# resource_method = "aliexpress.solution.product.sku.inventory.edit"
# required_params = ["edit_product_sku_inventory_request"]
#
#
# class EditProductSkuPriceAPI(AliexpressAPI):
# resource_method = "aliexpress.solution.product.sku.price.edit"
# required_params = ["edit_product_sku_price_request"]
class DeleteProductsAPI(AliexpressAPI):
resource_method = "aliexpress.solution.batch.product.delete"
required_params = ["productIds"]
class UpdateBatchProductPriceAPI(AliexpressAPI):
"""
Docs: https://developers.aliexpress.com/en/doc.htm?docId=45140&docType=2
"""
resource_method = "aliexpress.solution.batch.product.price.update"
required_params = ["mutiple_product_update_list"]
class UpdateBatchInventory(AliexpressAPI):
"""
Docs: https://developers.aliexpress.com/en/doc.htm?docId=45135&docType=2
"""
resource_method = "aliexpress.solution.batch.product.inventory.update"
required_params = ["mutiple_product_update_list"]
class OnlineProductAPI(AliexpressAPI):
resource_method = "aliexpress.postproduct.redefining.onlineaeproduct"
allowed_params = ["product_ids"]
class OfflineProductAPI(AliexpressAPI):
resource_method = "aliexpress.postproduct.redefining.offlineaeproduct"
allowed_params = ["product_ids"]
class SubmitFeedDataAPI(AliexpressAPI):
resource_method = "aliexpress.solution.feed.submit"
required_params = ["operation_type", "item_list"]
class FeedQueryAPI(AliexpressAPI):
resource_method = "aliexpress.solution.feed.query"
allowed_params = ["job_id"]
class GetFeedListAPI(AliexpressAPI):
resource_method = "aliexpress.solution.feed.list.get"
allowed_params = ["current_page", "data_type", "page_size", "status"]
# PRODUCT SCHEMA
class GetProductSchemaAPI(AliexpressAPI):
resource_method = "aliexpress.solution.product.schema.get"
required_params = ["aliexpress_category_id"]
class PostProductBasedOnSchemaAPI(AliexpressAPI):
resource_method = "aliexpress.solution.schema.product.instance.post"
required_params = ["product_instance_request"]
class UpdateProductBasedOnSchemaAPI(AliexpressAPI):
resource_method = "aliexpress.solution.schema.product.full.update"
required_params = ["schema_full_update_request"]
# PRODUCT GROUP
class CreateProductGroupAPI(AliexpressAPI):
resource_method = "aliexpress.postproduct.redefining.createproductgroup"
allowed_params = ["name", "parent_id"]
class SetProductGroupAPI(AliexpressAPI):
resource_method = "aliexpress.postproduct.redefining.setgroups"
allowed_params = ["product_id", "group_ids"]
class GetProductGroupAPI(AliexpressAPI):
resource_method = "aliexpress.product.productgroups.get"
# PRODUCT IMAGE
class UploadProductImageAPI(AliexpressAPI):
resource_method = "aliexpress.photobank.redefining.uploadimageforsdk"
allowed_params = ["group_id", "image_bytes", "file_name"] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/aliexpress/core/product.py | product.py |
from zs_utils.api.yandex_market.base_api import YandexMarketAPI
class SendYandexMarketShipmentBoxesAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-marketplace-cd/doc/dg/reference/put-campaigns-id-orders-id-delivery-shipments-id-boxes.html
"""
description = "Передача информации о грузовых местах в заказе Yandex Market"
http_method = "PUT"
resource_method = "campaigns/{shop_id}/orders/{order_id}/delivery/shipments/{shipment_id}/boxes"
required_params = [
"shop_id",
"order_id",
"shipment_id",
"boxes",
]
class GetYandexMarketTransferActAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-marketplace-cd/doc/dg/reference/get-campaigns-id-shipments-reception-transfer-act.html
"""
description = "Получение акта приема-передачи сегодняшних заказов Yandex Market"
http_method = "GET"
resource_method = "campaigns/{shop_id}/shipments/reception-transfer-act"
required_params = [
"shop_id",
]
class GetYandexMarketRegions(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/get-regions.html
"""
description = "Поиск региона"
http_method = "GET"
resource_method = "regions"
required_params = [
"name",
]
class GetYandexMarketDeliveryServicesAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/get-delivery-services.html
"""
description = "Получение служб доставки Yandex Market"
http_method = "GET"
resource_method = "delivery/services"
class GetYandexMarketOrderListAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/get-campaigns-id-orders.html
"""
description = "Получение списка заказов Yandex Market"
http_method = "GET"
resource_method = "campaigns/{shop_id}/orders"
allowed_params = [
"shop_id",
"fromDate",
"toDate",
"status",
"substatus",
"page",
"pageSize",
]
class GetYandexMarketOrderAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/get-campaigns-id-orders-id.html
"""
description = "Получения заказа Yandex Market"
http_method = "GET"
resource_method = "campaigns/{shop_id}/orders/{order_id}"
required_params = [
"shop_id",
"order_id",
]
class ChangeYandexMarketOrderStatusAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/put-campaigns-id-orders-id-status.html
"""
description = "Изменение статуса заказа Yandex Market"
http_method = "PUT"
resource_method = "campaigns/{shop_id}/orders/{order_id}/status"
required_params = [
"shop_id",
"order_id",
"order",
]
class ChangeYandexMarketDigitalOrderStatusAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/troubleshooting/general.html#general__digital
"""
description = "Изменение статуса цифрового заказа Yandex Market"
http_method = "POST"
resource_method = "campaigns/{shop_id}/orders/{order_id}/deliverDigitalGoods"
required_params = [
"shop_id",
"order_id",
]
class GetYandexMarketShipmentLabelsAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-marketplace-cd/doc/dg/reference/get-campaigns-id-orders-id-delivery-labels.html
"""
description = "Получение ярлыков‑наклеек на все грузовые места в заказе Yandex Market"
http_method = "GET"
resource_method = "campaigns/{shop_id}/orders/{order_id}/delivery/labels"
required_params = [
"shop_id",
"order_id",
]
class SetYandexMarketShipmentTrackAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/post-campaigns-id-orders-id-delivery-track.html
"""
description = "Передача трек-номера посылки"
http_method = "POST"
resource_method = "campaigns/{shop_id}/orders/{order_id}/delivery/track"
required_params = [
"shop_id",
"order_id",
] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/yandex_market/core/order.py | order.py |
from zs_utils.api.base_api import BaseAPI
from zs_utils.api.yandex_market.base_api import YandexMarketAPI
class GetYandexMarketShopListAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/get-campaigns.html
"""
description = "Получение списка магазинов Yandex Market"
http_method = "GET"
resource_method = "campaigns"
allowed_params = ["page", "pageSize"]
class GetYandexMarketShopAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/get-campaigns-id.html
"""
description = "Получение информации о магазине Yandex Market"
http_method = "GET"
resource_method = "campaigns/{shop_id}"
required_params = [
"shop_id",
]
class GetYandexMarketShopLoginListAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/get-campaigns-id-logins.html
"""
description = "Получение списка логинов, у которых есть доступ к магазину Yandex Market"
http_method = "GET"
resource_method = "campaigns/{shop_id}/logins"
required_params = [
"shop_id",
]
class GetYandexMarketShopListByLoginAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/get-campaigns-by-login.html
"""
description = "Получение списка магазинов, к которым есть доступ по данному логину. Yandex Market"
http_method = "GET"
resource_method = "campaigns/by_login/{login}"
required_params = [
"login",
]
class GetYandexMarketShopSettingsAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/get-campaigns-id-settings.html
"""
description = "Получение настроек магазина Yandex Market"
http_method = "GET"
resource_method = "campaigns/{shop_id}/settings"
required_params = [
"shop_id",
]
class GetYandexMarketShopCategoriesAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/get-campaigns-id-feeds-categories.html
"""
description = "Получение категорий магазина Яндекс.Маркета"
http_method = "GET"
resource_method = "campaigns/{shop_id}/feeds/categories"
required_params = [
"shop_id",
]
class GetYandexMarketOutletsAPI(YandexMarketAPI):
"""
https://yandex.ru/dev/market/partner-dsbs/doc/dg/reference/get-campaigns-id-outlets.html
"""
description = "Получение точек продаж магазина Яндекс.Маркета"
http_method = "GET"
resource_method = "campaigns/{shop_id}/outlets"
required_params = [
"shop_id",
]
class GetYandexMarketAccountInfo(BaseAPI):
http_method = "GET"
def __init__(self, access_token: str, **kwargs):
super().__init__(**kwargs)
self.access_token = access_token
def build_url(self, params: dict) -> str:
return f"https://login.yandex.ru/info?format=json&oauth_token={self.access_token}"
def validate_attrs(self) -> None:
pass | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/yandex_market/core/shop.py | shop.py |
from zs_utils.api.etsy.base_api import EtsyAPI
class GetEtsyShippingProfileList(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingShippingProfiles
"""
http_method = "GET"
resource_method = "shops/{shop_id}/shipping-profiles"
required_params = ["shop_id"]
class GetEtsyShippingProfile(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingShippingProfile
"""
http_method = "GET"
resource_method = "shops/{shop_id}/shipping-profiles/{shipping_profile_id}"
required_params = ["shop_id", "shipping_profile_id"]
class DeleteEtsyShippingProfile(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/deleteListingShippingProfile
"""
http_method = "DELETE"
resource_method = "shops/{shop_id}/shipping-profiles/{shipping_profile_id}"
required_params = ["shop_id", "shipping_profile_id"]
class CreateEtsyShippingProfile(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/createListingShippingProfile
"""
http_method = "POST"
resource_method = "shops/{shop_id}/shipping-profiles"
required_params = [
"shop_id",
"title",
"origin_country_iso",
"primary_cost",
"secondary_cost",
"min_processing_time",
"max_processing_time",
]
allowed_params = [
"destination_country_iso",
"destination_region",
"origin_postal_code",
"shipping_carrier_id",
"mail_class",
"min_processing_time",
"max_processing_time",
"min_delivery_days",
"max_delivery_days",
]
class UpdateEtsyShippingProfile(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/updateListingShippingProfile
"""
http_method = "PUT"
resource_method = "shops/{shop_id}/shipping-profiles/{shipping_profile_id}"
required_params = ["shop_id", "shipping_profile_id"]
allowed_params = [
"title",
"origin_country_iso",
"origin_postal_code",
"min_processing_time",
"max_processing_time",
] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/etsy/core/shipping_profile.py | shipping_profile.py |
from zs_utils.api.etsy.base_api import EtsyAPI
class CreateEtsyShippingProfileDestination(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/createListingShippingProfileDestination
"""
http_method = "POST"
resource_method = "shops/{shop_id}/shipping-profiles/{shipping_profile_id}/destinations"
required_params = [
"shop_id",
"shipping_profile_id",
"primary_cost",
"secondary_cost",
]
allowed_params = [
"destination_country_iso",
"destination_region",
"shipping_carrier_id",
"mail_class",
"min_delivery_days",
"max_delivery_days",
]
class GetEtsyShippingProfileDestinationList(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingShippingProfileDestinationsByShippingProfile
"""
http_method = "POST"
resource_method = "shops/{shop_id}/shipping-profiles/{shipping_profile_id}/destinations"
required_params = ["shop_id", "shipping_profile_id"]
class UpdateEtsyShippingProfileDestination(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/updateListingShippingProfileDestination
"""
http_method = "PUT"
resource_method = (
"shops/{shop_id}/shipping-profiles/{shipping_profile_id}/destinations/{shipping_profile_destination_id}"
)
required_params = [
"shop_id",
"shipping_profile_id",
"shipping_profile_destination_id",
]
allowed_params = [
"primary_cost",
"secondary_cost",
"destination_country_iso",
"destination_region",
"shipping_carrier_id",
"mail_class",
"min_delivery_days",
"max_delivery_days",
]
class DeleteEtsyShippingProfileDestination(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/deleteListingShippingProfileDestination
"""
http_method = "DELETE"
resource_method = (
"shops/{shop_id}/shipping-profiles/{shipping_profile_id}/destinations/{shipping_profile_destination_id}"
)
required_params = [
"shop_id",
"shipping_profile_id",
"shipping_profile_destination_id",
] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/etsy/core/shipping_profile_destination.py | shipping_profile_destination.py |
from zs_utils.api.etsy.base_api import EtsyAPI
class GetEtsyProduct(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingProduct
"""
http_method = "GET"
resource_method = "listings/{listing_id}/inventory/products/{product_id}"
required_params = ["listing_id", "product_id"]
class GetEtsyOffering(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingOffering
"""
http_method = "GET"
resource_method = "listings/{listing_id}/products/{product_id}/offerings/{product_offering_id}"
required_params = ["listing_id", "product_id", "product_offering_id"]
class GetEtsyListingProductList(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingInventory
"""
http_method = "GET"
resource_method = "listings/{listing_id}/inventory"
required_params = ["listing_id"]
class UpdateEtsyListingInventory(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/updateListingInventory
"""
http_method = "PUT"
resource_method = "listings/{listing_id}/inventory"
required_params = [
"listing_id",
"products",
]
allowed_params = [
"price_on_property",
"quantity_on_property",
"sku_on_property",
]
class GetEtsyListingList(EtsyAPI):
"""
Endpoint to list Listings that belong to a Shop. Listings can be filtered using the 'state' param.
Docs:
https://www.etsy.com/openapi/developers#operation/getListings
"""
http_method = "GET"
resource_method = "shops/{shop_id}/listings"
required_params = ["shop_id"]
allowed_params = ["state", "limit", "offset", "sort_on", "sort_order"]
class GetEtsySingleListing(EtsyAPI):
"""
Docs:
https://www.etsy.com/developers/documentation/reference/listing#method_getlisting
"""
http_method = "GET"
resource_method = "listings/{listing_id}"
required_params = ["listing_id"]
class GetEtsyListingAttributeList(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingProperties
"""
http_method = "GET"
resource_method = "shops/{shop_id}/listings/{listing_id}/properties"
required_params = ["shop_id", "listing_id"]
class GetEtsyListingAttribute(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingProperty
"""
http_method = "GET"
resource_method = "shops/{shop_id}/listings/{listing_id}/properties/{property_id}"
required_params = ["shop_id", "listing_id", "property_id"]
class CreateOrUpdateEtsyListingAttribute(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/updateListingProperty
"""
http_method = "PUT"
resource_method = "shops/{shop_id}/listings/{listing_id}/properties/{property_id}"
required_params = [
"shop_id",
"listing_id",
"property_id",
"values",
]
allowed_params = [
"value_ids",
"scale_id",
]
class DeleteEtsyListingAttribute(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/deleteListingProperty
"""
http_method = "DELETE"
resource_method = "shops/{shop_id}/listings/{listing_id}/properties/{property_id}"
required_params = ["shop_id", "listing_id", "property_id"]
class DeleteEtsyListing(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/deleteListing
"""
http_method = "DELETE"
resource_method = "listings/{listing_id}"
required_params = ["listing_id"]
class GetEtsyOrderListings(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingsByShopReceipt
"""
http_method = "GET"
resource_method = "shops/{shop_id}/receipts/{receipt_id}/listings"
required_params = ["receipt_id", "shop_id"]
class GetEtsyShopSectionListings(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingsByShopSectionId
"""
http_method = "GET"
resource_method = "shops/{shop_id}/sections/{shop_section_id}/listings"
required_params = ["shop_id", "shop_section_id"]
allowed_params = ["limit", "offset", "sort_on", "sort_order"]
class CreateEtsySingleListing(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/createListing
"""
http_method = "POST"
resource_method = "shops/{shop_id}/listings"
required_params = [
"shop_id",
"quantity",
"title",
"description",
"price",
"who_made",
"when_made",
"taxonomy_id",
"shipping_profile_id",
]
allowed_params = [
"materials",
"shop_section_id",
"processing_min",
"processing_max",
"tags",
"recipient",
"occasion",
"styles",
"is_personalizable",
"personalization_is_required",
"personalization_char_count_max",
"personalization_instructions",
"production_partner_ids",
"image_ids",
"is_supply",
"is_customizable",
"is_taxable",
"item_length",
"item_width",
"item_height",
"item_dimensions_unit",
"item_weight",
"item_weight_unit",
"type",
]
class UpdateEtsySingleListing(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/updateListing
"""
http_method = "PUT"
resource_method = "shops/{shop_id}/listings/{listing_id}"
required_params = ["shop_id", "listing_id"]
allowed_params = [
"quantity",
"price",
"title",
"description",
"materials",
"should_auto_renew",
"shipping_profile_id",
"shop_section_id",
"is_taxable",
"taxonomy_id",
"tags",
"who_made",
"when_made",
"featured_rank",
"is_personalizable",
"personalization_is_required",
"personalization_char_count_max",
"personalization_instructions",
"state",
"is_supply",
"production_partner_ids",
"type",
"item_length",
"item_width",
"item_height",
"item_dimensions_unit",
"item_weight",
"item_weight_unit",
]
class DeleteListingFile(EtsyAPI):
"""
Docs: https://developers.etsy.com/documentation/reference/#operation/getListingsByShopSectionId
"""
http_method = "DELETE"
resource_method = "shops/{shop_id}/listings/{listing_id}/files/{listing_file_id}"
required_params = ["shop_id", "listing_id", "listing_file_id"]
class GetListingFile(EtsyAPI):
"""
Docs: https://developers.etsy.com/documentation/reference/#operation/getListingFile
"""
http_method = "GET"
resource_method = "shops/{shop_id}/listings/{listing_id}/files/{listing_file_id}"
required_params = ["shop_id", "listing_id", "listing_file_id"]
class GetAllListingFiles(EtsyAPI):
"""
Docs: https://developers.etsy.com/documentation/reference/#operation/getAllListingFiles
"""
http_method = "GET"
resource_method = "shops/{shop_id}/listings/{listing_id}/files"
required_params = ["shop_id", "listing_id"]
class UploadListingFile(EtsyAPI):
"""
Docs: https://developers.etsy.com/documentation/reference/#operation/uploadListingFile
"""
http_method = "POST"
resource_method = "shops/{shop_id}/listings/{listing_id}/files"
required_params = ["shop_id", "listing_id"]
allowed_params = [
"listing_file_id",
"file",
"name",
"rank",
]
@property
def headers(self) -> dict:
# При наличии файла будет автоматом подставлен multipart - что нам и нужно
headers = super().headers
headers.pop("Content-Type")
return headers | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/etsy/core/listing/listing.py | listing.py |
from zs_utils.api.etsy.base_api import EtsyAPI
class GetEtsyListingImageList(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingImages
"""
http_method = "GET"
resource_method = "shops/{shop_id}/listings/{listing_id}/images"
required_params = ["shop_id", "listing_id"]
class GetEtsyListingImage(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingImage
"""
http_method = "GET"
resource_method = "shops/{shop_id}/listings/{listing_id}/images/{listing_image_id}"
required_params = ["shop_id", "listing_id", "listing_image_id"]
class DeleteEtsyListingImage(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/deleteListingImage
"""
http_method = "DELETE"
resource_method = "shops/{shop_id}/listings/{listing_id}/images/{listing_image_id}"
required_params = ["shop_id", "listing_id", "listing_image_id"]
class UploadEtsyListingImage(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/uploadListingImage
"""
http_method = "POST"
resource_method = "shops/{shop_id}/listings/{listing_id}/images"
required_params = ["shop_id", "listing_id"]
allowed_params = [
"image",
"listing_image_id",
"rank",
"overwrite",
"is_watermarked",
]
@property
def headers(self) -> dict:
# При наличии файла будет автоматом подставлен multipart - что нам и нужно
headers = super().headers
headers.pop("Content-Type")
return headers
class GetVariationImages(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/getListingVariationImages
"""
http_method = "GET"
resource_method = "shops/{shop_id}/listings/{listing_id}/variation-images"
required_params = ["shop_id", "listing_id"]
class UpdateVariationImages(EtsyAPI):
"""
Docs:
https://www.etsy.com/openapi/developers#operation/updateVariationImages
"""
http_method = "POST"
resource_method = "shops/{shop_id}/listings/{listing_id}/variation-images"
required_params = ["shop_id", "listing_id", "variation_images"] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/etsy/core/listing/image.py | image.py |
from zs_utils.api.base_api import BaseAPI
from zs_utils.api.ebay.utils import custom_quote
__all__ = [
"EbayAPI",
]
class EbayAPI(BaseAPI):
production_api_url = "https://api.ebay.com/"
sandbox_api_url = "https://api.sandbox.ebay.com/"
params_to_quote = [
"sku",
"inventoryItemGroupKey",
"merchantLocationKey",
]
# TODO: валидация?
MAX_LIMIT = 100
MAX_OFFSET = 99
def __init__(self, access_token: str, marketplace_id: str = None, **kwargs):
super().__init__(**kwargs)
self.access_token = access_token
self.marketplace_id = marketplace_id
@property
def headers(self):
# DOCS: https://developer.ebay.com/api-docs/static/rest-request-components.html#marketpl
DOMAIN_TO_LOCALE = {
"EBAY_AT": "de-AT",
"EBAY_AU": "en-AU",
"EBAY_BE": "fr-BE",
"EBAY_CA": "en-CA",
"EBAY_CH": "de-CH",
"EBAY_DE": "de-DE",
"EBAY_ES": "es-ES",
"EBAY_FR": "fr-FR",
"EBAY_GB": "en-GB",
"EBAY_HK": "zh-HK",
"EBAY_IE": "en-IE",
"EBAY_IN": "en-GB",
"EBAY_IT": "it-IT",
"EBAY_MY": "en-MY",
"EBAY_NL": "nl-NL",
"EBAY_PH": "en-PH",
"EBAY_PL": "pl-PL",
"EBAY_TH": "th-TH",
"EBAY_TW": "zh-TW",
}
locale = DOMAIN_TO_LOCALE.get(self.marketplace_id)
if not locale:
locale = "en-US"
return {
"Authorization": f"Bearer {self.access_token}",
"Content-Language": locale,
"Content-Type": "application/json",
"Accept-Language": locale,
"Accept": "application/json",
"Accept-Charset": "utf-8",
"Accept-Encoding": "application/gzip",
"X-EBAY-C-MARKETPLACE-ID": self.marketplace_id,
}
def build_url(self, params: dict):
next_url = params.pop("next_url", None)
if next_url:
url = self.sandbox_api_url if self.is_sandbox else self.production_api_url
if next_url.startswith("/"):
url += next_url
else:
url = next_url
return url
else:
return super().build_url(params=params)
def get_path_params(self, params: dict):
path_params = super().get_path_params(params)
return {
param: custom_quote(value)
for param, value in path_params.items()
if value and (param in self.params_to_quote)
}
def get_clean_params(self, params: dict) -> dict:
clean_params = {
"next_url": params.get("next_url"),
"payload": params.get("payload"),
}
if not params.get("next_url"):
clean_params.update(super().get_clean_params(params))
for param in self.params_to_quote:
if clean_params.get(param):
clean_params[param] = custom_quote(clean_params[param])
return clean_params
def get_payload(self, params: dict):
return params.pop("payload", None) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/base_api/new_api.py | new_api.py |
from abc import abstractmethod
from ebaysdk.exception import ConnectionError as BaseEbayTradingAPIError
from ebaysdk.trading import Connection as BaseEbayTradingAPI
from ebaysdk.response import Response as EbaySDKResponse
from zs_utils.api.base_api import BaseAPI
from zs_utils.api.ebay.data.marketplace.marketplace_to_site import (
EbayDomainCodeToSiteID,
)
__all__ = [
"EbayTradingAPI",
]
class EbayTradingAPI(BaseAPI):
def __init__(
self,
access_token: str,
client_id: str,
client_secret: str,
dev_id: str,
site_id: str = None,
domain_code: str = None,
debug: bool = False,
**kwargs,
):
super().__init__(**kwargs)
self.access_token = access_token
self.client_id = client_id
self.client_secret = client_secret
self.dev_id = dev_id
self.site_id = site_id
self.domain_code = domain_code
self.debug = debug
def validate_attrs(self) -> None:
pass
@property
@abstractmethod
def method_name(self) -> str:
pass
@abstractmethod
def get_params(self, **kwargs) -> dict:
pass
def _clean_data(self, data: dict) -> dict:
cleaned_data = {}
for key, value in data.items():
if value or type(value) in [bool, int]:
if isinstance(value, dict):
cleaned_data.update({key: self._clean_data(value)})
else:
cleaned_data.update({key: value})
return cleaned_data
def get_site_id(self, site_id: str = None, domain_code: str = None) -> str:
if site_id:
if site_id not in EbayDomainCodeToSiteID.values():
raise BaseEbayTradingAPIError(msg=f"Неизвестный 'site_id'={site_id}")
elif domain_code:
if domain_code not in EbayDomainCodeToSiteID.keys():
raise BaseEbayTradingAPIError(msg=f"Маркетплейс '{domain_code}' не поддерживается Trading API.")
else:
site_id = EbayDomainCodeToSiteID[domain_code]
else:
site_id = EbayDomainCodeToSiteID["default"]
return site_id
def make_request(self, **kwargs) -> EbaySDKResponse:
params = self.get_params(**kwargs)
cleaned_params = self._clean_data(params)
api = BaseEbayTradingAPI(
iaf_token=self.access_token,
appid=self.client_id,
devid=self.dev_id,
certid=self.client_secret,
siteid=self.get_site_id(site_id=self.site_id, domain_code=self.domain_code),
config_file=None,
debug=self.debug,
)
return api.execute(
verb=self.method_name,
data=cleaned_params,
) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/base_api/trading_api.py | trading_api.py |
import base64
import simplejson
import logging
import urllib
import requests
from zs_utils.exceptions import CustomException
from django.utils.translation import gettext as _
from .model import environment, oAuth_token
class EbayOAuthClientError(CustomException):
pass
class EbayOAuthClient:
def __init__(
self,
client_id: str,
client_secret: str,
redirect_uri: str,
is_sandbox: bool,
user_scopes: list = None,
app_scopes: list = None,
logger=None,
):
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
if is_sandbox:
self.env_type = environment.SANDBOX
else:
self.env_type = environment.PRODUCTION
self.user_scopes = user_scopes
self.app_scopes = app_scopes
self.headers = self._generate_request_headers()
self.logger = logger or logging.getLogger(__name__)
def _generate_request_headers(self) -> dict:
b64_string = f"{self.client_id}:{self.client_secret}".encode()
b64_encoded_credential = base64.b64encode(b64_string).decode("utf-8")
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": f"Basic {b64_encoded_credential}",
}
return headers
def generate_user_authorization_url(self, state: str = None) -> str:
param = {
"client_id": self.client_id,
"redirect_uri": self.redirect_uri,
"response_type": "code",
"prompt": "login",
"scope": " ".join(self.user_scopes),
}
if state is not None:
param.update({"state": state})
query = urllib.parse.urlencode(param)
return f"{self.env_type.web_endpoint}?{query}"
def _get_token(self, data: dict) -> oAuth_token:
response = requests.post(self.env_type.api_endpoint, data=data, headers=self.headers)
content = simplejson.loads(response.content)
status = response.status_code
if status != requests.codes.ok:
raise EbayOAuthClientError(
message=_("Не удалось получить токен: {error}").format(error=content["error_description"])
)
return oAuth_token(**content)
def get_application_access_token(self) -> oAuth_token:
body = {
"grant_type": "client_credentials",
"redirect_uri": self.redirect_uri,
"scope": " ".join(self.app_scopes),
}
return self._get_token(data=body)
def exchange_code_for_access_token(self, code: str) -> oAuth_token:
body = {
"grant_type": "authorization_code",
"redirect_uri": self.redirect_uri,
"code": code,
}
return self._get_token(data=body)
def get_user_access_token(self, refresh_token: str) -> oAuth_token:
body = {
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"scope": " ".join(self.user_scopes),
}
return self._get_token(data=body) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/oauth/oauth_client.py | oauth_client.py |
# from pysftp import CnOpts, Connection
# cnopts = CnOpts()
# cnopts.hostkeys = None
# credentials = {
# "host": "mip.ebay.com",
# "port": 22,
# "username": "zone-smart",
# "password": "v^1.1#i^1#r^1#I^3#f^0#p^3#t^Ul4xMF82OjQ5REY2QzJDQjM2RTVERDE5MDIyRTAwNDU3NUQ3MzVBXzNfMSNFXjI2MA==",
# }
# mip_dirs = [
# "availability",
# "deleteInventory",
# "distribution",
# "inventory",
# "location",
# "order",
# "orderfulfillment",
# "product",
# "reports",
# ]
# parser = argparse.ArgumentParser(description="Получение результатов загрузки eBay feed")
# class StoreNameValuePair(argparse.Action):
# def __call__(self, parser, namespace, values, option_string=None):
# n, v = values.split("=")
# setattr(namespace, n, v)
# parser.add_argument("file_name", action=StoreNameValuePair, help="Имя файла")
# parser.add_argument(
# "localpath",
# action=StoreNameValuePair,
# help="Путь на локальной машине для загруженного файла",
# )
# parser.add_argument(
# "mip_dir",
# action=StoreNameValuePair,
# help="Папка на сервере mip.ebay.com, в которую был загружен feed-файл",
# )
# args = parser.parse_args()
# file_name = args.file_name
# print("Имя ранее загруженного файла:", file_name)
# localpath = os.path.join(os.path.dirname(__file__), args.localpath, file_name)
# localpath_dir = os.path.dirname(localpath)
# print("Результаты сохранятся в файл:", localpath)
# if not os.path.isdir(localpath_dir):
# raise AttributeError(f"Указанная папка {localpath_dir} не существует на локальной машине")
# mip_dir = args.mip_dir
# print("Папка для поиска результатов в системе eBay:", mip_dir)
# if mip_dir not in mip_dirs:
# raise AttributeError(
# f"Недопустимая папка для поиска результатов загрузки: {mip_dir}\n" f"Допустимые папки: {mip_dirs}"
# )
# def callback(ready, total):
# print(f"File was {'un' if ready!=total else ''}successfully downloaded:")
# print(f"{ready} of {total} bytes downloaded")
# def get_similar(filename, dirname):
# print("Поиск файлов в", dirname)
# print("Содержимое папки:", sftp.listdir(dirname))
# files = [
# os.path.join(dirname, file)
# for file in sftp.listdir(dirname)
# if (os.path.splitext(filename)[0] in file) and file.endswith(".csv")
# ]
# return files
# def get_last_modified(files):
# dt_objs = []
# for file in files:
# dt_str = "-".join(os.path.basename(file).split("-")[1:7])
# dt_obj = time.strptime(dt_str, "%b-%d-%Y-%H-%M-%S")
# dt_objs.append((dt_obj, file))
# if dt_objs:
# return max(dt_objs, key=lambda x: x[0])[1]
# with Connection(**credentials, cnopts=cnopts) as sftp:
# root_dir = os.path.join("store", mip_dir)
# sftp.chdir(root_dir)
# processed_files = []
# for date_dir in sftp.listdir("output"):
# processed_files += get_similar(file_name, os.path.join("output", date_dir))
# unprocessed_files = []
# if "inprogress" in sftp.listdir(""):
# # возможно папка тоже содержит вложенные папки по датам
# unprocessed_files = get_similar(file_name, "inprogress")
# found_files = processed_files + unprocessed_files
# print("Все найденные файлы:", found_files)
# last_modified = get_last_modified(found_files)
# print("Результаты последней загрузки:", last_modified)
# if "output" in last_modified:
# remotepath = last_modified
# else:
# print(f"Файл {last_modified} находится в обработке системой eBay, результаты пока недоступны.")
# remotepath = get_last_modified(filter(lambda file_path: "output" in file_path, found_files))
# if remotepath:
# print(f"Загружен последний обработанный системой eBay файл с тем же именем {remotepath}.")
# else:
# print(f"Обработанных системой eBay файлов с тем же именем {file_name} не найдено.")
# if remotepath:
# sftp.get(remotepath=remotepath, localpath=localpath, callback=callback)
# print(f"Файл {remotepath} загружен в {localpath}.")
# else:
# print("Файл не был загружен.") | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/mip/sftp_get.py | sftp_get.py |
from zs_utils.api.ebay.base_api import EbayAPI
class CreateInventoryLocation(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/location/methods/createInventoryLocation
"""
http_method = "POST"
resource_method = "sell/inventory/v1/location/{merchantLocationKey}"
required_params = ["merchantLocationKey"]
class DeleteInventoryLocation(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/location/methods/deleteInventoryLocation
"""
http_method = "DELETE"
resource_method = "sell/inventory/v1/location/{merchantLocationKey}"
required_params = ["merchantLocationKey"]
class DisableInventoryLocation(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/location/methods/disableInventoryLocation
"""
http_method = "POST"
resource_method = "sell/inventory/v1/location/{merchantLocationKey}/disable"
required_params = ["merchantLocationKey"]
class EnableInventoryLocation(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/location/methods/enableInventoryLocation
"""
http_method = "POST"
resource_method = "sell/inventory/v1/location/{merchantLocationKey}/enable"
required_params = ["merchantLocationKey"]
class GetInventoryLocation(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/location/methods/getInventoryLocation
"""
http_method = "GET"
resource_method = "sell/inventory/v1/location/{merchantLocationKey}"
required_params = ["merchantLocationKey"]
class GetInventoryLocations(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/location/methods/getInventoryLocations
"""
http_method = "GET"
resource_method = "sell/inventory/v1/location"
allowed_params = ["offset", "limit"]
class UpdateInventoryLocation(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/location/methods/updateInventoryLocation
"""
http_method = "POST"
resource_method = "sell/inventory/v1/location/{merchantLocationKey}/update_location_details"
required_params = ["merchantLocationKey"] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/core/sell/inventory/location.py | location.py |
from zs_utils.api.ebay.base_api import EbayAPI
class CreateOffer(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/createOffer
"""
http_method = "POST"
resource_method = "sell/inventory/v1/offer"
class UpdateOffer(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/updateOffer
"""
http_method = "PUT"
resource_method = "sell/inventory/v1/offer/{offerId}"
required_params = ["offerId"]
class GetOffers(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/getOffers
"""
http_method = "GET"
resource_method = "sell/inventory/v1/offer"
required_params = ["sku"]
allowed_params = ["marketplace_id", "offset", "limit"]
class GetOffer(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/getOffer
"""
http_method = "GET"
resource_method = "sell/inventory/v1/offer/{offerId}"
required_params = ["offerId"]
class DeleteOffer(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/deleteOffer
"""
http_method = "DELETE"
resource_method = "sell/inventory/v1/offer/{offerId}"
required_params = ["offerId"]
class PublishOffer(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/publishOffer
"""
http_method = "POST"
resource_method = "sell/inventory/v1/offer/{offerId}/publish"
required_params = ["offerId"]
class WithdrawOffer(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/withdrawOffer
"""
http_method = "POST"
resource_method = "sell/inventory/v1/offer/{offerId}/withdraw"
required_params = ["offerId"]
class GetListingFees(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/getListingFees
"""
http_method = "POST"
resource_method = "sell/inventory/v1/offer/get_listing_fees"
class BulkCreateOffer(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/bulkCreateOffer
"""
http_method = "POST"
resource_method = "sell/inventory/v1/bulk_create_offer"
class BulkPublishOffer(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/offer/methods/bulkPublishOffer
"""
http_method = "POST"
resource_method = "sell/inventory/v1/bulk_publish_offer" | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/core/sell/inventory/offer.py | offer.py |
from zs_utils.api.ebay.base_api import EbayAPI
# SINGLE ITEM API
class CreateOrReplaceInventoryItem(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/methods/createOrReplaceInventoryItem
"""
http_method = "PUT"
resource_method = "sell/inventory/v1/inventory_item/{sku}"
required_params = ["sku"]
class GetInventoryItem(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/methods/getInventoryItem
"""
http_method = "GET"
resource_method = "sell/inventory/v1/inventory_item/{sku}"
required_params = ["sku"]
class GetInventoryItems(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/methods/getInventoryItems
"""
http_method = "GET"
resource_method = "sell/inventory/v1/inventory_item"
allowed_params = ["offset", "limit"]
class DeleteInventoryItem(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/methods/deleteInventoryItem
"""
http_method = "DELETE"
resource_method = "sell/inventory/v1/inventory_item/{sku}"
required_params = ["sku"]
# PRODUCT COMPATIBILITY API
class ProductCompatibilityAPI(EbayAPI):
resource_method = "sell/inventory/v1/inventory_item/{sku}/product_compatibility"
required_params = ["sku"]
class CreateOrReplaceProductCompatibility(ProductCompatibilityAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/product_compatibility/methods/createOrReplaceProductCompatibility
""" # noqa
http_method = "PUT"
class GetProductCompatibility(ProductCompatibilityAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/product_compatibility/methods/getProductCompatibility
""" # noqa
http_method = "GET"
class DeleteProductCompatibility(ProductCompatibilityAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/product_compatibility/methods/deleteProductCompatibility
""" # noqa
http_method = "DELETE"
# BULK API
class BulkUpdatePriceQuantity(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/methods/bulkUpdatePriceQuantity
"""
http_method = "POST"
resource_method = "sell/inventory/v1/bulk_update_price_quantity"
class BulkCreateOrReplaceInventoryItem(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/methods/bulkCreateOrReplaceInventoryItem
""" # noqa
http_method = "POST"
resource_method = "sell/inventory/v1/bulk_create_or_replace_inventory_item"
class BulkGetInventoryItem(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/inventory/resources/inventory_item/methods/bulkGetInventoryItem
"""
http_method = "POST"
resource_method = "sell/inventory/v1/bulk_get_inventory_item" | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/core/sell/inventory/item.py | item.py |
import datetime
from dateutil.parser import parse
from zs_utils.api.ebay.base_api import EbayAPI
class PaymentDisputeAPI(EbayAPI):
production_api_url = "https://apiz.ebay.com/"
sandbox_api_url = "https://apiz.sandbox.ebay.com/"
class GetPaymentDispute(PaymentDisputeAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/fulfillment/resources/payment_dispute/methods/getPaymentDispute
"""
http_method = "GET"
resource_method = "sell/fulfillment/v1/payment_dispute/{payment_dispute_id}"
required_params = ["payment_dispute_id"]
class FetchEvidenceContent(PaymentDisputeAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/fulfillment/resources/payment_dispute/methods/fetchEvidenceContent
"""
http_method = "GET"
resource_method = "sell/fulfillment/v1/payment_dispute/{payment_dispute_id}/fetch_evidence_content"
required_params = ["payment_dispute_id", "evidence_id", "file_id"]
class GetActivities(PaymentDisputeAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/fulfillment/resources/payment_dispute/methods/getActivities
"""
http_method = "GET"
resource_method = "sell/fulfillment/v1/payment_dispute/{payment_dispute_id}/activity"
required_params = ["payment_dispute_id"]
class GetPaymentDisputeSummaries(PaymentDisputeAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/fulfillment/resources/payment_dispute/methods/getPaymentDisputeSummaries
"""
http_method = "GET"
resource_method = "sell/fulfillment/v1/payment_dispute/payment_dispute_summary"
allowed_params = [
"order_id",
"buyer_username",
"open_date_from",
"open_date_to",
"payment_dispute_status",
"limit",
"offset",
]
MAX_LIMIT = 200
def get_clean_params(self, params: dict) -> dict:
clean_params = super().get_clean_params(params)
if clean_params.get("open_date_to"):
clean_params["open_date_to"] = self.clean_open_date_to(value=clean_params["open_date_to"])
if clean_params.get("open_date_from"):
clean_params["open_date_from"] = self.clean_open_date_from(value=clean_params["open_date_from"])
return clean_params
def clean_open_date_to(self, value):
value = parse(value)
now = datetime.datetime.now()
if now < value:
value = now
elif (now - value).days >= 18 * 30:
raise self.exception_class(
'Разница между датой "open_date_to" и настоящим моментом не должна превышать 18 месяцев.'
)
return value
def clean_open_date_from(self, value):
value = parse(value)
now = datetime.datetime.now()
if now <= value:
raise self.exception_class('Дата "open_date_from" должна быть более ранней, чем сегодняшняя дата.')
elif (now - value).days >= 18 * 30:
raise self.exception_class(
'Разница между датой "open_date_from" и настоящим моментом не должна превышать 18 месяцев.'
)
return value | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/core/sell/fulfillment/payment_dispute.py | payment_dispute.py |
from zs_utils.api.ebay.base_api import EbayAPI
class GetOrder(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/fulfillment/resources/order/methods/getOrder
"""
http_method = "GET"
resource_method = "sell/fulfillment/v1/order/{orderId}"
required_params = ["orderId"]
class GetOrders(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/fulfillment/resources/order/methods/getOrders
"""
http_method = "GET"
resource_method = "sell/fulfillment/v1/order"
allowed_params = ["orderIds", "filter", "offset", "limit"]
MAX_OFFSET = 999
MAX_LIMIT = 1000
def get_clean_params(self, params: dict) -> dict:
clean_params = super().get_clean_params(params)
if clean_params.get("orderIds"):
clean_params["orderIds"] = self.clean_orderIds(orderIds_string=clean_params["orderIds"])
if clean_params.get("filter"):
clean_params["filter"] = self.clean_filter(filter_string=clean_params["filter"])
return clean_params
def clean_orderIds(self, orderIds_string):
message = ""
order_ids = [order_id.strip() for order_id in orderIds_string.split(",")]
if not (1 <= len(order_ids) <= 50):
message = f"Количество ID заказов должно лежать в диапазоне [1:50]. Передано ID заказов: {len(order_ids)}"
elif len(order_ids) != len(set(order_ids)):
message = f"Среди ID заказов есть повторяющиеся.\nСписок ID: {orderIds_string}"
else:
for order_id in order_ids:
for part in order_id.split("-"):
if not part.isdigit():
message += f"Недопустимый ID заказа: {order_id}.\n"
if message:
raise self.exception_class(message)
return ",".join(order_ids)
def clean_filter(self, filter_string):
# Docs: https://developer.ebay.com/api-docs/sell/fulfillment/resources/order/methods/getOrders#h2-input
def _percent_encode(string):
string = string.replace("[", "%5B")
string = string.replace("]", "%5D")
string = string.replace("{", "%7B")
string = string.replace("}", "%7D")
string = string.replace("|", "%7C")
return string
allowed_filters = ["creationdate", "lastmodifieddate", "orderfulfillmentstatus"]
allowed_orderfulfillmentstatuses = [
"{NOT_STARTED|IN_PROGRESS}",
"{FULFILLED|IN_PROGRESS}",
]
for pair in filter_string.split(","):
key, value = pair.split(":")[0], ":".join(pair.split(":")[1:])
if key == "orderfulfillmentstatus":
if value.strip() not in allowed_orderfulfillmentstatuses:
self.exception_class(
f"Недопустимое значение фильтра {key}: {value}. Допустимые значения: {allowed_orderfulfillmentstatuses}.\n"
)
elif key in ["creationdate", "lastmodifieddate"]:
pass
# TODO: проверить на соответствие шаблону YYYY-MM-DDThh:mm:ss.000Z
# if not is_datetime(...):
# message += f"Недопустимое значение фильтра {key}: {value}.\n"
# message += f"Значение должно соответствовать шаблону: [<datetime>..<datetime or empty string>]"
else:
self.exception_class(f"Недопустимый фильтр: {key}. Допустимые фильтры: {allowed_filters}.\n")
return ",".join([_percent_encode(filter_pair.strip()) for filter_pair in filter_string.split(",")])
class IssueRefund(EbayAPI):
"""
Docs:
https://developer.ebay.com/api-docs/sell/fulfillment/resources/order/methods/issueRefund
"""
http_method = "POST"
resource_method = "sell/fulfillment/v1/order/{orderId}/issue_refund"
required_params = ["orderId"] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/core/sell/fulfillment/order.py | order.py |
from zs_utils.api.ebay.base_api import EbayAPI
class TaxonomyAPI(EbayAPI):
@property
def headers(self):
headers = {
"Authorization": f"Bearer {self.access_token}",
"Accept": "application/json",
"Content-Type": "application/json",
"Accept-Encoding": "application/gzip",
}
return headers
class GetDefaultCategoryTreeId(TaxonomyAPI):
"""
Docs:
https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getDefaultCategoryTreeId
"""
http_method = "GET"
resource_method = "commerce/taxonomy/v1/get_default_category_tree_id"
required_params = ["marketplace_id"]
class GetCategoryTree(TaxonomyAPI):
"""
Docs:
https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getCategoryTree
"""
http_method = "GET"
resource_method = "commerce/taxonomy/v1/category_tree/{category_tree_id}"
required_params = ["category_tree_id"]
class GetCategorySubtree(TaxonomyAPI):
"""
Docs:
https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getCategorySubtree
"""
http_method = "GET"
resource_method = "commerce/taxonomy/v1/category_tree/{category_tree_id}/get_category_subtree"
required_params = ["category_tree_id", "category_id"]
class GetCategorySuggestions(TaxonomyAPI):
"""
Docs:
https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getCategorySuggestions
"""
http_method = "GET"
resource_method = "commerce/taxonomy/v1/category_tree/{category_tree_id}/get_category_suggestions"
required_params = ["category_tree_id", "q"]
class GetItemAspectsForCategory(TaxonomyAPI):
"""
Docs:
https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getItemAspectsForCategory
"""
http_method = "GET"
resource_method = "commerce/taxonomy/v1/category_tree/{category_tree_id}/get_item_aspects_for_category"
required_params = ["category_tree_id", "category_id"]
class GetCompatibilityProperties(TaxonomyAPI):
"""
Docs:
https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getCompatibilityProperties
"""
http_method = "GET"
resource_method = "commerce/taxonomy/v1/category_tree/{category_tree_id}/get_compatibility_properties"
required_params = ["category_tree_id", "category_id"]
class GetCompatibilityPropertyValues(TaxonomyAPI):
"""
Docs:
https://developer.ebay.com/api-docs/commerce/taxonomy/resources/category_tree/methods/getCompatibilityPropertyValues
"""
http_method = "GET"
resource_method = "commerce/taxonomy/v1/category_tree/{category_tree_id}/get_compatibility_property_values"
required_params = ["category_tree_id", "compatibility_property", "category_id"]
allowed_params = ["filter"] | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/core/commerce/taxonomy.py | taxonomy.py |
from datetime import datetime
from zs_utils.api.ebay.base_api import EbayTradingAPI
__all__ = [
"GetEbayAccountBillingInfo",
"GetEbaySellingInfo",
"GetEbaySellingSummary",
]
class GetEbayAccountBillingInfo(EbayTradingAPI):
"""
Docs:
https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/GetAccount.html
"""
method_name = "GetAccount"
def get_params(
self,
account_history_selection: str,
begin_date: datetime = None, # 4 months ago -- ebay limit
end_date: datetime = None,
**kwargs,
):
assert account_history_selection in [
"BetweenSpecifiedDates",
"LastInvoice",
], "Недопустимое значение 'account_history_selection'."
if account_history_selection == "BetweenSpecifiedDates":
assert begin_date and end_date, "Необходимо задать временной диапазон ('begin_date' и 'end_date')."
return {
"AccountHistorySelection": account_history_selection,
# "AccountEntrySortType": "AccountEntryCreatedTimeDescending",
"BeginDate": begin_date,
"EndDate": end_date,
"ExcludeBalance": False,
"ExcludeSummary": False,
}
class GetEbaySellingInfo(EbayTradingAPI):
"""
Docs:
https://developer.ebay.com/devzone/xml/docs/reference/ebay/GetMyeBaySelling.html
"""
method_name = "GetMyeBaySelling"
containers = [
"ActiveList",
"DeletedFromSoldList",
"DeletedFromUnsoldList",
"ScheduledList",
"SoldList",
"UnsoldList",
"SellingSummary",
]
def get_params(self, **kwargs):
return {container: {"Include": kwargs.get(container, False)} for container in self.containers}
class GetEbaySellingSummary(GetEbaySellingInfo):
def get_params(self, **kwargs):
kwargs.update({container: False for container in self.containers})
kwargs["SellingSummary"] = True
return super().get_params(**kwargs) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/core/trading/billing.py | billing.py |
from zs_utils.api.ebay.base_api import EbayTradingAPI
from .category import GetEbayCategoryFeatures
from .messages import AbstractSendMessage
__all__ = [
"GetCategoryBestOfferFeatures",
"GetListingBestOffers",
"RespondToListingBestOffer",
"SendBestOfferMessage",
]
class GetCategoryBestOfferFeatures(GetEbayCategoryFeatures):
def get_params(self, category_id: int, **kwargs):
kwargs["feature_ids"] = [
"BestOfferEnabled",
"BestOfferAutoDeclineEnabled",
"BestOfferAutoAcceptEnabled",
]
return super().get_params(category_id=category_id, **kwargs)
class GetListingBestOffers(EbayTradingAPI):
"""
Docs:
https://developer.ebay.com/DevZone/XML/docs/Reference/eBay/GetBestOffers.html
"""
method_name = "GetBestOffers"
def get_params(
self,
best_offer_id: int = None,
item_id: int = None,
active_only: bool = True,
**kwargs,
):
if active_only:
best_offer_status = "Active"
else:
best_offer_status = "All"
return {
"BestOfferID": best_offer_id,
"BestOfferStatus": best_offer_status,
"ItemID": item_id,
"DetailLevel": "ReturnAll",
}
class RespondToListingBestOffer(EbayTradingAPI):
"""
Docs:
https://developer.ebay.com/devzone/xml/docs/reference/ebay/RespondToBestOffer.html
"""
method_name = "RespondToBestOffer"
def get_params(
self,
action: str,
best_offer_id: int,
item_id: int,
counter_offer_price: float = None,
counter_offer_quantity: int = None,
seller_response: str = None,
**kwargs,
):
if not (action in ["Accept", "Counter", "Decline"]):
raise AttributeError('Недопустимое значение параметра "action".')
if best_offer_id and (not item_id):
raise ValueError("Если задан 'best_offer_id', то должен быть задан 'item_id'.")
return {
"Action": action,
"BestOfferID": best_offer_id,
"ItemID": item_id,
"CounterOfferPrice": counter_offer_price,
"currencyID": "USD",
"CounterOfferQuantity": counter_offer_quantity,
"SellerResponse": seller_response,
}
class SendBestOfferMessage(AbstractSendMessage):
"""
AddMemberMessagesAAQToBidder:
https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/AddMemberMessagesAAQToBidder.html
HINT: item needs to be tested
"""
method_name = "AddMemberMessagesAAQToBidder"
def get_params(self, **kwargs):
params = super().get_params(**kwargs)
params.update({"CorrelationID": "1"})
return params | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/core/trading/best_offer.py | best_offer.py |
from datetime import datetime, timedelta
from zs_utils.api.ebay.base_api import EbayTradingAPI
from zs_utils.api.ebay.data.enums import PlatformNotificationEventTypeEnum
__all__ = [
"GetNotificationSettings",
"GetAppNotificationSettings",
"GetUserNotificationSettings",
"GetNotificationsUsage",
"SetNotificationSettings",
"ReviseNotifications",
"SubscribeNotification",
"UnSubscribeNotification",
]
class GetNotificationSettings(EbayTradingAPI):
"""
Docs:
https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/GetNotificationPreferences.html
"""
method_name = "GetNotificationPreferences"
def get_params(self, preference_level: str, **kwargs):
assert preference_level in [
"Application",
"Event",
"User",
"UserData",
], f'Недопустимое значение "preference_level": {preference_level}'
return {
"PreferenceLevel": preference_level,
"OutputSelector": None,
}
# DEPRECATED
# def make_request(self, **kwargs):
# is_success, message, objects = super().make_request(**kwargs)
# if objects.get("errors", []):
# if objects["errors"][0].get("ErrorCode", None) == "12209":
# is_success = True
# objects["results"] = []
# return is_success, message, objects
class GetAppNotificationSettings(GetNotificationSettings):
def get_params(self, **kwargs):
kwargs["preference_level"] = "Application"
return super().get_params(**kwargs)
class GetUserNotificationSettings(GetNotificationSettings):
def get_params(self, **kwargs):
kwargs["preference_level"] = "User"
return super().get_params(**kwargs)
class GetNotificationsUsage(EbayTradingAPI):
"""
Docs:
https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/GetNotificationsUsage.html
FIX: timeout problem
"""
method_name = "GetNotificationsUsage"
def get_params(
self,
remote_id: str = None,
start_time: str = None,
end_time: str = None,
hours_ago: int = None,
**kwargs,
):
if hours_ago:
start_time = (datetime.now() - timedelta(hours=hours_ago)).isoformat()
end_time = datetime.now().isoformat()
elif not end_time:
end_time = datetime.now().isoformat()
return {
"ItemID": remote_id,
"StartTime": start_time,
"EndTime": end_time,
}
class SetNotificationSettings(EbayTradingAPI):
"""
Docs:
https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/SetNotificationPreferences.html
"""
method_name = "SetNotificationPreferences"
def get_params(
self,
alert_enable: bool = None,
app_enable: bool = None,
alert_email: str = None,
app_url: str = None,
delivery_urls: dict = None,
subscriptions: list = None,
user_identifier: str = None,
**kwargs,
):
params = {
"ApplicationDeliveryPreferences": {
"AlertEmail": alert_email,
"ApplicationURL": app_url,
"DeviceType": "Platform",
},
"UserDeliveryPreferenceArray": subscriptions,
}
if app_enable is not None:
params["ApplicationDeliveryPreferences"]["ApplicationEnable"] = "Enable" if app_enable else "Disable"
if alert_enable is not None:
params["ApplicationDeliveryPreferences"]["AlertEnable"] = "Enable" if alert_enable else "Disable"
if user_identifier:
params["UserData"] = {
"ExternalUserData": user_identifier,
}
if delivery_urls:
params["ApplicationDeliveryPreferences"].update(
{
"DeliveryURLDetails": [
{
"DeliveryURL": url,
"DeliveryURLName": url,
"Status": "Enable" if enable else "Disable",
}
for url, enable in delivery_urls.items()
]
}
)
params["DeliveryURLName"] = ",".join(list(delivery_urls.keys()))
return params
class ReviseNotifications(SetNotificationSettings):
def get_params(self, notifications: list, enable: bool, **kwargs):
for notification in notifications:
assert (
notification in PlatformNotificationEventTypeEnum
), f'Недопустимое значение "notification": {notification}'
kwargs["subscriptions"] = [
{
"NotificationEnable": [
{
"EventType": notification,
"EventEnable": "Enable" if enable else "Disable",
}
for notification in notifications
]
}
]
return super().get_params(**kwargs)
class SubscribeNotification(ReviseNotifications):
def get_params(self, **kwargs):
kwargs["enable"] = True
return super().get_params(**kwargs)
class UnSubscribeNotification(ReviseNotifications):
def get_params(self, **kwargs):
kwargs["enable"] = False
return super().get_params(**kwargs) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/core/trading/notifications.py | notifications.py |
import datetime
from zs_utils.api.ebay.base_api import EbayTradingAPI
__all__ = [
"GetMessagesInfo",
"GetMessageSummary",
"GetMessageHeaderList",
"GetMessageList",
"SendMessage",
"GetMemberMessageList",
"AnswerOrderMessage",
"MarkMessageRead",
"MarkMessageUnread",
"DeleteMessageList",
]
class GetMessagesInfo(EbayTradingAPI):
"""
GetMyMessages:
https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/GetMyMessages.html
"""
method_name = "GetMyMessages"
def get_params(
self,
detail_level: str,
folder_id: int = None,
message_ids: list = [],
days_ago: int = None,
**kwargs,
):
assert detail_level in ["ReturnHeaders", "ReturnMessages", "ReturnSummary"]
assert folder_id in [None, "0", "1", "2", 0, 1, 2]
if message_ids:
assert len(message_ids) <= 10, 'Размер "message_ids" не должен превышать 10.'
folder_id = None
days_ago = None
elif detail_level == "ReturnMessages":
raise AttributeError('Необходимо задать "message_ids".')
if days_ago:
EndTime = datetime.datetime.now() + datetime.timedelta(minutes=1)
StartTime = EndTime - datetime.timedelta(days=int(days_ago))
else:
StartTime = None
EndTime = None
return {
"DetailLevel": detail_level,
"FolderID": folder_id,
"MessageIDs": {"MessageID": message_ids},
"EndTime": EndTime,
"StartTime": StartTime,
}
class GetMessageSummary(GetMessagesInfo):
def get_params(self, **kwargs):
kwargs["detail_level"] = "ReturnSummary"
kwargs["folder_id"] = None
kwargs["message_ids"] = None
return super().get_params(**kwargs)
class GetMessageHeaderList(GetMessagesInfo):
def get_params(self, full_messages=False, **kwargs):
kwargs["detail_level"] = "ReturnHeaders"
return super().get_params(**kwargs)
class GetMessageList(GetMessagesInfo):
def get_params(self, **kwargs):
kwargs["detail_level"] = "ReturnMessages"
return super().get_params(**kwargs)
class AbstractSendMessage(EbayTradingAPI):
"""
Abstract class.
"""
def get_params(
self,
message_body: str,
parent_message_id: str,
message_media_url: str = None,
item_id: str = None,
recipient_id: str = None,
email_copy_to_sender: bool = False,
**kwargs,
):
params = {
"MemberMessage": {
"Body": message_body,
"EmailCopyToSender": email_copy_to_sender,
"ParentMessageID": parent_message_id,
"RecipientID": recipient_id,
},
"ItemID": item_id,
}
if message_media_url:
params["MemberMessage"]["MessageMedia"] = {
"MediaName": "Attached media",
"MediaURL": message_media_url,
}
return params
class SendMessage(AbstractSendMessage):
"""
AddMemberMessageRTQ:
https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/AddMemberMessageRTQ.html
"""
method_name = "AddMemberMessageRTQ"
def get_params(self, display_to_public=False, **kwargs):
if not kwargs.get("item_id", None):
display_to_public = False
if not kwargs.get("recipient_id", None):
raise AttributeError('Необходимо задать "recipient_id" или "item_id"')
params = super().get_params(**kwargs)
params["MemberMessage"].update({"DisplayToPublic": display_to_public})
return params
class GetMemberMessageList(EbayTradingAPI):
"""
GetMemberMessages:
https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/GetMemberMessages.html
"""
method_name = "GetMemberMessages"
def get_params(
self,
message_type="All",
message_status=None,
item_id=None,
sender_id=None,
days_ago: int = None,
**kwargs,
):
if message_type not in ["All", "AskSellerQuestion"]:
raise AttributeError('Недопустимое значение параметра "message_type"')
params = {"MailMessageType": message_type}
if message_status:
if not (message_status in ["Answered", "Unanswered"]):
raise AttributeError('Недопустимое значение параметра "message_status"')
params.update({"MessageStatus": message_status})
if item_id:
params.update({"ItemID": item_id})
elif sender_id:
params.update({"SenderID": sender_id})
else:
end_creation_time = datetime.datetime.now()
start_creation_time = end_creation_time - datetime.timedelta(days=days_ago)
params.update(
{
"EndCreationTime": end_creation_time,
"StartCreationTime": start_creation_time,
}
)
return params
class AnswerOrderMessage(AbstractSendMessage):
"""
AddMemberMessageAAQToPartner:
https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/AddMemberMessageAAQToPartner.html
HINT: item needs to be a part of an offer
"""
method_name = "AddMemberMessageAAQToPartner"
question_type_enum = [
"CustomizedSubject",
"General",
"MultipleItemShipping",
"None",
"Payment",
"Shipping",
]
def get_params(self, item_id, recipient_id, subject, question_type="None", **kwargs):
if not (question_type in self.question_type_enum):
raise AttributeError('Недопустимое значение параметра "question_type"')
params = super().get_params(**kwargs)
params["MemberMessage"].update(
{
"QuestionType": question_type,
"Subject": subject,
}
)
return params
class ReviseMessages(EbayTradingAPI):
"""
ReviseMyMessages:
https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/ReviseMyMessages.html
"""
method_name = "ReviseMyMessages"
def get_params(self, message_ids: list, read: bool = None, folder_id: int = None, **kwargs):
if read:
folder_id = None
return {
"MessageIDs": {
"MessageID": message_ids,
},
"Read": read,
"FolderID": folder_id,
}
class MarkMessageRead(ReviseMessages):
def get_params(self, **kwargs):
kwargs["read"] = True
return super().get_params(**kwargs)
class MarkMessageUnread(ReviseMessages):
def get_params(self, **kwargs):
kwargs["read"] = False
return super().get_params(**kwargs)
class DeleteMessageList(EbayTradingAPI):
"""
Docs:
https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/DeleteMyMessages.html
"""
method_name = "DeleteMyMessages"
def get_params(self, message_ids: list, **kwargs):
return {
"MessageIDs": {"MessageID": message_ids},
} | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/core/trading/messages.py | messages.py |
MarketplaceToLang = {
"default": "en-US",
"EBAY_US": "en-US",
"EBAY_MOTORS_US": "en-US",
"EBAY_CA": "en-CA",
"EBAY_GB": "en-GB",
"EBAY_AU": "en-AU",
"EBAY_AT": "de-AT",
"EBAY_BE_FR": "fr-BE",
"EBAY_FR": "fr-FR",
"EBAY_DE": "de-DE",
"EBAY_IT": "it-IT",
"EBAY_BE_NL": "nl-BE",
"EBAY_NL": "nl-NL",
"EBAY_ES": "es-ES",
"EBAY_CH": "de-CH",
"EBAY_TW": "zh-TW",
"EBAY_CZ": "en-US", # not defined
"EBAY_DK": "en-US", # not defined
"EBAY_FI": "en-US", # not defined
"EBAY_GR": "en-US", # not defined
"EBAY_HK": "zh-HK",
"EBAY_HU": "en-US", # not defined
"EBAY_IN": "en-GB",
"EBAY_ID": "en-US", # not defined
"EBAY_IE": "en-IE",
"EBAY_IL": "en-US", # not defined
"EBAY_MY": "en-US",
"EBAY_NZ": "en-US", # not defined
"EBAY_NO": "en-US", # not defined
"EBAY_PH": "en-PH",
"EBAY_PL": "pl-PL",
"EBAY_PT": "en-US", # not defined
"EBAY_PR": "en-US", # not defined
"EBAY_RU": "ru-RU",
"EBAY_SG": "en-US",
"EBAY_ZA": "en-US", # not defined
"EBAY_SE": "en-US", # not defined
"EBAY_TH": "th-TH",
"EBAY_VN": "en-US",
"EBAY_CN": "en-US", # not defined
"EBAY_PE": "en-US", # not defined
"EBAY_CA_FR": "fr-CA",
"EBAY_JP": "en-US", # not defined
}
MarketplaceToLocale = {
"default": "en_US",
"EBAY_US": "en_US",
"EBAY_MOTORS_US": "en_US",
"EBAY_CA": "en_CA",
"EBAY_GB": "en_GB",
"EBAY_AU": "en_AU",
"EBAY_AT": "de_AT",
"EBAY_BE_FR": "fr_BE",
"EBAY_FR": "fr_FR",
"EBAY_DE": "de_DE",
"EBAY_IT": "it_IT",
"EBAY_BE_NL": "nl_BE",
"EBAY_NL": "nl_NL",
"EBAY_ES": "es_ES",
"EBAY_CH": "de_CH",
"EBAY_TW": "zh_TW",
"EBAY_CZ": "en_US", # not defined
"EBAY_DK": "en_US", # not defined
"EBAY_FI": "en_US", # not defined
"EBAY_GR": "en_US", # not defined
"EBAY_HK": "zh_HK",
"EBAY_HU": "en_US", # not defined
"EBAY_IN": "en_GB",
"EBAY_ID": "en_US", # not defined
"EBAY_IE": "en_IE",
"EBAY_IL": "en_US", # not defined
"EBAY_MY": "en_US",
"EBAY_NZ": "en_US", # not defined
"EBAY_NO": "en_US", # not defined
"EBAY_PH": "en_PH",
"EBAY_PL": "pl_PL",
"EBAY_PT": "en_US", # not defined
"EBAY_PR": "en_US", # not defined
"EBAY_RU": "ru_RU",
"EBAY_SG": "en_US",
"EBAY_ZA": "en_US", # not defined
"EBAY_SE": "en_US", # not defined
"EBAY_TH": "th_TH",
"EBAY_VN": "en_US",
"EBAY_CN": "en_US", # not defined
"EBAY_PE": "en_US", # not defined
"EBAY_CA_FR": "fr_CA",
"EBAY_JP": "en_US", # not defined
} | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/data/marketplace/marketplace_to_lang.py | marketplace_to_lang.py |
from model_utils import Choices
CancelStateEnum = Choices(
("CANCELED", "Заказ отменён"),
("IN_PROGRESS", "Сделан хотя бы один запрос на отмену заказа"),
("NONE_REQUESTED", "Запросов на отмену заказа нет"),
)
CancelRequestStateEnum = Choices(
("COMPLETED", "Продавец подтвердил отмену заказа"),
("REJECTED", "Продавец отказал в отмене заказа"),
("REQUESTED", "Запрос на отмену заказа ожидает ответа от продавца"),
)
FulfillmentInstructionsType = Choices(
("DIGITAL", "Цифровой вид"),
("PREPARE_FOR_PICKUP", "Готовится к In-Store Pickup"),
("SELLER_DEFINED", "Определяется продавцом"),
("SHIP_TO", "Отправляется продавцом"),
)
LineItemFulfillmentStatusEnum = Choices(
("FULFILLED", "Фулфилмент завершен"),
("IN_PROGRESS", "Фулфилмент в процессе"),
("NOT_STARTED", "Фулфилмент не начат"),
)
SoldFormatEnum = Choices(
("AUCTION", "Аукцион"),
("FIXED_PRICE", "Фиксированная цена"),
("OTHER", "Другое"),
("SECOND_CHANCE_OFFER", "Second chance offer"),
)
OrderFulfillmentStatus = Choices(
("FULFILLED", "Фулфилмент завершен"),
("IN_PROGRESS", "Фулфилмент в процессе"),
("NOT_STARTED", "Фулфилмент не начат"),
)
OrderPaymentStatusEnum = Choices(
("FAILED", "Неудача"),
("FULLY_REFUNDED", "Деньги в полном объеме возвращены покупателю"),
("PAID", "Оплачено"),
("PARTIALLY_REFUNDED", "Деньги частично возвращены покупателю"),
("PENDING", "Ожидание"),
)
PaymentMethodTypeEnum = Choices(("CREDIT_CARD", "Банковская карта"), ("PAYPAL", "Paypal"))
PaymentStatusEnum = Choices(
("FAILED", "Неудача"),
("PAID", "Оплачено"),
("PENDING", "Ожидание"),
)
PaymentHoldStateEnum = Choices(
("HELD", "Заморожено"),
("HELD_PENDING", "Ожидается заморозка"),
("NOT_HELD", "Не заморожено"),
("RELEASE_CONFIRMED", "Подтверждено размораживание"),
("RELEASE_FAILED", "Неудачное размораживание"),
("RELEASE_PENDING", "Ожидается размораживание"),
("RELEASED", "Разморожено"),
)
RefundStatusEnum = Choices(
("FAILED", "Неудача"),
("PENDING", "Ожидание"),
("REFUNDED", "Деньги возвращены"),
)
TaxTypeEnum = Choices(
("GST", "Goods and Services import tax"),
("PROVINCE_SALES_TAX", "Provincial sales tax"),
("REGION", "Regional sales tax"),
("STATE_SALES_TAX", "State sales tax"),
("VAT", "Value-Added tax (VAT)"),
)
DisputeStateEnum = Choices(
("OPEN", "Открыто"),
("ACTION_NEEDED", "Требуется действие"),
("CLOSED", "Закрыто"),
) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/data/enums/order_enums.py | order_enums.py |
from model_utils import Choices
AvailabilityTypeEnum = Choices(
("IN_STOCK", "В наличии"),
("OUT_OF_STOCK", "Нет в наличии"),
("SHIP_TO_STORE", "Ожидается пополнение"),
)
PackageTypeEnum = Choices(
("LETTER", "Бумага"),
("BULKY_GOODS", "Bulky good"),
("CARAVAN", "Caravan"),
("CARS", "Автомобиль"),
("EUROPALLET", "Euro pallet"),
("EXPANDABLE_TOUGH_BAGS", "Expandable tough bag"),
("EXTRA_LARGE_PACK", "Extra large pack"),
("FURNITURE", "Мебель"),
("INDUSTRY_VEHICLES", "Industry vehicle"),
("LARGE_CANADA_POSTBOX", "A Canada Post large box"),
("LARGE_CANADA_POST_BUBBLE_MAILER", "Canada Post large bubble mailer"),
("LARGE_ENVELOPE", "Большой конверт"),
("MAILING_BOX", "Mailing box"),
("MEDIUM_CANADA_POST_BOX", "Medium Canada Post box"),
("MEDIUM_CANADA_POST_BUBBLE_MAILER", "Medium Canada Post bubble mailer"),
("MOTORBIKES", "Мотоцикл"),
("ONE_WAY_PALLET", "One-way pallet"),
("PACKAGE_THICK_ENVELOPE", "Толстый конверт"),
("PADDED_BAGS", "Padded bag"),
("PARCEL_OR_PADDED_ENVELOPE", "Посылка или мягкий конверт"),
("ROLL", "Roll"),
("SMALL_CANADA_POST_BOX", "Small Canada Post box"),
("SMALL_CANADA_POST_BUBBLE_MAILER", "Small Canada Post bubble mailer"),
("TOUGH_BAGS", "Tough bag"),
("UPS_LETTER", "Письмо UPS"),
("USPS_FLAT_RATE_ENVELOPE", "USPS flat-rate envelope"),
("USPS_LARGE_PACK", "USPS large pack"),
("VERY_LARGE_PACK", "USPS very large pack"),
("WINE_PAK", "Wine pak"),
)
ShippingServiceTypeEnum = Choices(
("DOMESTIC", "Внутренняя доставка"),
("INTERNATIONAL", "Международная доставка"),
)
SoldOnEnum = Choices(
("ON_EBAY", "Товар продавался по указанной цене на сайте eBay"),
("OFF_EBAY", "Товар продавался по указанной цене на сторонних сайтах"),
(
"ON_AND_OFF_EBAY",
"Товар продавался по указанной цене как на сайте eBay, так и на сторонних сайтах",
),
)
MinimumAdvertisedPriceHandlingEnum = Choices(
("NONE", "Не использовать"),
("PRE_CHECKOUT", "До оформления заказа"),
("DURING_CHECKOUT", "После оформления заказа"),
)
# https://developer.ebay.com/api-docs/sell/inventory/types/slr:ListingStatusEnum
ListingStatusEnum = Choices(
("ACTIVE", "ACTIVE"),
("OUT_OF_STOCK", "OUT_OF_STOCK"),
("INACTIVE", "INACTIVE"),
("ENDED", "ENDED"),
("EBAY_ENDED", "EBAY_ENDED"),
("NOT_LISTED", "NOT_LISTED"),
) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/data/enums/listing_enums.py | listing_enums.py |
from model_utils import Choices
ShippingCarriersEnum = Choices(
("Other", "Другое"),
("DHL", "DHL Express"),
("DHLEKB", "DHL EKB"),
("DHLEXPRESS", "DHL Express"),
("DHLGlobalMail", "DHL Global Mail"),
("UPS", "United Parcel Service"),
("USPS", "U.S. Postal Service"),
("GENERIC", "Generic"),
)
AllShippingCarriersEnum = Choices(
("Other", "Use this code for any carrier not listed here."),
("A1CourierServices", "A-1 Courier"),
("ABF", "ABF Freight"),
("AeroPost", "AeroPost"),
("ALLIEDEXPRESS", "Allied Express"),
("AMWST", "AMWST"),
("AnPost", "An Post"),
("APC", "APC Postal Logistics"),
("ARAMEX", "Aramex"),
("ARVATO", "Arvato"),
("ASM", "ASM"),
("AustralianAirExpress", "Australian Air Express"),
("AustraliaPost", "Australia Post"),
("AVRT", "Averitt Express"),
("Bartolini", "BRT Bartolini"),
("BELGIANPOST", "Belgian Post Group"),
("BKNS", "BKNS"),
("BluePackage", "Blue Package Delivery"),
("BPost", "bpost"),
("BusinessPost", "BusinessPost"),
("CanPar", "Canpar Courier"),
("CENF", "Central Freight Lines"),
("CEVA", "CEVA Logistics"),
("ChinaPost", "China Post"),
("Chronoexpres", "Chronoexpres"),
("Chronopost", "Chronopost"),
("CHUKOU1", "Chukou1"),
("ChunghwaPost", "Chunghwa Post"),
("CitiPost", "CitiPost"),
("CityLink", "Citylink"),
("ClickandQuick", "Click & Quick"),
("CNWY", "XPO Logistics (formerly Con-way Freight)"),
("ColiposteDomestic", "Coliposte Domestic"),
("ColiposteInternational", "Coliposte International"),
("Colissimo", "Colissimo"),
("CollectPlus", "CollectPlus"),
("Correos", "Correos"),
("CPC", "CPC Logistics"),
("DAIPost", "DAI Post"),
("DayandRoss", "Day & Ross"),
("DBSchenker", "DB Schenker"),
("DeutschePost", "Deutsche Post"),
("DHL", "DHL Express"),
("DHLEKB", "DHL EKB"),
("DHLEXPRESS", "DHL Express"),
("DHLGlobalMail", "DHL Global Mail"),
("DieSchweizerischePost", "Die Schweizerische Post"),
("DPD", "DPD (Dynamic Parcel Distribution)"),
("DPXThailand", "DPX Thailand"),
("EGO", "E-go"),
("Exapaq", "DPD France (formerly Exapaq)"),
("Fastway", "Fastway"),
("FASTWAYCOURIERS", "Fastway Couriers"),
("FedEx", "FedEx"),
("FedExSmartPost", "FedEx SmartPost"),
("FLYT", "Flyt"),
("FLYTExpress", "Flyt Express"),
("FlytExpressUSDirectline", "Flyt Express US Direct line"),
("FourPX", "4PX"),
("FourPXCHINA", "4PX China"),
("FourPXExpress", "4PX Express"),
("FourPXLTD", "4PX Express Co. Ltd"),
("FulfilExpressAccStation", "FulfilExpress-AccStation"),
("FulfilExpresseForCity", "FulfilExpress-eForCity"),
("FulfilExpressEverydaySource", "FulfilExpress-EverydaySource"),
("FulfilExpressiTrimming", "FulfilExpress-iTrimming"),
("GLS", "GLS (General Logistics Systems)"),
("HDUSA", "MXD Group (formerly Home Direct USA)"),
("Hermes", "Hermes Group"),
("HongKongPost", "Hong Kong Post"),
("HUNTEREXPRESS", "Hunter Express"),
("iLoxx", "iloxx eService"),
("IndiaPost", "India Post"),
("IndonesiaPost", "Indonesia Post"),
("Interlink", "Interlink Express"),
("InterPost", "InterPost"),
("IoInvio", "IoInvio"),
("Iparcel", "UPS i-parcel"),
("IsraelPost", "Israel Post"),
("JapanPost", "Japan Post"),
("KIALA", "Kiala (UPS Access Point)"),
("KoreaPost", "Korea Post"),
("Landmark", "Landmark Global"),
("LAPOSTE", "La Poste"),
("MALAYSIAPOST", "Malaysia Post"),
("MannaFreight", "Manna Distribution Services"),
("Metapack", "Metapack"),
("MNGTurkey", "MNG Kargo"),
("MondialRelay", "Mondial Relay"),
("MRW", "MRW"),
("MSI", "MSI Transportation"),
("Nacex", "Nacex"),
("NEMF", "New England Motor Freight"),
("ODFL", "Old Dominion Freight Line"),
("ONTRACK", "OnTrac Shipping"),
("OsterreichischePostAG", "Osterreichische Post"),
("Parcelforce", "Parcelforce"),
("ParcelPool", "International Bridge Domestic delivery"),
("Philpost", "PHLPost (Philippine Postal Corporation)"),
("Pilot", "Pilot Freight Services"),
("PITD", "PITT OHIO"),
("PocztaPolska", "Poczta Polska"),
("Pocztex", "Pocztex"),
("PosteItaliane", "Poste Italiane"),
("POSTITALIANO", "Post Italiano"),
("PostNL", "PostNL"),
("PostNordNorway", "PostNord"),
("Quantium", "Quantium Solutions"),
("RETL", "Reddaway"),
("RoyalMail", "Royal Mail"),
("SAIA", "Saia LTL Freight"),
("SDA", "SDA Express Courier"),
("SINGAPOREPOST", "Singapore Post"),
("Siodemka", "Siodemka (DPD Poland)"),
("SioliandFontana", "Sioli & Fontana"),
("SkynetMalaysia", "Skynet (Malaysia)"),
("SMARTSEND", "Smart Send Courier Service"),
("Sogetras", "SGT Corriere Espresso"),
("Spediamo", "Spediamo"),
("SpeeDee", "Spee-Dee Delivery Service"),
("StarTrack", "StarTrack"),
("SuntekExpressLTD", "Suntek Express LTD"),
("SwissPost", "Swiss Post"),
("TELE", "TELE"),
("TEMANDO", "Temando (shipping broker)"),
("THAILANDPOST", "Thailand Post"),
("Toll", "Toll (Japan Post)"),
("TPG", "TPG Logistics"),
("UBI", "UBI Smart Parcel"),
("UKMail", "UK Mail"),
("UPS", "United Parcel Service"),
("USPS", "U.S. Postal Service"),
("USPSCeP", "USPS Commercial ePacket"),
("USPSPMI", "USPS Priority Mail International"),
("VietnamPost", "Vietnam Post"),
("VITR", "Vitran Express"),
("Winit", "WIN.IT America"),
("WNdirect", "wnDirect"),
("WPX", "WPX Delivery Solutions"),
("YANWEN", "YANWEN Express"),
("Yodel", "Yodel"),
("YRC", "YRC Freight"),
) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/api/ebay/data/enums/shipping_carriers_enum.py | shipping_carriers_enum.py |
from model_utils import Choices
from django.utils.translation import gettext_lazy as _
from .country import COUNTRIES
__all__ = [
"OTHER_CURRENCIES",
"MARKETPLACE_CURRENCIES",
"CURRENCIES",
"USER_CURRENCIES",
"INTERNAL_CURRENCIES",
"CURRENCY_CODE_TO_NAME",
"CURRENCY_NAME_TO_CODE",
"CURRENCIES_BY_COUNTRY_CODE",
]
OTHER_CURRENCIES = Choices(
("AED", _("Дирхам (Оаэ)")),
("AFN", _("Афгани")),
("ALL", _("Лек")),
("AMD", _("Армянский Драм")),
("ANG", _("Нидерландский Антильский Гульден")),
("AOA", _("Кванза")),
("ARS", _("Аргентинское Песо")),
("AWG", _("Арубанский Флорин")),
("AZN", _("Азербайджанский Манат")),
("BAM", _("Конвертируемая Марка")),
("BBD", _("Барбадосский Доллар")),
("BDT", _("Така")),
("BGN", _("Болгарский Лев")),
("BHD", _("Бахрейнский Динар")),
("BIF", _("Бурундийский Франк")),
("BMD", _("Бермудский Доллар")),
("BND", _("Брунейский Доллар")),
("BOB", _("Боливиано")),
("BRL", _("Бразильский Реал")),
("BSD", _("Багамский Доллар")),
("BTN", _("Нгултрум")),
("BWP", _("Пула")),
("BYR", _("Белорусский Рубль")),
("BZD", _("Белизский Доллар")),
("CDF", _("Конголезский Франк")),
("CLP", _("Чилийское Песо")),
("COP", _("Колумбийское Песо")),
("CRC", _("Костариканский Колон")),
("CUP", _("Кубинское Песо")),
("CVE", _("Эскудо Кабо-Верде")),
("DJF", _("Франк Джибути")),
("DOP", _("Доминиканское Песо")),
("DZD", _("Алжирский Динар")),
("EGP", _("Египетский Фунт")),
("ERN", _("Накфа")),
("ETB", _("Эфиопский Быр")),
("FJD", _("Доллар Фиджи")),
("FKP", _("Фунт Фолклендских Островов")),
("GEL", _("Ларистанский")),
("GHS", _("Седи")),
("GIP", _("Гибралтарский Фунт")),
("GMD", _("Даласи")),
("GNF", _("Гвинейский Франк")),
("GTQ", _("Кетсаль")),
("GYD", _("Гайанский Доллар")),
("HNL", _("Лемпира")),
("HRK", _("Куна")),
("HTG", _("Гурд")),
("IQD", _("Иракский Динар")),
("IRR", _("Иранский Риал")),
("ISK", _("Исландская Крона")),
("JMD", _("Ямайский Доллар")),
("JOD", _("Иорданский Динар")),
("KES", _("Кенийский Шиллинг")),
("KGS", _("Сом")),
("KHR", _("Риель")),
("KMF", _("Франк Комор")),
("KPW", _("Северокорейская Вона")),
("KRW", _("Вона")),
("KWD", _("Кувейтский Динар")),
("KYD", _("Доллар Островов Кайман")),
("KZT", _("Тенге")),
("LAK", _("Кип")),
("LBP", _("Ливанский Фунт")),
("LKR", _("Шри-Ланкийская Рупия")),
("LRD", _("Либерийский Доллар")),
("LSL", _("Лоти")),
("LTL", _("Литовский Лит")),
("LYD", _("Ливийский Динар")),
("MAD", _("Марокканский Дирхам")),
("MDL", _("Молдавский Лей")),
("MGA", _("Малагасийский Ариари")),
("MKD", _("Македонский Денар")),
("MMK", _("Кьят")),
("MNT", _("Тугрик")),
("MOP", _("Патака")),
("MRO", _("Угия")),
("MUR", _("Маврикийская Рупия")),
("MVR", _("Руфия")),
("MWK", _("Малавийская Квача")),
("MXN", _("Мексиканское Песо")),
("MZN", _("Мозамбикский Метикал")),
("NAD", _("Доллар Намибии")),
("NGN", _("Найра")),
("NIO", _("Золотая Кордоба")),
("NPR", _("Непальская Рупия")),
("OMR", _("Оманский Риал")),
("PAB", _("Бальбоа")),
("PGK", _("Кина")),
("PKR", _("Пакистанская Рупия")),
("PYG", _("Гуарани")),
("QAR", _("Катарский Риал")),
("RON", _("Румынский Лей")),
("RSD", _("Сербский Динар")),
("RUR", _("Российский Рубль")),
("RWF", _("Франк Руанды")),
("SAR", _("Саудовский Риял")),
("SBD", _("Доллар Соломоновых Островов")),
("SCR", _("Сейшельская Рупия")),
("SDG", _("Суданский Фунт")),
("SHP", _("Фунт Святой Елены")),
("SLL", _("Леоне")),
("SOS", _("Сомалийский Шиллинг")),
("SRD", _("Суринамский Доллар")),
("STD", _("Добра")),
("SYP", _("Сирийский Фунт")),
("SZL", _("Лилангени")),
("TJS", _("Сомони")),
("TMT", _("Туркменский Новый Манат")),
("TND", _("Тунисский Динар")),
("TOP", _("Паанга")),
("TRY", _("Турецкая Лира")),
("TTD", _("Доллар Тринидада И Тобаго")),
("TZS", _("Танзанийский Шиллинг")),
("UAH", _("Гривна")),
("UGX", _("Угандийский Шиллинг")),
("UYU", _("Уругвайское Песо")),
("UZS", _("Узбекский Сум")),
("VEF", _("Боливар")),
("VUV", _("Вату")),
("WST", _("Тала")),
("XAF", _("Франк Кфа Веас")),
("XCD", _("Восточно-Карибский Доллар")),
("XOF", _("Франк Кфа Всеао")),
("XPF", _("Франк Кфп")),
("YER", _("Йеменский Риал")),
("ZMW", _("Замбийская Квача")),
("ZWL", _("Доллар Зимбабве")),
)
MARKETPLACE_CURRENCIES = Choices(
("USD", _("Доллар США")),
("RUB", _("Российский Рубль")),
("EUR", _("Евро")),
("GBP", _("Фунт Стерлингов")),
("AUD", _("Австралийский Доллар")),
("CNY", _("Китайский Юань")),
("PLN", _("Злотый")),
("CHF", _("Швейцарский Франк")),
("JPY", _("Иена")),
("IDR", _("Рупия")),
("VND", _("Донг")),
("NOK", _("Норвежская Крона")),
("SGD", _("Сингапурский Доллар")),
("SEK", _("Шведская Крона")),
("MYR", _("Малайзийский Ринггит")),
("THB", _("Бат")),
("NZD", _("Новозеландский Доллар")),
("HUF", _("Форинт")),
("HKD", _("Гонконгский Доллар")),
("INR", _("Индийская Рупия")),
("PHP", _("Филиппинское Песо")),
("DKK", _("Датская Крона")),
("TWD", _("Новый Тайваньский Доллар")),
("PEN", _("Соль")),
("ZAR", _("Рэнд")),
("CAD", _("Канадский Доллар")),
("CZK", _("Чешская Крона")),
("ILS", _("Новый Израильский Шекель")),
)
CURRENCIES = MARKETPLACE_CURRENCIES + OTHER_CURRENCIES
CURRENCY_CODE_TO_NAME = dict(CURRENCIES)
CURRENCY_NAME_TO_CODE = dict((v, k) for k, v in CURRENCY_CODE_TO_NAME.items())
USER_CURRENCIES = CURRENCIES.subset("RUB", "USD")
INTERNAL_CURRENCIES = CURRENCIES.subset("USD", "EUR")
CURRENCIES_BY_COUNTRY_CODE = {
COUNTRIES.BD: ("BDT",),
COUNTRIES.BE: ("EUR",),
COUNTRIES.BF: ("XOF",),
COUNTRIES.BG: ("BGN",),
COUNTRIES.BA: ("BAM",),
COUNTRIES.BB: ("BBD",),
COUNTRIES.WF: ("XPF",),
COUNTRIES.BL: ("EUR",),
COUNTRIES.BM: ("BMD",),
COUNTRIES.BN: ("BND",),
COUNTRIES.BO: ("BOB",),
COUNTRIES.BH: ("BHD",),
COUNTRIES.BI: ("BIF",),
COUNTRIES.BJ: ("XOF",),
COUNTRIES.BT: ("BTN", "INR"),
COUNTRIES.JM: ("JMD",),
COUNTRIES.BV: ("NOK",),
COUNTRIES.BW: ("BWP",),
COUNTRIES.WS: ("WST",),
COUNTRIES.BQ: ("USD",),
COUNTRIES.BR: ("BRL",),
COUNTRIES.BS: ("BSD",),
COUNTRIES.JE: ("GBP",),
COUNTRIES.BY: ("BYR",),
COUNTRIES.BZ: ("BZD",),
COUNTRIES.RU: ("RUB",),
COUNTRIES.RW: ("RWF",),
COUNTRIES.RS: ("RSD",),
COUNTRIES.TL: ("USD",),
COUNTRIES.RE: ("EUR",),
COUNTRIES.TM: ("TMT",),
COUNTRIES.TJ: ("TJS",),
COUNTRIES.RO: ("RON",),
COUNTRIES.TK: ("NZD",),
COUNTRIES.GW: ("XOF",),
COUNTRIES.GU: ("USD",),
COUNTRIES.GT: ("GTQ",),
COUNTRIES.GS: ("GBP",),
COUNTRIES.GR: ("EUR",),
COUNTRIES.GQ: ("XAF",),
COUNTRIES.GP: ("EUR",),
COUNTRIES.JP: ("JPY",),
COUNTRIES.GY: ("GYD",),
COUNTRIES.GG: ("GBP",),
COUNTRIES.GF: ("EUR",),
COUNTRIES.GE: ("GEL",),
COUNTRIES.GD: ("XCD",),
COUNTRIES.GB: ("GBP",),
COUNTRIES.GA: ("XAF",),
COUNTRIES.SV: ("USD",),
COUNTRIES.GN: ("GNF",),
COUNTRIES.GM: ("GMD",),
COUNTRIES.GL: ("DKK",),
COUNTRIES.GI: ("GIP",),
COUNTRIES.GH: ("GHS",),
COUNTRIES.OM: ("OMR",),
COUNTRIES.TN: ("TND",),
COUNTRIES.IL: ("ILS",),
COUNTRIES.JO: ("JOD",),
COUNTRIES.HR: ("HRK",),
COUNTRIES.HT: ("HTG", "USD"),
COUNTRIES.HU: ("HUF",),
COUNTRIES.HK: ("HKD",),
COUNTRIES.HN: ("HNL",),
COUNTRIES.HM: ("AUD",),
COUNTRIES.VE: ("VEF",),
COUNTRIES.PR: ("USD",),
COUNTRIES.PS: (),
COUNTRIES.PW: ("USD",),
COUNTRIES.PT: ("EUR",),
COUNTRIES.SJ: ("NOK",),
COUNTRIES.PY: ("PYG",),
COUNTRIES.IQ: ("IQD",),
COUNTRIES.PA: ("PAB", "USD"),
COUNTRIES.PF: ("XPF",),
COUNTRIES.PG: ("PGK",),
COUNTRIES.PE: ("PEN",),
COUNTRIES.PK: ("PKR",),
COUNTRIES.PH: ("PHP",),
COUNTRIES.PN: ("NZD",),
COUNTRIES.PL: ("PLN",),
COUNTRIES.PM: ("EUR",),
COUNTRIES.ZM: ("ZMW",),
COUNTRIES.EH: ("MAD",),
COUNTRIES.EE: ("EUR",),
COUNTRIES.EG: ("EGP",),
COUNTRIES.ZA: ("ZAR",),
COUNTRIES.EC: ("USD",),
COUNTRIES.IT: ("EUR",),
COUNTRIES.VN: ("VND",),
COUNTRIES.SB: ("SBD",),
COUNTRIES.ET: ("ETB",),
COUNTRIES.SO: ("SOS",),
COUNTRIES.ZW: ("USD", "ZAR", "BWP", "GBP", "EUR"),
COUNTRIES.SA: ("SAR",),
COUNTRIES.ES: ("EUR",),
COUNTRIES.ER: ("ETB", "ERN"),
COUNTRIES.ME: ("EUR",),
COUNTRIES.MD: ("MDL",),
COUNTRIES.MG: ("MGA",),
COUNTRIES.MF: ("EUR",),
COUNTRIES.MA: ("MAD",),
COUNTRIES.MC: ("EUR",),
COUNTRIES.UZ: ("UZS",),
COUNTRIES.MM: ("MMK",),
COUNTRIES.ML: ("XOF",),
COUNTRIES.MO: ("MOP",),
COUNTRIES.MN: ("MNT",),
COUNTRIES.MH: ("USD",),
COUNTRIES.MK: ("MKD",),
COUNTRIES.MU: ("MUR",),
COUNTRIES.MT: ("EUR",),
COUNTRIES.MW: ("MWK",),
COUNTRIES.MV: ("MVR",),
COUNTRIES.MQ: ("EUR",),
COUNTRIES.MP: ("USD",),
COUNTRIES.MS: ("XCD",),
COUNTRIES.MR: ("MRO",),
COUNTRIES.IM: ("GBP",),
COUNTRIES.UG: ("UGX",),
COUNTRIES.MY: ("MYR",),
COUNTRIES.MX: ("MXN",),
COUNTRIES.AT: ("EUR",),
COUNTRIES.FR: ("EUR",),
COUNTRIES.IO: ("USD",),
COUNTRIES.SH: ("SHP",),
COUNTRIES.FI: ("EUR",),
COUNTRIES.FJ: ("FJD",),
COUNTRIES.FK: ("FKP",),
COUNTRIES.FM: ("USD",),
COUNTRIES.FO: ("DKK",),
COUNTRIES.NI: ("NIO",),
COUNTRIES.NL: ("EUR",),
COUNTRIES.NO: ("NOK",),
COUNTRIES.NA: ("NAD", "ZAR"),
COUNTRIES.NC: ("XPF",),
COUNTRIES.NE: ("XOF",),
COUNTRIES.NF: ("AUD",),
COUNTRIES.NG: ("NGN",),
COUNTRIES.NZ: ("NZD",),
COUNTRIES.NP: ("NPR",),
COUNTRIES.NR: ("AUD",),
COUNTRIES.NU: ("NZD",),
COUNTRIES.CK: ("NZD",),
COUNTRIES.CI: ("XOF",),
COUNTRIES.CH: ("CHF",),
COUNTRIES.CO: ("COP",),
COUNTRIES.CN: ("CNY",),
COUNTRIES.CM: ("XAF",),
COUNTRIES.CL: ("CLP",),
COUNTRIES.CC: ("AUD",),
COUNTRIES.CA: ("CAD",),
COUNTRIES.LB: ("LBP",),
COUNTRIES.CG: ("XAF",),
COUNTRIES.CF: ("XAF",),
COUNTRIES.CD: ("CDF",),
COUNTRIES.CZ: ("CZK",),
COUNTRIES.CY: ("EUR",),
COUNTRIES.CX: ("AUD",),
COUNTRIES.CR: ("CRC",),
COUNTRIES.CW: ("ANG",),
COUNTRIES.CV: ("CVE",),
COUNTRIES.CU: ("CUP", "CUC"),
COUNTRIES.SZ: ("SZL",),
COUNTRIES.SY: ("SYP",),
COUNTRIES.SX: ("ANG",),
COUNTRIES.KG: ("KGS",),
COUNTRIES.KE: ("KES",),
COUNTRIES.SR: ("SRD",),
COUNTRIES.KI: ("AUD",),
COUNTRIES.KH: ("KHR",),
COUNTRIES.KN: ("XCD",),
COUNTRIES.KM: ("KMF",),
COUNTRIES.ST: ("STD",),
COUNTRIES.SK: ("EUR",),
COUNTRIES.KR: ("KRW",),
COUNTRIES.SI: ("EUR",),
COUNTRIES.KP: ("KPW",),
COUNTRIES.KW: ("KWD",),
COUNTRIES.SN: ("XOF",),
COUNTRIES.SM: ("EUR",),
COUNTRIES.SL: ("SLL",),
COUNTRIES.SC: ("SCR",),
COUNTRIES.KZ: ("KZT",),
COUNTRIES.KY: ("KYD",),
COUNTRIES.SG: ("SGD",),
COUNTRIES.SE: ("SEK",),
COUNTRIES.SD: ("SDG",),
COUNTRIES.DO: ("DOP",),
COUNTRIES.DM: ("XCD",),
COUNTRIES.DJ: ("DJF",),
COUNTRIES.DK: ("DKK",),
COUNTRIES.VG: ("USD",),
COUNTRIES.DE: ("EUR",),
COUNTRIES.YE: ("YER",),
COUNTRIES.DZ: ("DZD",),
COUNTRIES.US: ("USD",),
COUNTRIES.UY: ("UYU",),
COUNTRIES.YT: ("EUR",),
COUNTRIES.UM: ("USD",),
COUNTRIES.TZ: ("TZS",),
COUNTRIES.LC: ("XCD",),
COUNTRIES.LA: ("LAK",),
COUNTRIES.TV: ("TVD", "AUD"),
COUNTRIES.TW: ("TWD",),
COUNTRIES.TT: ("TTD",),
COUNTRIES.TR: ("TRY",),
COUNTRIES.LK: ("LKR",),
COUNTRIES.LI: ("CHF",),
COUNTRIES.LV: ("EUR",),
COUNTRIES.TO: ("TOP",),
COUNTRIES.LT: ("LTL",),
COUNTRIES.LU: ("EUR",),
COUNTRIES.LR: ("LRD",),
COUNTRIES.LS: ("LSL", "ZAR"),
COUNTRIES.TH: ("THB",),
COUNTRIES.TF: ("EUR",),
COUNTRIES.TG: ("XOF",),
COUNTRIES.TD: ("XAF",),
COUNTRIES.TC: ("USD",),
COUNTRIES.LY: ("LYD",),
COUNTRIES.VA: ("EUR",),
COUNTRIES.VC: ("XCD",),
COUNTRIES.AE: ("AED",),
COUNTRIES.AD: ("EUR",),
COUNTRIES.AG: ("XCD",),
COUNTRIES.AF: ("AFN",),
COUNTRIES.AI: ("XCD",),
COUNTRIES.VI: ("USD",),
COUNTRIES.IS: ("ISK",),
COUNTRIES.IR: ("IRR",),
COUNTRIES.AM: ("AMD",),
COUNTRIES.AL: ("ALL",),
COUNTRIES.AO: ("AOA",),
COUNTRIES.AN: ("ANG",),
COUNTRIES.AQ: (),
COUNTRIES.AS: ("USD",),
COUNTRIES.AR: ("ARS",),
COUNTRIES.AU: ("AUD",),
COUNTRIES.VU: ("VUV",),
COUNTRIES.AW: ("AWG",),
COUNTRIES.IN: ("INR",),
COUNTRIES.AX: ("EUR",),
COUNTRIES.AZ: ("AZN",),
COUNTRIES.IE: ("EUR",),
COUNTRIES.ID: ("IDR",),
COUNTRIES.UA: ("UAH",),
COUNTRIES.QA: ("QAR",),
COUNTRIES.MZ: ("MZN",),
} | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/data/enums/currency.py | currency.py |
from model_utils import Choices
from django.utils.translation import gettext_lazy as _
__all__ = [
"USER_LANGUAGES",
"MARKETPLACE_LANGUAGES",
"OTHER_LANGUAGES",
"LANGUAGES",
]
USER_LANGUAGES = Choices(
("ru", _("Русский")),
("en", _("Английский")),
)
MARKETPLACE_LANGUAGES = Choices(
("en", _("Английский")),
("ru", _("Русский")),
("de", _("Немецкий")),
("zh", _("Китайский")),
("pl", _("Польский")),
("fr", _("Французский")),
("it", _("Итальянский")),
("pt", _("Португальский")),
("es", _("Испанский")),
("ja", _("Японский")),
("th", _("Тайский")),
("nl", _("Голландский")),
)
OTHER_LANGUAGES = Choices(
("ab", _("Абхазский")),
("aa", _("Афар")),
("af", _("Африкаанс")),
("ak", _("Акан")),
("sq", _("Албанский")),
("am", _("Амхарский")),
("ar", _("Арабский")),
("an", _("Арагонский")),
("hy", _("Армянский")),
("as", _("Ассамский")),
("av", _("Аварский")),
("ae", _("Авестийский")),
("ay", _("Аймара")),
("az", _("Азербайджанский")),
("bm", _("Бамбара")),
("ba", _("Башкирский")),
("eu", _("Баскский")),
("be", _("Белорусский")),
("bn", _("Бенгальский")),
("bh", _("Бихари")),
("bi", _("Бислама")),
("bs", _("Боснийский")),
("br", _("Бретонский")),
("bg", _("Болгарский")),
("my", _("Бирманский")),
("ca", _("Каталанский")),
("ch", _("Чаморро")),
("ce", _("Чеченский")),
("ny", _("Ньянджа")),
("cv", _("Чувашский")),
("kw", _("Корнский")),
("co", _("Корсиканский")),
("cr", _("Кри")),
("hr", _("Хорватский")),
("cs", _("Чешский")),
("da", _("Датский")),
("dv", _("Дивехи")),
("dz", _("Дзонг-Кэ")),
("eo", _("Эсперанто")),
("et", _("Эстонский")),
("ee", _("Эве")),
("fo", _("Фарерский")),
("fj", _("Фиджи")),
("fi", _("Финский")),
("ff", _("Фулах")),
("gl", _("Галисийский")),
("ka", _("Грузинский")),
("el", _("Новогреческий (1453-)")),
("gn", _("Гуарани")),
("gu", _("Гуджарати")),
("ht", _("Гаитянский")),
("ha", _("Хауса")),
("he", _("Иврит")),
("hz", _("Гереро")),
("hi", _("Хинди")),
("ho", _("Хири Моту")),
("hu", _("Венгерский")),
("ia", _("Интерлингва (Ассоциация Международного Вспомогательного Языка)")),
("id", _("Индонезийский")),
("ie", _("Интерлингве")),
("ga", _("Ирландский")),
("ig", _("Игбо")),
("ik", _("Инулиак")),
("io", _("Идо")),
("is", _("Исландский")),
("iu", _("Инуктитут")),
("jv", _("Яванский")),
("kl", _("Калааллисут")),
("kn", _("Каннада")),
("kr", _("Канури")),
("ks", _("Кашмири")),
("kk", _("Казахский")),
("km", _("Кхмерский Центральный")),
("ki", _("Кикуйю")),
("rw", _("Киньяруанда")),
("ky", _("Киргизский")),
("kv", _("Коми")),
("kg", _("Конго")),
("ko", _("Корейский")),
("ku", _("Курдский")),
("kj", _("Киньяма")),
("la", _("Латынь")),
("lb", _("Люксембургский")),
("lg", _("Ганда")),
("li", _("Лимбурган")),
("ln", _("Лингала")),
("lo", _("Лаосский")),
("lt", _("Литовский")),
("lu", _("Луба-Катанга")),
("lv", _("Латышский")),
("gv", _("Мэнкский")),
("mk", _("Македонский")),
("mg", _("Малагасийский")),
("ms", _("Малайский (Макроязык)")),
("ml", _("Малаялам")),
("mt", _("Мальтийский")),
("mi", _("Маори")),
("mr", _("Маратхи")),
("mh", _("Маршалльский")),
("mn", _("Монгольский")),
("na", _("Науру")),
("nv", _("Навахо")),
("nb", _("Норвежский Букмол")),
("nd", _("Северный Ндебеле")),
("ne", _("Непальский (макроязык)")),
("ng", _("Ндунга")),
("nn", _("Норвежский Нюнорск")),
("no", _("Норвежский")),
("ii", _("Сычуань Йи")),
("nr", _("Южный Ндебеле")),
("oc", _("Окситанский (пост 1500)")),
("oj", _("Оджибва")),
("cu", _("Церковнославянский")),
("om", _("Оромо")),
("or", _("Ория (макроязык)")),
("os", _("Осетинский")),
("pa", _("Панджаби")),
("pi", _("Пали")),
("fa", _("Персидский")),
("ps", _("Пушту")),
("qu", _("Кечуа")),
("rm", _("Ретороманский")),
("rn", _("Рунди")),
("ro", _("Румынский")),
("sa", _("Санскрит")),
("sc", _("Сардинский")),
("sd", _("Синдхи")),
("se", _("Северные Саамы")),
("sm", _("Самоанский")),
("sg", _("Санго")),
("sr", _("Сербский")),
("gd", _("Шотландский Гэльский")),
("sn", _("Шона")),
("si", _("Сингальский")),
("sk", _("Словацкий")),
("sl", _("Словенский")),
("so", _("Сомали")),
("st", _("Южный Сото")),
("su", _("Сунданский")),
("sw", _("Суахили (Макроязык)")),
("ss", _("Свати")),
("sv", _("Шведский")),
("ta", _("Тамильский")),
("te", _("Телугу")),
("tg", _("Таджикский")),
("ti", _("Тигринья")),
("bo", _("Тибетский")),
("tk", _("Туркменский")),
("tl", _("Тагальский")),
("tn", _("Тсвана")),
("to", _("Тонга (Острова Тонга)")),
("tr", _("Турецкий")),
("ts", _("Тсонга")),
("tt", _("Татарский")),
("tw", _("Тви")),
("ty", _("Таитянский")),
("ug", _("Уйгурский")),
("uk", _("Украинский")),
("ur", _("Урду")),
("uz", _("Узбекский")),
("ve", _("Венда")),
("vi", _("Вьетнамский")),
("vo", _("Волапюк")),
("wa", _("Валлун")),
("cy", _("Валлийский")),
("wo", _("Волоф")),
("fy", _("Западно-фризский")),
("xh", _("Коса")),
("yi", _("Идиш")),
("yo", _("Йоруба")),
("za", _("Чжуан")),
("zu", _("Зулусский")),
)
LANGUAGES = MARKETPLACE_LANGUAGES + OTHER_LANGUAGES | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/data/enums/language.py | language.py |
from model_utils import Choices
from django.utils.translation import gettext_lazy as _
__all__ = [
"OTHER_COUNTRIES",
"MARKETPLACE_COUNTRIES",
"COUNTRIES",
"COUNTRY_CODE_TO_NAME",
"COUNTRY_NAME_TO_CODE",
"COUNTRIES_NAME",
"COUNTRY_CODE_ALPHA_TO_NUM",
"NUM_TO_COUNTRY_CODE_ALPHA",
]
OTHER_COUNTRIES = Choices(
("AD", _("Андорра")),
("AE", _("Объединённые Арабские Эмираты")),
("AF", _("Афганистан")),
("AG", _("Антигуа И Барбуда")),
("AI", _("Ангвилла")),
("AL", _("Албания")),
("AM", _("Армения")),
("AN", _("Нидерландские Антильские острова")),
("AO", _("Ангола")),
("AQ", _("Антарктика")),
("AR", _("Аргентина")),
("AS", _("Американские Самоа")),
("AW", _("Аруба")),
("AX", _("Аландские Острова")),
("AZ", _("Азербайджан")),
("BA", _("Босния И Герцеговина")),
("BB", _("Барбадос")),
("BD", _("Бангладеш")),
("BE", _("Бельгия")),
("BF", _("Буркина-Фасо")),
("BG", _("Болгария")),
("BH", _("Бахрейн")),
("BI", _("Бурунди")),
("BJ", _("Бенин")),
("BL", _("Сен-Бартельми")),
("BM", _("Бермуды")),
("BN", _("Бруней Даруссалам")),
("BO", _("Боливия")),
("BQ", _("Бонайре, Синт-Эстатиус И Саба")),
("BR", _("Бразилия")),
("BS", _("Багамы")),
("BT", _("Бутан")),
("BV", _("Остров Буве")),
("BW", _("Ботсвана")),
("BY", _("Беларусь")),
("BZ", _("Белиз")),
("CC", _("Кокосовые Острова ")),
("CD", _("Демократическая Республика Конго")),
("CF", _("Центрально-Африканская Республика")),
("CG", _("Конго")),
("CI", _("Кот-Д'Ивуар")),
("CK", _("Острова Кука")),
("CL", _("Чили")),
("CM", _("Камерун")),
("CO", _("Колумбия")),
("CR", _("Коста-Рика")),
("CU", _("Куба")),
("CV", _("Кабо-Верде")),
("CW", _("Кюрасао")),
("CX", _("Остров Рождества")),
("CY", _("Кипр")),
("DJ", _("Джибути")),
("DM", _("Доминика")),
("DO", _("Доминиканская Республика")),
("DZ", _("Алжир")),
("EC", _("Эквадор")),
("EE", _("Эстония")),
("EG", _("Египет")),
("EH", _("Западная Сахара")),
("ER", _("Эритрея")),
("ET", _("Эфиопия")),
("FJ", _("Фиджи")),
("FK", _("Фолклендские (Мальвинские) Острова")),
("FM", _("Федеративные Штаты Микронезии")),
("FO", _("Фарерские Острова")),
("GA", _("Габон")),
("GD", _("Гренада")),
("GE", _("Грузия")),
("GF", _("Французская Гвиана")),
("GG", _("Гернси")),
("GH", _("Гана")),
("GI", _("Гибралтар")),
("GL", _("Гренландия")),
("GM", _("Гамбия")),
("GN", _("Гвинея")),
("GP", _("Гваделупа")),
("GQ", _("Экваториальная Гвинея")),
("GS", _("Южная Джорджия И Южные Сандвичевы Острова ")),
("GT", _("Гватемала")),
("GU", _("Гуам")),
("GW", _("Гвинея-Бисау")),
("GY", _("Гайана")),
("HM", _("Остров Херд И Острова Макдональд")),
("HN", _("Гондурас")),
("HR", _("Хорватия")),
("HT", _("Гаити")),
("IM", _("Остров Мэн")),
("IO", _("Британская Территория Индийского Океана")),
("IQ", _("Ирак")),
("IR", _("Иран")),
("IS", _("Исландия")),
("JE", _("Джерси")),
("JM", _("Ямайка")),
("JO", _("Иордания")),
("KE", _("Кения")),
("KG", _("Кыргызстан")),
("KH", _("Камбоджа")),
("KI", _("Кирибати")),
("KM", _("Коморские Острова")),
("KN", _("Сент-Китс И Невис")),
("KP", _("Корейская Народно-Демократическая Республика")),
("KR", _("Республика Корея")),
("KW", _("Кувейт")),
("KY", _("Каймановы Острова")),
("KZ", _("Казахстан")),
("LA", _("Лаосская Народно-Демократическая Республика")),
("LB", _("Ливан")),
("LC", _("Сент-Люсия")),
("LI", _("Лихтенштейн")),
("LK", _("Шри-Ланка")),
("LR", _("Либерия")),
("LS", _("Лесото")),
("LT", _("Литва")),
("LU", _("Люксембург")),
("LV", _("Латвия")),
("LY", _("Ливия")),
("MA", _("Марокко")),
("MC", _("Монако")),
("MD", _("Республика Молдова")),
("ME", _("Черногория")),
("MF", _("Сен-Мартен (Франция)")),
("MG", _("Мадагаскар")),
("MH", _("Маршалловы Острова")),
("MK", _("Северная Македония")),
("ML", _("Мали")),
("MM", _("Мьянма")),
("MN", _("Монголия")),
("MO", _("Аомынь")),
("MP", _("Острова Северной Марианы")),
("MQ", _("Мартиника")),
("MR", _("Мавритания")),
("MS", _("Монсеррат")),
("MT", _("Мальта")),
("MU", _("Маврикий")),
("MV", _("Мальдивы")),
("MW", _("Малави")),
("MX", _("Мексика")),
("MZ", _("Мозамбик")),
("NA", _("Намибия")),
("NC", _("Новая Каледония")),
("NE", _("Нигер")),
("NF", _("Остров Норфолк")),
("NG", _("Нигерия")),
("NI", _("Никарагуа")),
("NP", _("Непал")),
("NR", _("Науру")),
("NU", _("Ниуэ")),
("OM", _("Оман")),
("PA", _("Панама")),
("PF", _("Французская Полинезия")),
("PG", _("Папуа — Новая Гвинея")),
("PK", _("Пакистан")),
("PM", _("Сен-Пьер И Микелон")),
("PN", _("Питкэрн")),
("PS", _("Палестина")),
("PW", _("Палау")),
("PY", _("Парагвай")),
("QA", _("Катар")),
("RE", _("Реюньон")),
("RO", _("Румыния")),
("RS", _("Сербия")),
("RW", _("Руанда")),
("SA", _("Саудовская Аравия")),
("SB", _("Соломоновы Острова")),
("SC", _("Сейшельские Острова")),
("SD", _("Судан")),
("SH", _("Остров Святой Елены, Остров Вознесения И Тристан-Да-Кунья")),
("SI", _("Словения")),
("SJ", _("Шпицберген И Ян-Майен")),
("SK", _("Словакия")),
("SL", _("Сьерра-Леоне")),
("SM", _("Сан-Марино")),
("SN", _("Сенегал")),
("SO", _("Сомали")),
("SR", _("Суринам")),
("ST", _("Сан-Томе И Принсипи")),
("SV", _("Сальвадор")),
("SX", _("Синт-Мартен (Голландская Часть)")),
("SY", _("Сирийская Арабская Республика")),
("SZ", _("Эсватини")),
("TC", _("Острова Туркс И Каикос")),
("TD", _("Чад")),
("TF", _("Французские Южные Территории")),
("TG", _("Того")),
("TJ", _("Таджикистан")),
("TK", _("Токелау")),
("TL", _("Восточный Тимор")),
("TM", _("Туркменистан")),
("TN", _("Тунис")),
("TO", _("Тонга")),
("TR", _("Турция")),
("TT", _("Тринидад И Тобаго")),
("TV", _("Тувалу")),
("TZ", _("Танзания")),
("UA", _("Украина")),
("UG", _("Уганда")),
("UM", _("Соединенные Штаты Малых Удаленных Островов")),
("UY", _("Уругвай")),
("UZ", _("Узбекистан")),
("VA", _("Государство-Город Ватикан")),
("VC", _("Сент-Винсент И Гренадины")),
("VE", _("Боливарианская Республика Венесуэла")),
("VG", _("Виргинские Острова (Британия)")),
("VI", _("Виргинские Острова (CША)")),
("VU", _("Вануату")),
("WF", _("Уоллес И Футана")),
("WS", _("Самоа")),
("YE", _("Йемен")),
("YT", _("Майот")),
("ZM", _("Замбия")),
("ZW", _("Зимбабве")),
("ZR", _("Заир")),
)
MARKETPLACE_COUNTRIES = Choices(
("RU", _("Российская Федерация")),
("US", _("Соединённые Штаты")),
("AU", _("Австралия")),
("GB", _("Соединённое Королевство")),
("DE", _("Германия")),
("FR", _("Франция")),
("CZ", _("Чехия")),
("PL", _("Польша")),
("ES", _("Испания")),
("HK", _("Гонконг")),
("JP", _("Япония")),
("MY", _("Малайзия")),
("SG", _("Сингапур")),
("DK", _("Дания")),
("PE", _("Перу")),
("NZ", _("Новая Зеландия")),
("TW", _("Китайская Провинция Тайвань")),
("NO", _("Норвегия")),
("IL", _("Израиль")),
("SE", _("Швеция")),
("ZA", _("Южная Африка")),
("IT", _("Италия")),
("NL", _("Нидерланды")),
("ID", _("Индонезия")),
("TH", _("Таиланд")),
("PT", _("Португалия")),
("FI", _("Финляндия")),
("GR", _("Греция")),
("HU", _("Венгрия")),
("PR", _("Пуэрто-Рико")),
("IN", _("Индия")),
("VN", _("Вьетнам")),
("CN", _("Китай")),
("PH", _("Филиппины")),
("CA", _("Канада")),
("CH", _("Швейцария")),
("IE", _("Ирландия")),
("AT", _("Австрия")),
)
COUNTRIES = MARKETPLACE_COUNTRIES + OTHER_COUNTRIES
COUNTRY_CODE_TO_NAME = dict(COUNTRIES)
COUNTRY_NAME_TO_CODE = dict((v, k) for k, v in COUNTRY_CODE_TO_NAME.items())
COUNTRIES_NAME = [country for __, country in COUNTRIES]
COUNTRY_CODE_ALPHA_TO_NUM = {
"AW": 533,
"AF": 4,
"AO": 24,
"AI": 660,
"AX": 248,
"AL": 8,
"AD": 20,
"AE": 784,
"AR": 32,
"AM": 51,
"AS": 16,
"AQ": 10,
"TF": 260,
"AG": 28,
"AU": 36,
"AT": 40,
"AZ": 31,
"BI": 108,
"BE": 56,
"BJ": 204,
"BQ": 535,
"BF": 854,
"BD": 50,
"BG": 100,
"BH": 48,
"BS": 44,
"BA": 70,
"BL": 652,
"BY": 112,
"BZ": 84,
"BM": 60,
"BO": 68,
"BR": 76,
"BB": 52,
"BN": 96,
"BT": 64,
"BV": 74,
"BW": 72,
"CF": 140,
"CA": 124,
"CC": 166,
"CH": 756,
"CL": 152,
"CN": 156,
"CI": 384,
"CM": 120,
"CD": 180,
"CG": 178,
"CK": 184,
"CO": 170,
"KM": 174,
"CV": 132,
"CR": 188,
"CU": 192,
"CW": 531,
"CX": 162,
"KY": 136,
"CY": 196,
"CZ": 203,
"DE": 276,
"DJ": 262,
"DM": 212,
"DK": 208,
"DO": 214,
"DZ": 12,
"EC": 218,
"EG": 818,
"ER": 232,
"EH": 732,
"ES": 724,
"EE": 233,
"ET": 231,
"FI": 246,
"FJ": 242,
"FK": 238,
"FR": 250,
"FO": 234,
"FM": 583,
"GA": 266,
"GB": 826,
"GE": 268,
"GG": 831,
"GH": 288,
"GI": 292,
"GN": 324,
"GP": 312,
"GM": 270,
"GW": 624,
"GQ": 226,
"GR": 300,
"GD": 308,
"GL": 304,
"GT": 320,
"GF": 254,
"GU": 316,
"GY": 328,
"HK": 344,
"HM": 334,
"HN": 340,
"HR": 191,
"HT": 332,
"HU": 348,
"ID": 360,
"IM": 833,
"IN": 356,
"IO": 86,
"IE": 372,
"IR": 364,
"IQ": 368,
"IS": 352,
"IL": 376,
"IT": 380,
"JM": 388,
"JE": 832,
"JO": 400,
"JP": 392,
"KZ": 398,
"KE": 404,
"KG": 417,
"KH": 116,
"KI": 296,
"KN": 659,
"KR": 410,
"KW": 414,
"LA": 418,
"LB": 422,
"LR": 430,
"LY": 434,
"LC": 662,
"LI": 438,
"LK": 144,
"LS": 426,
"LT": 440,
"LU": 442,
"LV": 428,
"MO": 446,
"MF": 663,
"MA": 504,
"MC": 492,
"MD": 498,
"MG": 450,
"MV": 462,
"MX": 484,
"MH": 584,
"MK": 807,
"ML": 466,
"MT": 470,
"MM": 104,
"ME": 499,
"MN": 496,
"MP": 580,
"MZ": 508,
"MR": 478,
"MS": 500,
"MQ": 474,
"MU": 480,
"MW": 454,
"MY": 458,
"YT": 175,
"NA": 516,
"NC": 540,
"NE": 562,
"NF": 574,
"NG": 566,
"NI": 558,
"NU": 570,
"NL": 528,
"NO": 578,
"NP": 524,
"NR": 520,
"NZ": 554,
"OM": 512,
"PK": 586,
"PA": 591,
"PN": 612,
"PE": 604,
"PH": 608,
"PW": 585,
"PG": 598,
"PL": 616,
"PR": 630,
"KP": 408,
"PT": 620,
"PY": 600,
"PS": 275,
"PF": 258,
"QA": 634,
"RE": 638,
"RO": 642,
"RU": 643,
"RW": 646,
"SA": 682,
"SD": 729,
"SN": 686,
"SG": 702,
"GS": 239,
"SH": 654,
"SJ": 744,
"SB": 90,
"SL": 694,
"SV": 222,
"SM": 674,
"SO": 706,
"PM": 666,
"RS": 688,
"SS": 728,
"ST": 678,
"SR": 740,
"SK": 703,
"SI": 705,
"SE": 752,
"SZ": 748,
"SX": 534,
"SC": 690,
"SY": 760,
"TC": 796,
"TD": 148,
"TG": 768,
"TH": 764,
"TJ": 762,
"TK": 772,
"TM": 795,
"TL": 626,
"TO": 776,
"TT": 780,
"TN": 788,
"TR": 792,
"TV": 798,
"TW": 158,
"TZ": 834,
"UG": 800,
"UA": 804,
"UM": 581,
"UY": 858,
"US": 840,
"UZ": 860,
"VA": 336,
"VC": 670,
"VE": 862,
"VG": 92,
"VI": 850,
"VN": 704,
"VU": 548,
"WF": 876,
"WS": 882,
"YE": 887,
"ZA": 710,
"ZM": 894,
"ZW": 716,
}
NUM_TO_COUNTRY_CODE_ALPHA = {value: key for key, value in COUNTRY_CODE_ALPHA_TO_NUM.items()} | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/data/enums/country.py | country.py |
import requests
import json
from importlib import import_module
from django.conf import settings
from django.utils import timezone
from zs_utils.exceptions import CustomException
from zs_utils.api.services import ApiRequestLogService
from zs_utils.email import default_html_templates
class EmailServiceException(CustomException):
pass
class EmailService:
"""
Статика: https://cloud.digitalocean.com/spaces/zonesmart-production?i=e47403&path=zonesmart_production%2Femail_static%2F
Сервис для работы с email-уведомлениями (EmailSubscription)
"""
@classmethod
def get_html_template(cls, name: str) -> str:
if getattr(settings, "EMAIL_TEMPLATE_MODULE", None):
email_templates = import_module(name=settings.EMAIL_TEMPLATE_MODULE)
if hasattr(email_templates, name):
return getattr(email_templates, name)
if not hasattr(default_html_templates, name):
raise ValueError(f"HTML-шаблон '{name}' не найден.")
return getattr(default_html_templates, name)
@staticmethod
def format_date(date: timezone.datetime) -> str:
"""
Конвертация timezone.datetime в строку формата: '%a, %d %b %Y %H:%M:%S 0000'
"""
return date.strftime("%a, %d %b %Y %H:%M:%S 0000")
@classmethod
def send_email(
cls,
sender: str,
receivers: list,
subject: str,
text: str = None,
files: dict = None,
html: str = None,
template: str = None,
template_params: dict = None,
delivery_time: timezone.datetime = None,
tags: list = None,
**kwargs,
) -> dict:
"""
Отправка email-уведомления на пользовательские email адреса
"""
data = {
"from": sender,
"to": receivers,
"subject": subject,
"text": text,
"html": html,
"template": template,
"o:tag": tags,
}
if delivery_time:
data["o:deliverytime"] = cls.format_date(delivery_time)
if template_params:
data["h:X-Mailgun-Variables"] = json.dumps(template_params)
data = {key: value for key, value in data.items() if value}
response = requests.post(
url=f"{settings.MAILGUN_API_URL}/messages",
auth=("api", settings.MAILGUN_API_KEY),
data=data,
files=files,
)
ApiRequestLogService.save_api_request_log_by_response(
response=response,
save_if_is_success=False,
)
response.raise_for_status()
return response.json()
@classmethod
def get_social_media_icon_urls(cls) -> dict:
"""
Получение данных об иконках соц. сетей для формирования шаблона email-уведомления
"""
file_names = {
"facebook_icon_url": "facebook-icon.png",
"instagram_icon_url": "instagram-icon.png",
"linkedin_icon_url": "linkedin-icon.png",
"youtube_icon_url": "youtube-icon.png",
"twitter_icon_url": "twitter-icon.png",
"tg_icon_url": "tg_icon.png",
}
return {key: f"{settings.EMAIL_STATIC_FOLDER_URL}{value}" for key, value in file_names.items()}
@classmethod
def send_email_using_standard_template(
cls,
sender: str,
receivers: list,
subject: str,
title: str,
body_content: str,
cheers_content: str,
email_icon_path: str = None,
email_icon_url: str = None,
files: dict = None,
footer_extra_content: str = None,
extra_template_params: dict = None,
mailgun_template_name: str = "blank_template",
**kwargs,
) -> dict:
"""
Отправка email-уведомлений с использованием стандартного шаблона
"""
if title:
title_html = cls.get_html_template(name="title").format(title=title)
else:
title_html = ""
if not email_icon_url:
if email_icon_path:
email_icon_url = f"{settings.EMAIL_STATIC_FOLDER_URL}{email_icon_path}"
else:
email_icon_url = f"{settings.EMAIL_STATIC_FOLDER_URL}icon_email.png"
template_params = {
"title": title_html,
"body": body_content,
"logo_url": f"{settings.EMAIL_STATIC_FOLDER_URL}logo-1.png",
"email_icon_url": email_icon_url,
"cheers_text": cheers_content,
}
if footer_extra_content:
template_params["footer_text"] = footer_extra_content
template_params.update(cls.get_social_media_icon_urls())
if extra_template_params:
template_params.update(extra_template_params)
return cls.send_email(
sender=sender,
receivers=receivers,
subject=subject,
template=mailgun_template_name,
template_params=template_params,
files=files,
**kwargs,
)
@classmethod
def send_standard_team_email(
cls,
receivers: list,
subject: str,
title: str,
body_content: str,
email_icon_path: str = None,
files: dict = None,
footer_extra_content: str = None,
extra_template_params: dict = None,
**kwargs,
):
"""
Отправка email-уведомлений с использованием командного шаблона (от лица команды Zonesmart)
"""
return cls.send_email_using_standard_template(
sender="Команда Zonesmart [email protected]",
receivers=receivers,
subject=subject,
title=title,
body_content=body_content,
email_icon_path=email_icon_path,
cheers_content=cls.get_html_template(name="team_cheers"),
files=files,
footer_extra_content=footer_extra_content,
extra_template_params=extra_template_params,
**kwargs,
) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/email/services.py | services.py |
from distutils.util import strtobool
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
from rest_framework.views import View
from rest_framework.serializers import Serializer
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import get_user_model
from django.utils.translation import gettext as _
__all__ = [
"AdminModeViewMixin",
"ResponseShortcutsViewMixin",
"DataValidationViewMixin",
"OnlyInstanceViewMixin",
"NearbyIdsViewMixin",
]
class AdminModeViewMixin(View):
def _user_is_staff(self, user: settings.AUTH_USER_MODEL) -> bool:
return user.is_staff
@property
def admin_mode(self) -> bool:
"""
Включен режим администратора
"""
if not getattr(self, "_admin_mode", None):
return self._user_is_staff(user=self.request.user) and bool(
strtobool(self.request.GET.get("admin_mode", "false"))
)
return self._admin_mode
@admin_mode.setter
def admin_mode(self, value: bool) -> None:
"""
Установка значения для режима администрации
"""
self._admin_mode = value
@property
def no_limit(self) -> bool:
"""
Включён режим без ограничений
"""
if not getattr(self, "_no_limit", None):
self._no_limit = self.admin_mode and bool(strtobool(self.request.GET.get("no_limit", "false")))
return self._no_limit
@no_limit.setter
def no_limit(self, value) -> None:
"""
Установка значения для режима без ограничений
"""
self._no_limit = value
def get_user(self):
"""
Получение пользователя user.
В режиме администрации можно указывать любого пользователя и действовать от его лица
"""
if self.admin_mode:
user_id = self.request.GET.get("user_id")
if user_id:
User = get_user_model()
try:
return User.objects.get(id=user_id)
except User.DoesNotExist:
raise ValidationError({"user_id": _("Пользователь не найден.")})
user = self.request.user
if isinstance(user, AnonymousUser):
user = None
return user
class OnlyInstanceViewMixin(View):
"""
View-mixin для работы с единичными объектами (к пример у User лишь один объект настроек UserSettings)
"""
def get_object(self):
"""
Получение единственного объекта
"""
return self.get_queryset().first()
def list(self, request, *args, **kwargs):
"""
Замена отдачи списка объектов на единичный объект
"""
if getattr(self, "no_limit", False):
return super().list(request, *args, **kwargs)
instance = self.get_object()
if instance:
data = self.get_serializer(instance).data
else:
data = {}
return self.build_response(data=data)
@action(detail=False, methods=["PUT", "PATCH"])
def alter(self, request, *args, **kwargs):
"""
Обновление объекта
"""
instance = self.get_object()
serializer = self.get_serializer(instance=instance, data=request.data)
serializer.is_valid(raise_exception=True)
instance = serializer.save()
retrieve_serializer = self.serializer_classes.get(
"retrieve", self.serializer_classes.get("default", self.serializer_class)
)
return self.build_response(data=retrieve_serializer(instance=instance).data)
class NearbyIdsViewMixin(View):
"""
View-mixin для получения соседних идентификаторов
"""
@action(detail=True, methods=["GET"])
def get_nearby_ids(self, request, *args, **kwargs):
"""
Получение соседних идентификаторов относительно переданного объекта
"""
if hasattr(self, "actions_for_filterset_class"):
if self.actions_for_filterset_class != "__all__":
self.actions_for_filterset_class += ["get_nearby_ids"]
qs = self.filter_queryset(self.get_queryset())
ids = list(qs.values_list(self.lookup_field, flat=True))
obj_id = getattr(self.get_object(), self.lookup_field)
obj_index = ids.index(obj_id)
prev_id = ids[obj_index - 1] if (obj_index - 1 >= 0) else None
next_id = ids[obj_index + 1] if (obj_index + 1 <= qs.count() - 1) else None
return Response({"prev_id": prev_id, "next_id": next_id}, status=status.HTTP_200_OK)
class ResponseShortcutsViewMixin(View):
def build_response(
self,
message: str = None,
data: dict = None,
status_code: int = status.HTTP_200_OK,
**kwargs,
) -> Response:
"""
Создать ответ с переданным сообщением или данными. (Положительный по умолчанию)
"""
if not data:
if message:
data = {"message": message}
elif message:
if isinstance(data, dict):
data = {"message": message, **data}
else:
data = {"message": message, "data": data}
return Response(data=data, status=status_code)
def build_error_response(
self,
message: str = None,
data: dict = None,
status_code: int = status.HTTP_400_BAD_REQUEST,
**kwargs,
) -> Response:
"""
Создать ответ с ошибкой с переданным сообщением или данными
"""
return self.build_response(
message=message,
data=data,
status_code=status_code,
**kwargs,
)
class DataValidationViewMixin(View):
def validate_data(self, serializer_class: Serializer, data: dict = None) -> Serializer:
"""
Валидация данных по переданному сериализатору
"""
if not data:
data = {**self.request.data, **self.request.GET.dict()}
serializer = serializer_class(data=data)
serializer.is_valid(raise_exception=True)
return serializer
def get_validated_data(self, serializer_class, data: dict = None) -> dict:
"""
Получение провалидированных данных по переданному сериализатору
"""
serializer = self.validate_data(
serializer_class=serializer_class,
data=data,
)
return serializer.validated_data | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/views/mixins.py | mixins.py |
import logging
from distutils.util import strtobool
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.exceptions import MethodNotAllowed, ValidationError
from rest_framework.permissions import AllowAny
from django.conf import settings
from django.http import QueryDict
from django.utils.translation import gettext as _
from zs_utils.permissions import UserHasAccess
from zs_utils.views import mixins
from zs_utils.captcha import validate_captcha
__all__ = [
"CustomAPIView",
"CustomModelViewSet",
"get_client_ip",
]
logger = logging.getLogger()
def get_client_ip(request):
"""
Получение IP адреса клиента
"""
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[0]
else:
ip = request.META.get("REMOTE_ADDR")
return ip
class CustomAPIView(mixins.DataValidationViewMixin, mixins.ResponseShortcutsViewMixin, APIView):
permission_classes = [AllowAny]
class CustomModelViewSet(
mixins.AdminModeViewMixin,
mixins.DataValidationViewMixin,
mixins.ResponseShortcutsViewMixin,
ModelViewSet,
):
lookup_field = "id"
default_permission = UserHasAccess
ignore_has_access = False
allow_partial_update = True
not_allowed_actions = []
extra_allowed_actions = []
required_filters = []
actions_for_filterset_class = [
"retrieve",
]
serializer_classes = {}
serializer_class = None
light_serializer_class = None
verbose_serializer_class = None
def initialize_request(self, request, *args, **kwargs):
request = super().initialize_request(request, *args, **kwargs)
if (self.action in self.not_allowed_actions) and (self.action not in self.extra_allowed_actions):
return self.http_method_not_allowed(request, *args, **kwargs)
return request
def get_permissions(self):
"""
Проверка прав пользователя
"""
return super().get_permissions() + [self.default_permission()]
def get_exception_handler_context(self) -> dict:
"""
Формирование данных для контекста ошибки.
"""
context = super().get_exception_handler_context()
try:
context["user"] = self.get_user()
except Exception as error:
logger.error(msg=str(error))
return context
def _get_param_to_bool(self, name: str, default: str = "false"):
return bool(strtobool(self.request.GET.get(name, default)))
def get_serializer_class(self):
"""
Получение класса сериализтора
"""
# Поддержка облегченных сериализаторов
if getattr(self, "light_serializer_class", None) and self._get_param_to_bool("light"):
return self.light_serializer_class
# Поддержка подробных сериализаторов
if getattr(self, "verbose_serializer_class", None) and self._get_param_to_bool("verbose"):
return self.verbose_serializer_class
# Маппинг между экшенами и сериализаторами
return self.serializer_classes.get(self.action, self.serializer_classes.get("default", self.serializer_class))
def get_serializer(self, *args, **kwargs):
"""
Получение сериализтора
"""
# Если данные передаются на прямую из request.data, то это объект QueryDict, он не изменяем, нужно копировать
if ("data" in kwargs) and isinstance(kwargs["data"], QueryDict):
kwargs["data"] = kwargs["data"].copy()
serializer_class = self.get_serializer_class()
kwargs.setdefault("context", self.get_serializer_context())
return serializer_class(*args, **kwargs)
def validate_filters(self) -> None:
"""
Валидация фильтров запросов
"""
for key in self.required_filters:
if not self.request.GET.get(key):
raise ValidationError({key: _("Обязательный фильтр")})
if self.request.GET.get("limit") and (int(self.request.GET["limit"]) > settings.DRF_LIMIT_FILTER_MAX_VALUE):
raise ValidationError(
{"limit": _("Максимальное значение: {max_value}").format(max_value=settings.DRF_LIMIT_FILTER_MAX_VALUE)}
)
def get_queryset_filter_kwargs(self) -> dict:
return {}
def limit_queryset(self, queryset):
"""
Валидация фильтров при получении списка объектов
"""
if self.action == "list":
self.validate_filters()
return queryset.filter(**self.get_queryset_filter_kwargs())
def get_queryset(self, manager: str = "objects"):
"""
Получение Queryset
"""
if getattr(self, "filterset_class", None) and hasattr(self.filterset_class, "Meta"):
model = self.filterset_class.Meta.model
else:
model = self.get_serializer_class().Meta.model
queryset = getattr(model, manager).all()
if (self.actions_for_filterset_class == "__all__") or (self.action in self.actions_for_filterset_class):
queryset = self.filter_queryset(queryset=queryset)
if not self.no_limit:
# Обязательная фильтрация результатов для рядовых пользователей
queryset = self.limit_queryset(queryset=queryset)
return queryset
@action(detail=False, methods=["GET"])
def count(self, request, *args, **kwargs):
"""
Получение кол-во объектов
"""
return self.build_response(data={"count": self.get_queryset().count()})
def partial_update(self, request, *args, **kwargs):
"""
Запрет на частичное обновление
"""
if not getattr(self, "allow_partial_update", True):
raise MethodNotAllowed(self)
return super().partial_update(request, *args, **kwargs)
def get_client_ip(self):
"""
Получение IP адреса клиента
"""
return get_client_ip(request=self.request)
def validate_captcha(self, token: str, ip: str = None) -> None:
if not ip:
ip = self.get_client_ip()
validate_captcha(token=token, ip=ip) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/views/core.py | core.py |
from decimal import Decimal as D
from zs_utils.unit_converter.units import UnitPrefix, Unit
# ----------
# Prefix SI
# ----------
PREFIXES = {
"y": UnitPrefix(symbol="y", name="yocto", factor=D("1E-24")),
"z": UnitPrefix(symbol="z", name="zepto", factor=D("1E-21")),
"a": UnitPrefix(symbol="a", name="atto", factor=D("1E-18")),
"f": UnitPrefix(symbol="f", name="femto", factor=D("1E-15")),
"p": UnitPrefix(symbol="p", name="pico", factor=D("1E-12")),
"n": UnitPrefix(symbol="n", name="nano", factor=D("1E-9")),
"µ": UnitPrefix(symbol="µ", name="micro", factor=D("1E-6")),
"m": UnitPrefix(symbol="m", name="milli", factor=D("1E-3")),
"c": UnitPrefix(symbol="c", name="centi", factor=D("1E-2")),
"d": UnitPrefix(symbol="d", name="deci", factor=D("1E-1")),
"": UnitPrefix(symbol="", name="", factor=D("1E0")),
"da": UnitPrefix(symbol="da", name="deca", factor=D("1E+1")),
"h": UnitPrefix(symbol="h", name="hecto", factor=D("1E+2")),
"k": UnitPrefix(symbol="k", name="kilo", factor=D("1E+3")),
"M": UnitPrefix(symbol="M", name="mega", factor=D("1E+6")),
"G": UnitPrefix(symbol="G", name="giga", factor=D("1E+9")),
"T": UnitPrefix(symbol="T", name="tera", factor=D("1E+12")),
"P": UnitPrefix(symbol="P", name="peta", factor=D("1E+15")),
"E": UnitPrefix(symbol="E", name="exa", factor=D("1E+18")),
"Z": UnitPrefix(symbol="Z", name="zetta", factor=D("1E+21")),
"Y": UnitPrefix(symbol="Y", name="yotta", factor=D("1E+24")),
}
# ----------
# Units
# ----------
UNITS = {
# Basic SI units
# --------------
"m": Unit("m", "meter", L=1),
"g": Unit("g", "gram", M=1, coef=D("1E-3")),
"s": Unit("s", "second", T=1),
"A": Unit("A", "ampere", I=1),
"K": Unit("K", "kelvin", THETA=1),
"mol": Unit("mol", "mole", N=1),
"cd": Unit("cd", "candela", J=1),
# Derived SI units
# ----------------
"Hz": Unit("Hz", "hertz", T=-1),
"N": Unit("N", "newton", M=1, L=1, T=-2),
"Pa": Unit("Pa", "pascal", M=1, L=-1, T=-2),
"J": Unit("J", "joule", M=1, L=2, T=-2),
"W": Unit("W", "watt", M=1, L=2, T=-3),
"C": Unit("C", "coulomb", T=1, I=1),
"V": Unit("V", "volt", M=1, L=2, T=-3, I=-1),
"Ω": Unit("Ω", "ohm", M=1, L=2, T=-3, I=-2),
"S": Unit("S", "siemens", M=-1, L=-2, T=3, I=2),
"F": Unit("F", "farad", M=-1, L=-2, T=4, I=2),
"T": Unit("T", "tesla", M=1, T=-2, I=-1),
"Wb": Unit("Wb", "weber", M=1, L=2, T=-2, I=-1),
"H": Unit("H", "henry", M=1, L=2, T=-2, I=-2),
"°C": Unit("°C", "celsius", THETA=1, offset=D("273.15")),
"rad": Unit("rad", "radian"),
"sr": Unit("sr", "steradian"),
"lm": Unit("lm", "lumen", J=1),
"lx": Unit("lx", "lux", L=-2, J=1),
"Bq": Unit("Bq", "becquerel", T=-1),
"Gy": Unit("Gy", "gray", L=2, T=-2),
"Sv": Unit("Sv", "sievert", L=2, T=-2),
"kat": Unit("kat", "katal", T=-1, N=1),
# Imperial system
# ---------------
"°F": Unit("°F", "fahrenheit", THETA=1, offset=D("273.15") - D("32") / D("1.8"), coef=D("1") / D("1.8")),
"thou": Unit("th", "thou", L=1, coef=D("2.54E-5")),
"inch": Unit("in", "inch", L=1, coef=D("2.54E-2")),
"foot": Unit("ft", "foot", L=1, coef=D("3.048E-1")),
"yard": Unit("yd", "yard", L=1, coef=D("9.144E-1")),
"chain": Unit("ch", "chain", L=1, coef=D("20.1168")),
"furlong": Unit("fur", "furlong", L=1, coef=D("201.168")),
"mile": Unit("ml", "mile", L=1, coef=D("1609.344")),
"league": Unit("lea", "league", L=1, coef=D("4828.032")),
"oz": Unit("oz", "ounce", M=1, coef=D("2.835E-2")),
"lb": Unit("lb", "pound", M=1, coef=D("4.536E-1")),
# Miscellaneous units
# -------------------
"bar": Unit("bar", "bar", M=1, L=-1, T=-2, coef=D("1E5")),
"min": Unit("min", "minute", T=1, coef=D("60")),
"h": Unit("h", "hour", T=1, coef=D("3600")),
} | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/unit_converter/data.py | data.py |
from decimal import Decimal as D
from zs_utils.unit_converter.exceptions import UnConsistentUnitsError
class UnitPrefix(object):
def __init__(self, symbol, name, factor):
self.symbol = symbol
self.name = name
if isinstance(factor, str):
self.factor = D(factor)
elif isinstance(factor, D):
self.factor = factor
else:
raise TypeError("factor need to be a 'string' or a" " 'decimal.Decimal' class")
def __repr__(self):
return "UnitPrefix(symbol='%s', name='%s', factor='%s')" % (self.symbol, self.name, self.factor)
def is_same_factor(self, other_prefix):
return self.factor == other_prefix.factor
def __eq__(self, other_prefix):
return (
self.symbol == other_prefix.symbol and self.name == other_prefix.name and self.factor == other_prefix.factor
)
def __mul__(self, unit):
if isinstance(unit, Unit):
final_unit = Unit(
symbol=self.symbol + unit.symbol,
name=self.name + unit.name,
L=unit.L,
M=unit.M,
T=unit.T,
I=unit.I,
THETA=unit.THETA,
N=unit.N,
J=unit.J,
coef=self.factor * unit.coef,
offset=unit.offset,
)
return final_unit
else:
raise TypeError("unsupported operand type(s) for : '%s' and '%s'" % (type(self), type(unit)))
class Unit(object):
def __init__(
self, symbol, name, plural_name=None, L=0, M=0, T=0, I=0, THETA=0, N=0, J=0, coef=D("1"), offset=D("0")
):
self.symbol = symbol
self.name = name
self.plural_name = plural_name or name
self.coef = coef
self.offset = offset
# Dimensional quantities
# -----------------------
self.L = L # Length
self.M = M # Mass
self.T = T # Time
self.I = I # Electric current
self.THETA = THETA # Thermodynamic temperature
self.N = N # Amount of substance
self.J = J # Light intensity
def __repr__(self):
# TODO: Add a better representation including coef and offset.
# TODO: Hide plotting 0 dimension
l_units_r = ("m^%s", "kg^%s", "s^%s", "A^%s", "K^%s", "mol^%s", "cd^%s")
units = (self.L, self.M, self.T, self.I, self.THETA, self.N, self.J)
unit_r = [r % units[idx] for idx, r in enumerate(l_units_r) if units[idx]]
return "*".join(unit_r)
def is_same_dimension(self, other_unit):
return (
self.L == other_unit.L
and self.M == other_unit.M
and self.T == other_unit.T
and self.I == other_unit.I
and self.THETA == other_unit.THETA
and self.N == other_unit.N
and self.J == other_unit.J
)
def __eq__(self, other):
return self.is_same_dimension(other) and self.coef == other.coef and self.offset == other.offset
def __mul__(self, other):
if isinstance(other, Unit):
return self.__class__(
symbol=self.symbol + "*" + other.symbol,
name=self.name + "*" + other.name,
L=self.L + other.L,
M=self.M + other.M,
T=self.T + other.T,
I=self.I + other.I,
THETA=self.THETA + other.THETA,
N=self.N + other.N,
J=self.J + other.J,
coef=self.coef * other.coef,
offset=self.offset + other.offset,
)
elif type(other) in (int, float, D):
return Quantity(value=other, unit=self)
else:
raise TypeError("unsupported operand type(s) for : '%s' and '%s'" % (type(self), type(other)))
def __pow__(self, power):
if type(power) in (int, float, D):
if self.offset:
new_offset = self.offset ** D(power)
else:
new_offset = self.offset
final_unit = self.__class__(
symbol=self.symbol + "^" + str(power), # TODO: attention manque des parenthèses etc..
name=self.name + "^" + str(power),
L=self.L * power,
M=self.M * power,
T=self.T * power,
I=self.I * power,
THETA=self.THETA * power,
N=self.N * power,
J=self.J * power,
coef=self.coef ** D(power),
offset=new_offset,
)
return final_unit
else:
raise TypeError("unsupported operand type(s) for : '%s' and '%s'" % (type(self), type(power)))
def __truediv__(self, other):
return self.__pow__(-1)
def __rmul__(self, other):
return self.__mul__(other)
def __rtruediv__(self, other):
return self.__truediv__(other)
class Quantity(object):
def __init__(self, value, unit):
if type(value) in (int, float, D):
self.value = value
else:
raise TypeError("value must be an int, float or decimal class")
if isinstance(unit, Unit):
self.unit = unit
else:
raise TypeError("unit must be an Unit class")
def convert(self, desired_unit: Unit):
# Check dimension from current and desired units
if not desired_unit.is_same_dimension(self.unit):
raise UnConsistentUnitsError(desired_unit.name, self.unit.name)
default_value = self.unit.offset + self.value * self.unit.coef
desired_value = (-desired_unit.offset + default_value) / desired_unit.coef
return self.__class__(value=desired_value, unit=self.unit)
def __repr__(self):
return str(self.value) + " " + str(self.unit)
def __add__(self, other):
if isinstance(other, Quantity):
if self.unit == other.unit:
return self.__class__(self.value + other.value, self.unit)
def __sub__(self, other):
if isinstance(other, Quantity):
if self.unit == other.unit:
return self.__class__(self.value - other.value, self.unit)
def __mul__(self, other):
if isinstance(other, Quantity):
if self.unit == other.unit:
return self.__class__(self.value * other.value, self.unit * other.unit)
def __truediv__(self, other):
if isinstance(other, Quantity):
if self.unit == other.unit:
return self.__class__(self.value / other.value, self.unit / other.unit)
def __radd__(self, other):
return self.__add__(other)
def __rsub__(self, other):
return self.__sub__(other)
def __rmul__(self, other):
return self.__mul__(other)
def __rtruediv__(self, other):
return self.__truediv__(other) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/unit_converter/units.py | units.py |
from model_utils.fields import MonitorField
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin,
)
from django.utils import timezone
from zs_utils.json_utils import CustomJSONEncoder
__all__ = [
"AbstractZonesmartUser",
"CustomUserManager",
]
class CustomUserManager(BaseUserManager):
"""
Менеджер с возможностью создать пользователя
"""
def create_user(
self,
email: str,
password: str,
is_staff: bool = False,
is_superuser: bool = False,
**kwargs,
):
"""
Создать пользователя
"""
user: AbstractZonesmartUser = self.model(email=email, is_staff=is_staff, is_superuser=is_superuser, **kwargs)
user.set_password(password)
user.save()
return user
class AbstractZonesmartUser(AbstractBaseUser, PermissionsMixin):
"""
Данные пользователя
"""
USERNAME_FIELD = "email"
EMAIL_FIELD = "email"
REQUIRED_FIELDS = []
email = models.EmailField(unique=True, verbose_name="E-mail")
first_name = models.CharField(max_length=32, null=True, verbose_name="Имя")
last_name = models.CharField(max_length=32, null=True, verbose_name="Фамилия")
date_joined = models.DateTimeField(default=timezone.now, verbose_name="Дата регистрации")
password_last_modified = MonitorField(monitor="password", verbose_name="Дата последнего изменения пароля")
is_active = models.BooleanField(default=True, verbose_name="Активен")
is_superuser = models.BooleanField(default=False, verbose_name="Супер юзер")
is_staff = models.BooleanField(default=False, verbose_name="Администратор")
extra_data = models.JSONField(
default=dict,
encoder=CustomJSONEncoder,
verbose_name="Дополнительная информация",
)
objects = CustomUserManager()
class Meta:
abstract = True
def __str__(self):
return f"{self.email}"
def set_password(self, raw_password: str, save: bool = False) -> None:
super().set_password(raw_password=raw_password)
self.password_last_modified = timezone.now()
if save:
self.save(update_fields=["password", "password_last_modified"]) | zonesmart-utils | /zonesmart-utils-0.4.5.tar.gz/zonesmart-utils-0.4.5/zs_utils/user/models.py | models.py |
.. image:: .github/images/logo.png
:class: with-border
:width: 1280
=========
zonic
=========
.. image:: https://img.shields.io/pypi/v/zonic.svg
:target: https://pypi.python.org/pypi/zonic
.. image:: https://img.shields.io/travis/symonk/zonic.svg
:target: https://travis-ci.com/symonk/zonic
.. image:: https://readthedocs.org/projects/zonic/badge/?version=latest
:target: https://zonic.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
.. image:: https://pyup.io/repos/github/symonk/zonic/shield.svg
:target: https://pyup.io/repos/github/symonk/zonic/
:alt: Updates
.. image:: https://results.pre-commit.ci/badge/github/symonk/zonic/master.svg
:target: https://results.pre-commit.ci/latest/github/symonk/zonic/master
:alt: pre-commit.ci status
.. image:: https://codecov.io/gh/symonk/zonic/branch/master/graph/badge.svg
:target: https://codecov.io/gh/symonk/zonic
Port scanning made easy with python
* Free software: MIT license
* Documentation: https://zonic.readthedocs.io.
--------
Disclaimer
--------
Do **not** use this against any environment in which you do not have complete, explicit permission to conduct such scanning.
Features
--------
* Simple port scanner
* Extendible through a plugin system
| zonic | /zonic-0.1.7.tar.gz/zonic-0.1.7/README.rst | README.rst |
.. highlight:: shell
============
Contributing
============
Contributions are welcome, and they are greatly appreciated! Every little bit
helps, and credit will always be given.
You can contribute in many ways:
Types of Contributions
----------------------
Report Bugs
~~~~~~~~~~~
Report bugs at https://github.com/symonk/zonic/issues.
If you are reporting a bug, please include:
* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the bug.
Fix Bugs
~~~~~~~~
Look through the GitHub issues for bugs. Anything tagged with "bug" and "help
wanted" is open to whoever wants to implement it.
Implement Features
~~~~~~~~~~~~~~~~~~
Look through the GitHub issues for features. Anything tagged with "enhancement"
and "help wanted" is open to whoever wants to implement it.
Write Documentation
~~~~~~~~~~~~~~~~~~~
zonic could always use more documentation, whether as part of the
official zonic docs, in docstrings, or even on the web in blog posts,
articles, and such.
Submit Feedback
~~~~~~~~~~~~~~~
The best way to send feedback is to file an issue at https://github.com/symonk/zonic/issues.
If you are proposing a feature:
* Explain in detail how it would work.
* Keep the scope as narrow as possible, to make it easier to implement.
* Remember that this is a volunteer-driven project, and that contributions
are welcome :)
Get Started!
------------
Ready to contribute? Here's how to set up `zonic` for local development.
1. Fork the `zonic` repo on GitHub.
2. Clone your fork locally::
$ git clone [email protected]:your_name_here/zonic.git
3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development::
$ mkvirtualenv zonic
$ cd zonic/
$ python setup.py develop
4. Create a branch for local development::
$ git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
5. When you're done making changes, check that your changes pass flake8 and the
tests, including testing other Python versions with tox::
$ flake8 zonic tests
$ python setup.py test or pytest
$ tox
To get flake8 and tox, just pip install them into your virtualenv.
6. Commit your changes and push your branch to GitHub::
$ git add .
$ git commit -m "Your detailed description of your changes."
$ git push origin name-of-your-bugfix-or-feature
7. Submit a pull request through the GitHub website.
Pull Request Guidelines
-----------------------
Before you submit a pull request, check that it meets these guidelines:
1. The pull request should include tests.
2. If the pull request adds functionality, the docs should be updated. Put
your new functionality into a function with a docstring, and add the
feature to the list in README.rst.
3. The pull request should work for Python 3.5, 3.6, 3.7 and 3.8, and for PyPy. Check
https://travis-ci.com/symonk/zonic/pull_requests
and make sure that the tests pass for all supported Python versions.
Tips
----
To run a subset of tests::
$ pytest tests.test_zonic
Deploying
---------
A reminder for the maintainers on how to deploy.
Make sure all your changes are committed (including an entry in HISTORY.rst).
Then run::
$ bump2version patch # possible: major / minor / patch
$ git push
$ git push --tags
Travis will then deploy to PyPI if tests pass.
| zonic | /zonic-0.1.7.tar.gz/zonic-0.1.7/CONTRIBUTING.rst | CONTRIBUTING.rst |
# DATS6450-final-project
This package contains different machine learning models for prediction of zoo animals based on a given set of features.
Machine Learning Models Used:
* Decision Tree
* Random Forest
* Support Vector Machine
## Installation
You can install `animal_classification` following the below steps:
`# git clone https://github.com/yijiaceline/CSF-project.git`
`# cd CSF-project`
`# python3 setup.py install`
## Usage
Refer to example.py
## Example Output
`Fitting and predicting using Decision Tree Model:`
`Accuracy:0.9523809523809523`
`Fitting and predicting using Random Forest Model:`
`Accuracy: 1.0`
`Fitting and predicting using Support Vector Machine:`
`Accuracy: 1.0`
`Fitting and predicting using KNN:`
`Accuracy: 0.9047619047619048`
## License
The MIT License. Refer to LICENSE.
| zoo-animal-classification | /zoo_animal_classification-1.0.0.tar.gz/zoo_animal_classification-1.0.0/README.md | README.md |
import logging
from kazoo.client import KazooClient, KazooState
import os
from datetime import datetime
import time
import re
def fullpath(func):
def wrapper(self, path, *args):
fullpath = self.prefix_path + path \
if path else self.prefix_path
return func(self, fullpath, *args)
return wrapper
class ZkOpers(object):
def __init__(self, hosts='127.0.0.1:2181'):
self.zk = KazooClient(hosts=hosts, timeout=20)
self.zk.add_listener(self.listener)
self.zk.start()
print('instance zk client (%s)' % hosts)
self.prefix_path = '/'
def close(self):
try:
self.zk.stop()
self.zk.close()
except Exception as e:
logging.error(e)
def stop(self):
try:
self.zk.stop()
except Exception as e:
logging.error(e)
raise
def listener(self, state):
if state == KazooState.LOST:
print("zk connect lost, stop this "
"connection and then start new one!")
elif state == KazooState.SUSPENDED:
print("zk connect suspended, stop this "
"connection and then start new one!")
else:
pass
@fullpath
def get_extra_info(self, path):
value, stat = self.zk.get(path)
mtime = int(stat.mtime)/1000
timeA = time.localtime(mtime)
len_val = 0 if not value else len(value)
time_str = time.strftime('%Y-%m-%d %H:%M:%S', timeA)
return '%s%10d' %(time_str,len_val)
@fullpath
def ls(self, path=None, *args):
return self.zk.get_children(path)
def _relative_path_cd(self, path):
_pathlist = self.prefix_path.split('/')
list(map(lambda x: _pathlist.pop() if x == '..' \
else _pathlist.append(x),
list(filter(lambda x:x, path.split('/')))))
prefix_path = '/'.join(_pathlist).replace('//','/')
return prefix_path
def cd(self, path=None):
if not path:
return
_prefix_path = path if path.startswith('/') else \
self._relative_path_cd(path)
if self.zk.exists(_prefix_path):
self.prefix_path = _prefix_path
else:
print("unkown path")
return self.prefix_path
def pwd(self):
return self.prefix_path
def recursion_cat(self, path):
relative_path = path[len(self.prefix_path):]
tmp_paths = relative_path.split('/')
paths = list(filter(lambda x:x, tmp_paths))
layer_num = len(paths)
prefixes = [self.prefix_path]
i, values = 0, []
while i < layer_num:
for prefix in prefixes:
paths_pool = self.zk.get_children(prefix)
paths_selects = list(filter(lambda x:re.search(paths[i], x),
paths_pool))
next_prefixes = []
for p in paths_selects:
full_path = os.path.join(prefix, p)
next_prefixes.append(full_path)
prefixes = next_prefixes
i += 1
for p in prefixes:
value, _ = self.zk.get(p)
values.append("--%s:\n%s" %(p, value))
return '\n'.join(values)
@fullpath
def cat(self, path=None, *args):
if self.zk.exists(path):
value, _ = self.zk.get(path)
else:
value = self.recursion_cat(path)
return value
@fullpath
def set(self, path, value, *args):
return self.zk.set(path, value.encode('utf-8'))
@fullpath
def touch(self, filename, *args):
return self.zk.create(filename)
@fullpath
def rm(self, filename, *args):
return self.zk.delete(filename, recursive=True)
@fullpath
def vi(self, path=None, *args):
value, _ = self.zk.get(path)
# create a tmp file to store the value, then use vi to
# modify this file. At the end, save the file, get the
# new value, and restore the value to the zookeeper node
filename = '%s_%d.tmp' % (path.split('/')[-1],
time.mktime(datetime.now().timetuple()))
tmpfile = open(filename, 'w')
if value:
tmpfile.write(value)
tmpfile.close()
try:
os.system('vi %s' % filename)
except:
print("error occur in edit")
return
tmpfile = open(filename, 'r')
lines = tmpfile.read().strip('\n')
self.zk.set(path, lines)
tmpfile.close()
os.remove(filename)
print("edit ok") | zoo-cmd | /zoo_cmd-1.1.0-py3-none-any.whl/zoo_cmd/zk/zk_opers.py | zk_opers.py |
import json
import sys
import click
import os
import jinja2
from jinja2 import Environment, PackageLoader, Template
from zoo_framework.templates import worker_template, main_template, worker_mod_insert_template
DEFAULT_CONF = {
"_exports": [],
"log": {
"path": "./logs",
"level": "debug"
},
"worker": {
"runPolicy": "simple",
"pool": {
"size": 5,
"enabled": False
}
}
}
def create_func(object_name):
if os.path.exists(object_name):
return
os.mkdir(object_name)
src_dir = object_name + '/src'
conf_dir = src_dir + "/conf"
params_dir = src_dir + "/params"
main_file = src_dir + "/main.py"
events_dir = src_dir + "/events"
workers_dir = src_dir + "/workers"
config_file = object_name + "/config.json"
threads_init_file = workers_dir + "/__init__.py"
config_init_file = conf_dir + "/__init__.py"
events_init_file = events_dir + "/__init__.py"
params_init_file = params_dir + "/__init__.py"
os.mkdir(src_dir)
os.mkdir(conf_dir)
os.mkdir(workers_dir)
os.mkdir(params_dir)
os.mkdir(events_dir)
# os.mkdir(events_dir)
with open(config_file, "w") as fp:
json.dump(DEFAULT_CONF, fp)
with open(main_file, "w") as fp:
fp.write(main_template)
with open(threads_init_file, "w") as fp:
fp.write("")
with open(config_init_file, "w") as fp:
fp.write("")
with open(events_init_file, "w") as fp:
fp.write("")
with open(params_init_file, "w") as fp:
fp.write("")
# create main.py
def worker_func(worker_name):
# 创建文件夹
src_dir = "./workers"
if str(sys.argv[0]).endswith("/src"):
src_dir = "./src/workers"
file_path = src_dir + "/" + worker_name + "_worker.py"
workers_init_file = src_dir + "/__init__.py"
template = Template(worker_mod_insert_template)
content = template.render(worker_name=worker_name)
if not os.path.exists(src_dir):
os.mkdir(src_dir)
with open(workers_init_file, "w") as fp:
fp.write(content)
elif os.path.exists(workers_init_file):
with open(workers_init_file, "a") as fp:
fp.write(content)
template = Template(worker_template)
content = template.render(worker_name=worker_name) # 渲染
with open(file_path, "w") as fp:
fp.write(content)
@click.command()
@click.option("--create", help="Input target object name and create it")
@click.option("--worker", help="Input new worker name and create it")
@click.option("--config", help="Input new config file name and create it")
def zfc(create, worker, config):
if create is not None:
create_func(create)
if worker is not None:
worker_func(str(worker).lower())
if __name__ == '__main__':
zfc() | zoo-framework | /zoo-framework-0.4.2.tar.gz/zoo-framework-0.4.2/zoo_framework/__main__.py | __main__.py |
import time
from zoo_framework.constant import WaiterConstant
from zoo_framework.handler.event_reactor import EventReactor
from zoo_framework.constant import WorkerConstant
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import ProcessPoolExecutor
from zoo_framework.handler.waiter_result_handler import WaiterResultHandler
from zoo_framework.workers import BaseWorker
from multiprocessing import Pool
class BaseWaiter(object):
_lock = None
def __init__(self):
from zoo_framework.params import WorkerParams
# 获得模式
self.worker_mode, self.pool_enable = self.get_worker_mode(WorkerParams.WORKER_POOL_ENABLE)
# 获得资源池的大小
self.pool_size = WorkerParams.WORKER_POOL_SIZE
# 资源池初始化
self.resource_pool = None
self.workers = []
self.worker_props = {}
self.register_handler()
def get_worker_mode(self, pool_enable):
if pool_enable:
return WaiterConstant.WORKER_MODE_THREAD_POOL, pool_enable
else:
return WaiterConstant.WORKER_MODE_THREAD, pool_enable
def register_handler(self):
from zoo_framework.handler.event_reactor import EventReactor
EventReactor().register("waiter", WaiterResultHandler())
def init_lock(self):
pass
# 集结worker们
def call_workers(self, worker_list):
self.workers = worker_list
# 生成池或者列表
if self.worker_mode == WaiterConstant.WORKER_MODE_THREAD_POOL:
self.resource_pool = ThreadPoolExecutor(max_workers=self.pool_size)
def __del__(self):
if self.resource_pool is not None:
self.resource_pool.shutdown(wait=True)
# 执行服务
def execute_service(self):
workers = []
for worker in self.workers:
self.worker_band(worker.name)
if worker is None:
continue
if worker.is_loop:
workers.append(worker)
# 判定是否超时
self.worker_band(worker.name)
if self.worker_props.get(worker.name) is None:
self._dispatch_worker(worker)
self.workers = workers
def _dispatch_worker(self, worker):
'''
派遣 worker
:param worker:
:return:
'''
if self.worker_mode is WaiterConstant.WORKER_MODE_THREAD_POOL:
t = self.resource_pool.submit(self.worker_running, worker, self.worker_running_callback)
t.add_done_callback(self.worker_report)
self.register_worker(worker, t)
elif self.worker_mode is WaiterConstant.WORKER_MODE_THREAD:
from threading import Thread
t = Thread(target=self.worker_running, args=(worker, self.worker_running_callback))
t.start()
self.register_worker(worker, t)
def worker_band(self, worker_name):
# 根据模式
worker_prop = self.worker_props.get(worker_name)
if worker_prop is None:
return
worker = worker_prop.get("worker")
run_time = worker_prop.get("run_time")
run_timeout = worker_prop.get("run_timeout")
container = worker_prop.get("container")
now_time = time.time()
if run_timeout is None or run_timeout <= 0:
return
if (now_time - run_time) < run_timeout:
return
#
# if self.worker_mode is WaiterConstant.WORKER_MODE_THREAD_POOL:
# if container.cancel() is False:
# return
# elif self.worker_mode is WaiterConstant.WORKER_MODE_THREAD:
# container.kill()
#
# self.unregister_worker(worker)
def register_worker(self, worker, worker_container):
'''
register the worker to self.worker_props
:param worker: worker
:param worker_container: worker running thread or process
:return:
'''
self.worker_props[worker.name] = {
"worker": worker,
"run_time": time.time(),
"run_timeout": worker.run_timeout,
"container": worker_container
}
def unregister_worker(self, worker):
if self.worker_props.get(worker.name) is not None:
del self.worker_props[worker.name]
def worker_running_callback(self, worker):
self.unregister_worker(worker)
# 派遣worker
def worker_running(self, worker, callback=None):
if not isinstance(worker, BaseWorker):
return
result = worker.run()
if callback is not None:
callback(worker)
return result
# worker汇报结果
@staticmethod
def worker_report(worker):
result = worker.result()
EventReactor().dispatch(result.topic, result.content) | zoo-framework | /zoo-framework-0.4.2.tar.gz/zoo-framework-0.4.2/zoo_framework/core/waiter/base_waiter.py | base_waiter.py |
zooboss
=======
This is an application to organize all the malwares in a unorganized collection. With zooboss you will not need a web server or another type of running daemon, just run the zooboss and drink a coffee while it did his job.
# Parameters
`--origin` : The path to be scanned
`--destiny` : The destiny path to store files
`--move` : Determines that the origin file must be moved
`--filetype` : Determines that the destiny will use the file type
`--threads` : The number of threads
# Examples
The example bellow will scan the `/tmp/downloaded_files` using 10 threads to move the files to the samples directory inside the `$HOME` directory.
```
$ python zooboss.py --origin /tmp/downloaded_files --destiny ~/samples -threads 10 --move
```
To create a copy (not move) don't use the `--move` parameter
```
$ python zooboss.py --origin /tmp/downloaded_files --destiny ~/samples -threads 10
```
To organize files and separating using the file type use the parameter `--filetype` :
```
$ python zooboss.py --origin /tmp/downloaded_files --destiny ~/samples -threads 10 --move --filetype
``` | zooboss | /zooboss-0.1.0.tar.gz/zooboss-0.1.0/README.md | README.md |
# Zoobot
[](https://pepy.tech/project/zoobot)
[](https://zoobot.readthedocs.io/)


[](https://badge.fury.io/py/zoobot)
[](https://zenodo.org/badge/latestdoi/343787617)
<a href="https://ascl.net/2203.027"><img src="https://img.shields.io/badge/ascl-2203.027-blue.svg?colorB=262255" alt="ascl:2203.027" /></a>
Zoobot classifies galaxy morphology with deep learning.
<!-- At Galaxy Zoo, we use Zoobot to help our volunteers classify the galaxies in all our recent catalogues: GZ DECaLS, GZ DESI, GZ Rings and GZ Cosmic Dawn. -->
Zoobot is trained using millions of answers by Galaxy Zoo volunteers. This code will let you **retrain** Zoobot to accurately solve your own prediction task.
- [Install](#installation)
- [Quickstart](#quickstart)
- [Worked Examples](#worked-examples)
- [Pretrained Weights](https://zoobot.readthedocs.io/data_notes.html)
- [Datasets](https://www.github.com/mwalmsley/galaxy-datasets)
- [Documentation](https://zoobot.readthedocs.io/) (for understanding/reference)
## Installation
<a name="installation"></a>
You can retrain Zoobot in the cloud with a free GPU using this [Google Colab notebook](https://colab.research.google.com/drive/17bb_KbA2J6yrIm4p4Ue_lEBHMNC1I9Jd?usp=sharing). To install locally, keep reading.
Download the code using git:
git clone [email protected]:mwalmsley/zoobot.git
And then pick one of the three commands below to install Zoobot and either PyTorch (recommended) or TensorFlow:
# Zoobot with PyTorch and a GPU. Requires CUDA 11.3.
pip install -e "zoobot[pytorch_cu113]" --extra-index-url https://download.pytorch.org/whl/cu113
# OR Zoobot with PyTorch and no GPU
pip install -e "zoobot[pytorch_cpu]" --extra-index-url https://download.pytorch.org/whl/cpu
# OR Zoobot with PyTorch on Mac with M1 chip
pip install -e "zoobot[pytorch_m1]"
# OR Zoobot with TensorFlow. Works with and without a GPU, but if you have a GPU, you need CUDA 11.2.
pip install -e "zoobot[tensorflow]
This installs the downloaded Zoobot code using pip [editable mode](https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs) so you can easily change the code locally. Zoobot is also available directly from pip (`pip install zoobot[option]`). Only use this if you are sure you won't be making changes to Zoobot itself. For Google Colab, use `pip install zoobot[pytorch_colab]`
To use a GPU, you must *already* have CUDA installed and matching the versions above.
I share my install steps [here](#install_cuda). GPUs are optional - Zoobot will run retrain fine on CPU, just slower.
## Quickstart
<a name="quickstart"></a>
The [Colab notebook](https://colab.research.google.com/drive/17bb_KbA2J6yrIm4p4Ue_lEBHMNC1I9Jd?usp=sharing) is the quickest way to get started. Alternatively, the minimal example below illustrates how Zoobot works.
Let's say you want to find ringed galaxies and you have a small labelled dataset of 500 ringed or not-ringed galaxies. You can retrain Zoobot to find rings like so:
```python
import pandas as pd
from galaxy_datasets.pytorch.galaxy_datamodule import GalaxyDataModule
from zoobot.pytorch.training import finetune
# csv with 'ring' column (0 or 1) and 'file_loc' column (path to image)
labelled_df = pd.read_csv('/your/path/some_labelled_galaxies.csv')
datamodule = GalaxyDataModule(
label_cols=['ring'],
catalog=labelled_df,
batch_size=32
)
# load trained Zoobot model
model = finetune.FinetuneableZoobotClassifier(checkpoint_loc, num_classes=2)
# retrain to find rings
trainer = finetune.get_trainer(save_dir)
trainer.fit(model, datamodule)
```
Then you can make predict if new galaxies have rings:
```python
from zoobot.pytorch.predictions import predict_on_catalog
# csv with 'file_loc' column (path to image). Zoobot will predict the labels.
unlabelled_df = pd.read_csv('/your/path/some_unlabelled_galaxies.csv')
predict_on_catalog.predict(
unlabelled_df,
model,
label_cols=['ring'], # only used for
save_loc='/your/path/finetuned_predictions.csv'
)
```
Zoobot includes many guides and working examples - see the [Getting Started](#getting-started) section below.
## Getting Started
<a name="getting_started"></a>
I suggest starting with the [Colab notebook](https://colab.research.google.com/drive/17bb_KbA2J6yrIm4p4Ue_lEBHMNC1I9Jd?usp=sharing) or the worked examples below, which you can copy and adapt.
For context and explanation, see the [documentation](https://zoobot.readthedocs.io/).
For pretrained model weights, precalculated representations, catalogues, and so forth, see the [data notes](https://zoobot.readthedocs.io/data_notes.html) in particular.
### Worked Examples
<a name="worked_examples"></a>
PyTorch (recommended):
- [pytorch/examples/finetuning/finetune_binary_classification.py](https://github.com/mwalmsley/zoobot/blob/main/zoobot/pytorch/examples/finetuning/finetune_binary_classification.py)
- [pytorch/examples/finetuning/finetune_counts_full_tree.py](https://github.com/mwalmsley/zoobot/blob/main/zoobot/pytorch/examples/finetuning/finetune_counts_full_tree.py)
- [pytorch/examples/representations/get_representations.py](https://github.com/mwalmsley/zoobot/blob/main/zoobot/pytorch/examples/representations/get_representations.py)
- [pytorch/examples/train_model_on_catalog.py](https://github.com/mwalmsley/zoobot/blob/main/zoobot/pytorch/examples/train_model_on_catalog.py) (only necessary to train from scratch)
TensorFlow:
- [tensorflow/examples/train_model_on_catalog.py](https://github.com/mwalmsley/zoobot/blob/main/zoobot/tensorflow/examples/train_model_on_catalog.py) (only necessary to train from scratch)
- [tensorflow/examples/make_predictions.py](https://github.com/mwalmsley/zoobot/blob/main/zoobot/tensorflow/examples/make_predictions.py)
- [tensorflow/examples/finetune_minimal.py](https://github.com/mwalmsley/zoobot/blob/main/zoobot/tensorflow/examples/finetune_minimal.py)
- [tensorflow/examples/finetune_advanced.py](https://github.com/mwalmsley/zoobot/blob/main/zoobot/tensorflow/examples/finetune_advanced.py)
There is more explanation and an API reference on the [docs](https://zoobot.readthedocs.io/).
I also [include](https://github.com/mwalmsley/zoobot/blob/main/benchmarks) the scripts used to create and benchmark our pretrained models. Many pretrained models are available [already](https://zoobot.readthedocs.io/data_notes.html), but if you need one trained on e.g. different input image sizes or with a specific architecture, I can probably make it for you.
When trained with a decision tree head (ZoobotTree, FinetuneableZoobotTree), Zoobot can learn from volunteer labels of varying confidence and predict posteriors for what the typical volunteer might say. Specifically, this Zoobot mode predicts the parameters for distributions, not simple class labels! For a demonstration of how to interpret these predictions, see the [gz_decals_data_release_analysis_demo.ipynb](https://github.com/mwalmsley/zoobot/blob/main/gz_decals_data_release_analysis_demo.ipynb).
### (Optional) Install PyTorch or TensorFlow, with CUDA
<a name="install_cuda"></a>
*If you're not using a GPU, skip this step. Use the pytorch_cpu or tensorflow_cpu options in the section below.*
Install PyTorch 1.12.1 or Tensorflow 2.10.0 and compatible CUDA drivers. I highly recommend using [conda](https://docs.conda.io/en/latest/miniconda.html) to do this. Conda will handle both creating a new virtual environment (`conda create`) and installing CUDA (`cudatoolkit`, `cudnn`)
CUDA 11.3 for PyTorch:
conda create --name zoobot38_torch python==3.8
conda activate zoobot38_torch
conda install -c conda-forge cudatoolkit=11.3
CUDA 11.2 and CUDNN 8.1 for TensorFlow 2.10.0:
conda create --name zoobot38_tf python==3.8
conda activate zoobot38_tf
conda install -c conda-forge cudatoolkit=11.2 cudnn=8.1.0
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib/ # add this environment variable
### Latest features (v1.0.0)
v1.0.0 recognises that most of the complexity in this repo is training Zoobot from scratch, but most non-GZ users will probably simply want to load the pretrained Zoobot and finetune it on their data.
- Adds new finetuning interface (`finetune.run_finetuning()`), examples.
- Refocuses docs on finetuning rather than training from scratch.
- Rework installation process to separate CUDA from Zoobot (simpler, easier)
- Better wandb logging throughout, to monitor training
- Remove need to make TFRecords. Now TF directly uses images.
- Refactor out augmentations and datasets to `galaxy-datasets` repo. TF and Torch now use identical augmentations (via albumentations).
- Many small quality-of-life improvements
Contributions are very welcome and will be credited in any future work. Please get in touch! See [CONTRIBUTING.md](https://github.com/mwalmsley/zoobot/blob/main/benchmarks) for more.
### Benchmarks and Replication - Training from Scratch
The [benchmarks](https://github.com/mwalmsley/zoobot/blob/main/benchmarks) folder contains slurm and Python scripts to train Zoobot from scratch. We use these scripts to make sure new code versions work well, and that TensorFlow and PyTorch achieve similar performance.
Training Zoobot using the GZ DECaLS dataset option will create models very similar to those used for the GZ DECaLS catalogue and shared with the early versions of this repo. The GZ DESI Zoobot model is trained on additional data (GZD-1, GZD-2), as the GZ Evo Zoobot model (GZD-1/2/5, Hubble, Candels, GZ2).
### Citing
We have submitted a JOSS paper to describe Zoobot itself.
We hope this will become the single point-of-reference for Zoobot.
Meanwhile, please cite the [Galaxy Zoo DECaLS](https://arxiv.org/abs/2102.08414), which uses the code that evolved into Zoobot:
@article{Walmsley2022decals,
author = {Mike Walmsley and Chris Lintott and Geron Tobias and Sandor J Kruk and Coleman Krawczyk and Kyle Willett and Steven Bamford and William Keel and Lee S Kelvin and Lucy Fortson and Karen Masters and Vihang Mehta and Brooke Simmons and Rebecca J Smethurst and Elisabeth M L Baeten and Christine Macmillan},
issue = {3},
journal = {Monthly Notices of the Royal Astronomical Society},
month = {12},
pages = {3966-3988},
title = {Galaxy Zoo DECaLS: Detailed Visual Morphology Measurements from Volunteers and Deep Learning for 314,000 Galaxies},
volume = {509},
url = {https://arxiv.org/abs/2102.08414},
year = {2022},
}
You might be interested in reading papers using Zoobot:
- [Galaxy Zoo DECaLS](https://arxiv.org/abs/2102.08414) (first use at Galaxy Zoo)
- [A Comparison of Deep Learning Architectures for Optical Galaxy Morphology Classification](https://arxiv.org/abs/2111.04353)
- [Practical Galaxy Morphology Tools from Deep Supervised Representation Learning](https://arxiv.org/abs/2110.12735)
- [Towards Foundation Models for Galaxy Morphology](https://arxiv.org/abs/2206.11927) (adding contrastive learning)
- [Harnessing the Hubble Space Telescope Archives: A Catalogue of 21,926 Interacting Galaxies](https://arxiv.org/abs/2303.00366)
Many other works use Zoobot indirectly via the [Galaxy Zoo DECaLS](https://arxiv.org/abs/2102.08414) catalog.
| zoobot | /zoobot-1.0.3.tar.gz/zoobot-1.0.3/README.md | README.md |
Zoodle - command-line query tool for Moodle
===========================================
Zoodle is a command-line query tool for the Moodle LMS that queries
class lists on a remote moodle server from the command line.
What can Zoodle be used for?
----------------------------
Zoodle was originally designed to pull student lists from Moodle in a way that could be automated and/or scheduled.
In other words, I needed a utility that could be invoked from cron and pull down the current student list from Moodle each morning, rendering it as plaintext and sending it to the print spooler.
The included templates are all plaintext, however since the templating is done using Jinja2, rendering the student list as HTML would be straightforward.
Furthermore, using Apache FOP or LaTeX would allow for PDF generation.
Installing zoodle
-----------------
Zoodle is a pure python package, but runs only on Python 3.5.
Pip is required.
::
pip install zoodle
Alternatively you can clone the source and install zoodle using
::
setup.py install
It will make the necessary script link so that zoodle can be run from
the command line.
Using Zoodle
------------
Zoodle functions like the git command, where a single wrapper runs a number of possible subcommands.
To list them just type:
::
zoodle --help
Credential check
----------------
Before using Zoodle, you should verify that your credentials can login, by running:
::
zoodle checklogin -u <your_username> -b https://your.moodle
- Base URL can be determined by looking at your login page's URL. If
your login page is https://your.moodle/login/index.php, the --baseurl
should be set to https://your.moodle without the trailing slash.
- Your username and password are those used normally to login to
Moodle.
- Username and Password will be asked for, or can be supplied with the -u/-username and/or -p/--password options.
If supplying passwords on the command line, be aware that they probably will remain in your command-line history.
- For scripting purposes, you can disable any prompting with the -n/--noninteractive argument. This will cause missing parameters to raise an error.
Class list report
-----------------
Zoodle's main feature is the class list report, which can be invoked as follows:
::
zoodle userlist -u <your_username> -baseurl https://your.moodle <course_id>
More information about the command-line parameters
- course\_id is the numerical course ID that can be found in the
location bar when viewing the main page of your chosen course.
- By default, the list of names is printed direct to the screen. There are two additional available templates in the templates directory as shipped: classlist.txt and signinsheet.txt, using jinja2.
This command will then output all enrolled users on the course to the
stdout.
Configuration file
------------------
Using the command switch
::
--configfile config.ini
you can instead specify any of the baseurl, username or password options in the file:
::
[DEFAULT]
baseurl=base.url
username=your.username
password=your.password
Obviously, if you're storing passwords, you should chmod the file as appropriate.
Multiple profiles can be stored using the --profile switch to select the desired one, which may be useful if you teach in multiple colleges or use separate moodle servers.
The DEFAULT profile (if present) will be used to "fill in" any parameters that are not specified in the others.
::
[DEFAULT]
baseurl=base.url
username=your.username
password=your.password
[training]
baseurl=trainingserver.base.url
[other.college.cz]
baseurl=other.base.url
username=other.username
password=other.password
In the above example, the base URL would be overridden in [training] but would inherit the username/password.
The [other.college.cz] section overrides all.
Filtering by group and/or role
------------------------------
You can filter by group and/or role by using the groupid/roleid command switch, as in the example:
::
--groupid 3859 --roleid 5
Note that the group ID is the group/role's **id number**, NOT the corresponding name.
You can determine this by doing a manual filter in the usual way and noting the filtergroup or role URL parameter.
The default templates will display the group's name when this option is used.
Custom templates
----------------
Zoodle supports custom templates using the Jinja2 templating engine.
To use custom templates, use the --templatesdir option to point to your own directory:
::
--templatesdir my_templates
The templates included with the application give a reasonable starting point for further customisation.
Contributions
-------------
Contributions are most welcome by way of pull requests.
| zoodle | /zoodle-1.1.7.tar.gz/zoodle-1.1.7/README.rst | README.rst |
import json
import os
import sys
import click
from kazoo.client import KazooClient, KazooState
from kazoo.exceptions import KazooException
@click.group()
def cli():
pass
def zk_listener(state):
if state == KazooState.LOST:
click.echo("Connection to zookeeper has been dropped.")
elif state == KazooState.SUSPENDED:
click.echo(click.style('Connection to zookeeper has been suspended.', fg='red'))
elif state == KazooState.CONNECTED:
click.echo(click.style("Successfully connected to zookeeper host.", fg='green'))
else:
click.echo(click.style('Unexpected zookeeper connection state.', fg='red'))
@click.command()
@click.option('-s', '--server', type=str, required=True, help='zookeeper host')
@click.option('-p', '--port', type=int, default='2181', help='zookeeper port, by default it is 2181')
@click.option('-b', '--branch', type=str, default='', help='root branch for reading, default behaviour is to read everything from root')
@click.option('-e', '--exclude', type=str, default='', help='comma-separated list of branches to exclude, default behaviour is not to exclude branches')
def dump(server, port, branch, exclude):
"""Dumps zookeeper nodes and their values to json file."""
def get_nodes(zk, path, dic, exclude):
children = zk.get_children(path=path)
click.echo(f"Current node: {path}")
for child in children:
child_path = path + "/" + child
if child_path not in exclude:
data, stat = zk.get(child_path)
dic[child_path] = data.decode('utf-8') if data is not None else None
if stat.numChildren > 0:
get_nodes(zk, child_path, dic, exclude)
result = {}
zk = KazooClient(hosts=f"{server}:{port}", read_only=True)
zk.add_listener(zk_listener)
zk.start()
get_nodes(zk, branch, result, exclude)
zk.stop()
with open(f"{server}.zk.json", "w") as f:
f.write(json.dumps(result, sort_keys=True, indent=4,
separators=(',', ': ')))
click.echo(click.style(f"{len(result)} nodes succesfully stored in file {os.getcwd()}{os.sep}{server}.zk.json", fg='green'))
@click.command()
@click.option('-s', '--server', type=str, required=True, help='zookeeper host')
@click.option('-p', '--port', type=int, default='2181', help='zookeeper port, by default it is 2181')
@click.option('-f', '--dump_file', type=str, required=True, help='dump file, created when executed dump command')
def load(server, port, dump_file):
"""Loads zookeeper nodes and their values from dump file. If node exists - it's value will be updated, if doesn't exist - will be created."""
failed_nodes = []
zk = KazooClient(hosts=f"{server}:{port}")
zk.add_listener(zk_listener)
try:
with open(dump_file, 'r') as dump:
nodes = json.loads(dump.read())
click.echo(click.style(f"{len(nodes)} nodes read from dump file.", fg='green'))
zk.start()
for node in nodes:
try:
node_value = bytes(nodes[node], encoding='utf-8') if nodes[node] is not None else None
if not zk.exists(node):
click.echo(f"Creating node: {node}")
zk.create(node, node_value, makepath=True)
else:
click.echo(f"Updating value of node: {node}")
zk.set(node, node_value)
except KazooException:
failed_nodes.append(node)
click.echo(click.style(f"Error when creating node {node}: {sys.exc_info()[0]} - {sys.exc_info()[1]}", fg='red'))
zk.stop()
if len(failed_nodes) > 0:
click.echo(click.style(f"Following nodes were not created on host {server} ({len(failed_nodes)} of {len(nodes)}): {failed_nodes}", fg='red'))
exit(1)
else:
click.echo(click.style(f"{len(nodes)} nodes were successfully created on host {server}", fg='green'))
except IOError as e:
click.echo(click.style(f"I/O error({e.errno}): {e.strerror}", fg='red'))
cli.add_command(dump)
cli.add_command(load) | zoodumper | /zoodumper-0.1-py3-none-any.whl/zoodumper.py | zoodumper.py |

<div align="center">
<h1> 🐾 zoofs ( Zoo Feature Selection ) </h1>
[](https://sonarcloud.io/dashboard?id=jaswinder9051998_zoofs) [](https://sonarcloud.io/dashboard?id=jaswinder9051998_zoofs) [](https://sonarcloud.io/dashboard?id=jaswinder9051998_zoofs) [](https://sonarcloud.io/dashboard?id=jaswinder9051998_zoofs) [](https://doi.org/10.5281/zenodo.5638846) [](https://badge.fury.io/py/zoofs) [](https://pepy.tech/project/zoofs) [](https://codecov.io/gh/jaswinder9051998/zoofs) [](https://colab.research.google.com/drive/12LYc67hIuy7PKSa8J_75bQUZ62EBJz4J?usp=sharing) [](https://mybinder.org/v2/gh/jaswinder9051998/zoofs/HEAD) [](https://gitter.im/zooFeatureSelection/community)
</div>
``zoofs`` is a Python library for performing feature selection using a variety of nature inspired wrapper algorithms. The algorithms range from swarm-intelligence to physics based to Evolutionary.
It's an easy to use, flexible and powerful tool to reduce your feature size.
🌟 Like this Project? Give us a star !
## 📘 Documentation
https://jaswinder9051998.github.io/zoofs/
## 🔗 Whats new in V0.1.24
- pass kwargs through objective function
- improved logger for results
- added harris hawk algorithm
- now you can pass ``timeout`` as a parameter to stop operation after the given number of second(s). An amazing alternative to passing number of iterations
- Feature score hashing of visited feature sets to increase the overall performance
## 🛠 Installation
### Using pip
Use the package manager to install zoofs.
```bash
pip install zoofs
```
## 📜 Available Algorithms
| Algorithm Name | Class Name | Description | References doi |
|----------|-------------|-------------|-------------|
| Particle Swarm Algorithm | ParticleSwarmOptimization | Utilizes swarm behaviour | [https://doi.org/10.1007/978-3-319-13563-2_51](https://doi.org/10.1007/978-3-319-13563-2_51) |
| Grey Wolf Algorithm | GreyWolfOptimization | Utilizes wolf hunting behaviour | [https://doi.org/10.1016/j.neucom.2015.06.083](https://doi.org/10.1016/j.neucom.2015.06.083) |
| Dragon Fly Algorithm | DragonFlyOptimization | Utilizes dragonfly swarm behaviour | [https://doi.org/10.1016/j.knosys.2020.106131](https://doi.org/10.1016/j.knosys.2020.106131) |
| Harris Hawk Algorithm | HarrisHawkOptimization | Utilizes hawk hunting behaviour | [https://link.springer.com/chapter/10.1007/978-981-32-9990-0_12](https://link.springer.com/chapter/10.1007/978-981-32-9990-0_12) |
| Genetic Algorithm Algorithm | GeneticOptimization | Utilizes genetic mutation behaviour | [https://doi.org/10.1109/ICDAR.2001.953980](https://doi.org/10.1109/ICDAR.2001.953980) |
| Gravitational Algorithm | GravitationalOptimization | Utilizes newtons gravitational behaviour | [https://doi.org/10.1109/ICASSP.2011.5946916](https://doi.org/10.1109/ICASSP.2011.5946916) |
More algos soon, stay tuned !
* [Try It Now?] [](https://colab.research.google.com/drive/12LYc67hIuy7PKSa8J_75bQUZ62EBJz4J?usp=sharing)
## ⚡️ Usage
Define your own objective function for optimization !
### Classification Example
```python
from sklearn.metrics import log_loss
# define your own objective function, make sure the function receives four parameters,
# fit your model and return the objective value !
def objective_function_topass(model,X_train, y_train, X_valid, y_valid):
model.fit(X_train,y_train)
P=log_loss(y_valid,model.predict_proba(X_valid))
return P
# import an algorithm !
from zoofs import ParticleSwarmOptimization
# create object of algorithm
algo_object=ParticleSwarmOptimization(objective_function_topass,n_iteration=20,
population_size=20,minimize=True)
import lightgbm as lgb
lgb_model = lgb.LGBMClassifier()
# fit the algorithm
algo_object.fit(lgb_model,X_train, y_train, X_valid, y_valid,verbose=True)
#plot your results
algo_object.plot_history()
```
### Regression Example
```python
from sklearn.metrics import mean_squared_error
# define your own objective function, make sure the function receives four parameters,
# fit your model and return the objective value !
def objective_function_topass(model,X_train, y_train, X_valid, y_valid):
model.fit(X_train,y_train)
P=mean_squared_error(y_valid,model.predict(X_valid))
return P
# import an algorithm !
from zoofs import ParticleSwarmOptimization
# create object of algorithm
algo_object=ParticleSwarmOptimization(objective_function_topass,n_iteration=20,
population_size=20,minimize=True)
import lightgbm as lgb
lgb_model = lgb.LGBMRegressor()
# fit the algorithm
algo_object.fit(lgb_model,X_train, y_train, X_valid, y_valid,verbose=True)
#plot your results
algo_object.plot_history()
```
### Suggestions for Usage
- As available algorithms are wrapper algos, it is better to use ml models that build quicker, e.g lightgbm, catboost.
- Take sufficient amount for 'population_size' , as this will determine the extent of exploration and exploitation of the algo.
- Ensure that your ml model has its hyperparamters optimized before passing it to zoofs algos.
### objective score plot

<br/>
<br/>
## Algorithms
<details>
<summary markdown="span"> Particle Swarm Algorithm </summary>

In computational science, particle swarm optimization (PSO) is a computational method that optimizes a problem by iteratively trying to improve a candidate solution with regard to a given measure of quality. It solves a problem by having a population of candidate solutions, here dubbed particles, and moving these particles around in the search-space according to simple mathematical formula over the particle's position and velocity. Each particle's movement is influenced by its local best known position, but is also guided toward the best known positions in the search-space, which are updated as better positions are found by other particles. This is expected to move the swarm toward the best solutions.
------------------------------------------
#### class zoofs.ParticleSwarmOptimization(objective_function,n_iteration=50,population_size=50,minimize=True,c1=2,c2=2,w=0.9)
------------------------------------------
| | |
|----------|-------------|
| Parameters | ``objective_function`` : user made function of the signature 'func(model,X_train,y_train,X_test,y_test)'. <br/> <dl> <dd> The function must return a value, that needs to be minimized/maximized. </dd> </dl> ``n_iteration ``: int, default=1000 <br/> <dl> <dd> Number of time the algorithm will run </dd> </dl> ``timeout``: int = None <br/> <dl> <dd> Stop operation after the given number of second(s). If this argument is set to None, the operation is executed without time limitation and n_iteration is followed </dd> </dl> ``population_size`` : int, default=50 <br/> <dl> <dd> Total size of the population </dd> </dl> ``minimize ``: bool, default=True <br/> <dl> <dd> Defines if the objective value is to be maximized or minimized </dd> </dl> ``c1`` : float, default=2.0 <br/> <dl> <dd> first acceleration coefficient of particle swarm </dd> </dl> ``c2`` : float, default=2.0 <br/> <dl> <dd> second acceleration coefficient of particle swarm </dd> </dl> `w` : float, default=0.9 <br/> <dl> <dd> weight parameter </dd> </dl>|
| Attributes | ``best_feature_list`` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### Methods
| Methods | Class Name |
|----------|-------------|
| fit | Run the algorithm |
| plot_history | Plot results achieved across iteration |
#### fit(model,X_train, y_train, X_test, y_test,verbose=True)
| | |
|----------|-------------|
| Parameters | ``model`` : <br/> <dl> <dd> machine learning model's object </dd> </dl> ``X_train`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/><dl> <dd> Training input samples to be used for machine learning model </dd> </dl> ``y_train`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The target values (class labels in classification, real numbers in regression). </dd> </dl> ``X_valid`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/> <dl> <dd> Validation input samples </dd> </dl> ``y_valid`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The Validation target values . </dd> </dl> ``verbose`` : bool,default=True <br/> <dl> <dd> Print results for iterations </dd> </dl>|
| Returns | ``best_feature_list `` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### plot_history()
Plot results across iterations
#### Example
```python
from sklearn.metrics import log_loss
# define your own objective function, make sure the function receives four parameters,
# fit your model and return the objective value !
def objective_function_topass(model,X_train, y_train, X_valid, y_valid):
model.fit(X_train,y_train)
P=log_loss(y_valid,model.predict_proba(X_valid))
return P
# import an algorithm !
from zoofs import ParticleSwarmOptimization
# create object of algorithm
algo_object=ParticleSwarmOptimization(objective_function_topass,n_iteration=20,
population_size=20,minimize=True,c1=2,c2=2,w=0.9)
import lightgbm as lgb
lgb_model = lgb.LGBMClassifier()
# fit the algorithm
algo_object.fit(lgb_model,X_train, y_train, X_valid, y_valid,verbose=True)
#plot your results
algo_object.plot_history()
```
<br/>
<br/>
</details>
<details>
<summary markdown="span"> Grey Wolf Algorithm </summary>

The Grey Wolf Optimizer (GWO) mimics the leadership hierarchy and hunting mechanism of grey wolves in nature. Four types of grey wolves such as alpha, beta, delta, and omega are employed for simulating the leadership hierarchy. In addition, three main steps of hunting, searching for prey, encircling prey, and attacking prey, are implemented to perform optimization.
------------------------------------------
#### class zoofs.GreyWolfOptimization(objective_function,n_iteration=50,population_size=50,minimize=True)
------------------------------------------
| | |
|----------|-------------|
| Parameters | ``objective_function`` : user made function of the signature 'func(model,X_train,y_train,X_test,y_test)'. <br/> <dl> <dd> The function must return a value, that needs to be minimized/maximized. </dd> </dl> ``n_iteration ``: int, default=50 <br/> <dl> <dd> Number of time the algorithm will run </dd> </dl> ``timeout``: int = None <br/> <dl> <dd> Stop operation after the given number of second(s). If this argument is set to None, the operation is executed without time limitation and n_iteration is followed </dd> </dl> ``population_size`` : int, default=50 <br/> <dl> <dd> Total size of the population </dd> </dl> ``method`` : {1, 2}, default=1 <br/> <dl> <dd> Choose the between the two methods of grey wolf optimization </dd> </dl> ``minimize ``: bool, default=True <br/> <dl> <dd> Defines if the objective value is to be maximized or minimized </dd> </dl>|
| Attributes | ``best_feature_list`` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### Methods
| Methods | Class Name |
|----------|-------------|
| fit | Run the algorithm |
| plot_history | Plot results achieved across iteration |
#### fit(model,X_train,y_train,X_valid,y_valid,method=1,verbose=True)
| | |
|----------|-------------|
| Parameters | ``model`` : <br/> <dl> <dd> machine learning model's object </dd> </dl> ``X_train`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/><dl> <dd> Training input samples to be used for machine learning model </dd> </dl> ``y_train`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The target values (class labels in classification, real numbers in regression). </dd> </dl> ``X_valid`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/> <dl> <dd> Validation input samples </dd> </dl> ``y_valid`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The Validation target values . </dd> </dl> ``verbose`` : bool,default=True <br/> <dl> <dd> Print results for iterations </dd> </dl>|
| Returns | ``best_feature_list `` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### plot_history()
Plot results across iterations
#### Example
```python
from sklearn.metrics import log_loss
# define your own objective function, make sure the function receives four parameters,
# fit your model and return the objective value !
def objective_function_topass(model,X_train, y_train, X_valid, y_valid):
model.fit(X_train,y_train)
P=log_loss(y_valid,model.predict_proba(X_valid))
return P
# import an algorithm !
from zoofs import GreyWolfOptimization
# create object of algorithm
algo_object=GreyWolfOptimization(objective_function_topass,n_iteration=20,method=1,
population_size=20,minimize=True)
import lightgbm as lgb
lgb_model = lgb.LGBMClassifier()
# fit the algorithm
algo_object.fit(lgb_model,X_train, y_train, X_valid, y_valid,verbose=True)
#plot your results
algo_object.plot_history()
```
<br/>
<br/>
</details>
<details>
<summary markdown="span"> Dragon Fly Algorithm </summary>

The main inspiration of the Dragonfly Algorithm (DA) algorithm originates from static and dynamic swarming behaviours. These two swarming behaviours are very similar to the two main phases of optimization using meta-heuristics: exploration and exploitation. Dragonflies create sub swarms and fly over different areas in a static swarm, which is the main objective of the exploration phase. In the static swarm, however, dragonflies fly in bigger swarms and along one direction, which is favourable in the exploitation phase.
------------------------------------------
#### class zoofs.DragonFlyOptimization(objective_function,n_iteration=50,population_size=50,minimize=True)
------------------------------------------
| | |
|----------|-------------|
| Parameters | ``objective_function`` : user made function of the signature 'func(model,X_train,y_train,X_test,y_test)'. <br/> <dl> <dd> The function must return a value, that needs to be minimized/maximized. </dd> </dl> ``n_iteration ``: int, default=50 <br/> <dl> <dd> Number of time the algorithm will run </dd> </dl> ``timeout``: int = None <br/> <dl> <dd> Stop operation after the given number of second(s). If this argument is set to None, the operation is executed without time limitation and n_iteration is followed </dd> </dl> ``population_size`` : int, default=50 <br/> <dl> <dd> Total size of the population </dd> </dl> ``method`` : {'linear','random','quadraic','sinusoidal'}, default='sinusoidal' <br/> <dl> <dd> Choose the between the three methods of Dragon Fly optimization </dd> </dl> ``minimize ``: bool, default=True <br/> <dl> <dd> Defines if the objective value is to be maximized or minimized </dd> </dl>|
| Attributes | ``best_feature_list`` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### Methods
| Methods | Class Name |
|----------|-------------|
| fit | Run the algorithm |
| plot_history | Plot results achieved across iteration |
#### fit(model,X_train,y_train,X_valid,y_valid,method='sinusoidal',verbose=True)
| | |
|----------|-------------|
| Parameters | ``model`` : <br/> <dl> <dd> machine learning model's object </dd> </dl> ``X_train`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/><dl> <dd> Training input samples to be used for machine learning model </dd> </dl> ``y_train`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The target values (class labels in classification, real numbers in regression). </dd> </dl> ``X_valid`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/> <dl> <dd> Validation input samples </dd> </dl> ``y_valid`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The Validation target values . </dd> </dl> ``verbose`` : bool,default=True <br/> <dl> <dd> Print results for iterations </dd> </dl>|
| Returns | ``best_feature_list `` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### plot_history()
Plot results across iterations
#### Example
```python
from sklearn.metrics import log_loss
# define your own objective function, make sure the function receives four parameters,
# fit your model and return the objective value !
def objective_function_topass(model,X_train, y_train, X_valid, y_valid):
model.fit(X_train,y_train)
P=log_loss(y_valid,model.predict_proba(X_valid))
return P
# import an algorithm !
from zoofs import DragonFlyOptimization
# create object of algorithm
algo_object=DragonFlyOptimization(objective_function_topass,n_iteration=20,method='sinusoidal',
population_size=20,minimize=True)
import lightgbm as lgb
lgb_model = lgb.LGBMClassifier()
# fit the algorithm
algo_object.fit(lgb_model,X_train, y_train, X_valid, y_valid, verbose=True)
#plot your results
algo_object.plot_history()
```
<br/>
<br/>
</details>
<details>
<summary markdown="span"> Harris Hawk Optimization </summary>

HHO is a popular swarm-based, gradient-free optimization algorithm with several active and time-varying phases of exploration and exploitation. This algorithm initially published by the prestigious Journal of Future Generation Computer Systems (FGCS) in 2019, and from the first day, it has gained increasing attention among researchers due to its flexible structure, high performance, and high-quality results. The main logic of the HHO method is designed based on the cooperative behaviour and chasing styles of Harris' hawks in nature called "surprise pounce". Currently, there are many suggestions about how to enhance the functionality of HHO, and there are also several enhanced variants of the HHO in the leading Elsevier and IEEE transaction journals.
------------------------------------------
#### class zoofs.HarrisHawkOptimization(objective_function,n_iteration=50,population_size=50,minimize=True,beta=0.5)
------------------------------------------
| | |
|----------|-------------|
| Parameters | ``objective_function`` : user made function of the signature 'func(model,X_train,y_train,X_test,y_test)'. <br/> <dl> <dd> The function must return a value, that needs to be minimized/maximized. </dd> </dl> ``n_iteration ``: int, default=1000 <br/> <dl> <dd> Number of time the algorithm will run </dd> </dl> ``timeout``: int = None <br/> <dl> <dd> Stop operation after the given number of second(s). If this argument is set to None, the operation is executed without time limitation and n_iteration is followed </dd> </dl> ``population_size`` : int, default=50 <br/> <dl> <dd> Total size of the population </dd> </dl> ``minimize ``: bool, default=True <br/> <dl> <dd> Defines if the objective value is to be maximized or minimized </dd> </dl> ``beta`` : float, default=0.5 <br/> <dl> <dd> value for levy random walk </dd> </dl> |
| Attributes | ``best_feature_list`` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### Methods
| Methods | Class Name |
|----------|-------------|
| fit | Run the algorithm |
| plot_history | Plot results achieved across iteration |
#### fit(model,X_train, y_train, X_test, y_test,verbose=True)
| | |
|----------|-------------|
| Parameters | ``model`` : <br/> <dl> <dd> machine learning model's object </dd> </dl> ``X_train`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/><dl> <dd> Training input samples to be used for machine learning model </dd> </dl> ``y_train`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The target values (class labels in classification, real numbers in regression). </dd> </dl> ``X_valid`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/> <dl> <dd> Validation input samples </dd> </dl> ``y_valid`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The Validation target values . </dd> </dl> ``verbose`` : bool,default=True <br/> <dl> <dd> Print results for iterations </dd> </dl>|
| Returns | ``best_feature_list `` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### plot_history()
Plot results across iterations
#### Example
```python
from sklearn.metrics import log_loss
# define your own objective function, make sure the function receives four parameters,
# fit your model and return the objective value !
def objective_function_topass(model,X_train, y_train, X_valid, y_valid):
model.fit(X_train,y_train)
P=log_loss(y_valid,model.predict_proba(X_valid))
return P
# import an algorithm !
from zoofs import HarrisHawkOptimization
# create object of algorithm
algo_object=HarrisHawkOptimization(objective_function_topass,n_iteration=20,
population_size=20,minimize=True)
import lightgbm as lgb
lgb_model = lgb.LGBMClassifier()
# fit the algorithm
algo_object.fit(lgb_model,X_train, y_train, X_valid, y_valid,verbose=True)
#plot your results
algo_object.plot_history()
```
<br/>
<br/>
</details>
<details>
<summary markdown="span"> Genetic Algorithm </summary>

In computer science and operations research, a genetic algorithm (GA) is a metaheuristic inspired by the process of natural selection that belongs to the larger class of evolutionary algorithms (EA). Genetic algorithms are commonly used to generate high-quality solutions to optimization and search problems by relying on biologically inspired operators such as mutation, crossover and selection. Some examples of GA applications include optimizing decision trees for better performance, automatically solve sudoku puzzles, hyperparameter optimization, etc.
------------------------------------------
#### class zoofs.GeneticOptimization(objective_function,n_iteration=20,population_size=20,selective_pressure=2,elitism=2,mutation_rate=0.05,minimize=True)
------------------------------------------
| | |
|----------|-------------|
| Parameters | ``objective_function`` : user made function of the signature 'func(model,X_train,y_train,X_test,y_test)'. <br/> <dl> <dd> The function must return a value, that needs to be minimized/maximized. </dd> </dl> ``n_iteration``: int, default=50 <br/> <dl> <dd> Number of time the algorithm will run </dd> </dl> ``timeout``: int = None <br/> <dl> <dd> Stop operation after the given number of second(s). If this argument is set to None, the operation is executed without time limitation and n_iteration is followed </dd> </dl> ``population_size`` : int, default=50 <br/> <dl> <dd> Total size of the population </dd> </dl> ``selective_pressure``: int, default=2 <br/> <dl> <dd>measure of reproductive opportunities for each organism in the population </dd> </dl> ``elitism``: int, default=2 <br/> <dl> <dd> number of top individuals to be considered as elites </dd> </dl> ``mutation_rate``: float, default=0.05 <br/> <dl> <dd> rate of mutation in the population's gene </dd> </dl> ``minimize``: bool, default=True <br/> <dl> <dd> Defines if the objective value is to be maximized or minimized </dd> </dl>|
| Attributes | ``best_feature_list`` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### Methods
| Methods | Class Name |
|----------|-------------|
| fit | Run the algorithm |
| plot_history | Plot results achieved across iteration |
#### fit(model,X_train,y_train,X_valid,y_valid,verbose=True)
| | |
|----------|-------------|
| Parameters | ``model`` : <br/> <dl> <dd> machine learning model's object </dd> </dl> ``X_train`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/><dl> <dd> Training input samples to be used for machine learning model </dd> </dl> ``y_train`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The target values (class labels in classification, real numbers in regression). </dd> </dl> ``X_valid`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/> <dl> <dd> Validation input samples </dd> </dl> ``y_valid`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The Validation target values . </dd> </dl> ``verbose`` : bool,default=True <br/> <dl> <dd> Print results for iterations </dd> </dl>|
| Returns | ``best_feature_list `` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### plot_history()
Plot results across iterations
#### Example
```python
from sklearn.metrics import log_loss
# define your own objective function, make sure the function receives four parameters,
# fit your model and return the objective value !
def objective_function_topass(model,X_train, y_train, X_valid, y_valid):
model.fit(X_train,y_train)
P=log_loss(y_valid,model.predict_proba(X_valid))
return P
# import an algorithm !
from zoofs import GeneticOptimization
# create object of algorithm
algo_object=GeneticOptimization(objective_function_topass,n_iteration=20,
population_size=20,selective_pressure=2,elitism=2,
mutation_rate=0.05,minimize=True)
import lightgbm as lgb
lgb_model = lgb.LGBMClassifier()
# fit the algorithm
algo_object.fit(lgb_model,X_train, y_train,X_valid, y_valid, verbose=True)
#plot your results
algo_object.plot_history()
```
</details>
<details>
<summary markdown="span"> Gravitational Algorithm </summary>

Gravitational Algorithm is based on the law of gravity and mass interactions is introduced. In the algorithm, the searcher agents are a collection of masses which interact with each other based on the Newtonian gravity and the laws of motion.
------------------------------------------
#### class zoofs.GravitationalOptimization(self,objective_function,n_iteration=50,population_size=50,g0=100,eps=0.5,minimize=True)
------------------------------------------
| | |
|----------|-------------|
| Parameters | ``objective_function`` : user made function of the signature 'func(model,X_train,y_train,X_test,y_test)'. <br/> <dl> <dd> The function must return a value, that needs to be minimized/maximized. </dd> </dl> ``n_iteration``: int, default=50 <br/> <dl> <dd> Number of time the algorithm will run </dd> </dl> ``timeout``: int = None <br/> <dl> <dd> Stop operation after the given number of second(s). If this argument is set to None, the operation is executed without time limitation and n_iteration is followed </dd> </dl> ``population_size`` : int, default=50 <br/> <dl> <dd> Total size of the population </dd> </dl> ``g0``: float, default=100 <br/> <dl> <dd> gravitational strength constant </dd> </dl> ``eps``: float, default=0.5 <br/> <dl> <dd> distance constant </dd> </dl>``minimize``: bool, default=True <br/> <dl> <dd> Defines if the objective value is to be maximized or minimized </dd> </dl>|
| Attributes | ``best_feature_list`` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### Methods
| Methods | Class Name |
|----------|-------------|
| fit | Run the algorithm |
| plot_history | Plot results achieved across iteration |
#### fit(model,X_train,y_train,X_valid,y_valid,verbose=True)
| | |
|----------|-------------|
| Parameters | ``model`` : <br/> <dl> <dd> machine learning model's object </dd> </dl> ``X_train`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/><dl> <dd> Training input samples to be used for machine learning model </dd> </dl> ``y_train`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The target values (class labels in classification, real numbers in regression). </dd> </dl> ``X_valid`` : pandas.core.frame.DataFrame of shape (n_samples, n_features) <br/> <dl> <dd> Validation input samples </dd> </dl> ``y_valid`` : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples) <br/> <dl> <dd> The Validation target values . </dd> </dl> ``verbose`` : bool,default=True <br/> <dl> <dd> Print results for iterations </dd> </dl>|
| Returns | ``best_feature_list `` : array-like <br/> <dl> <dd> Final best set of features </dd> </dl> |
#### plot_history()
Plot results across iterations
#### Example
```python
from sklearn.metrics import log_loss
# define your own objective function, make sure the function receives four parameters,
# fit your model and return the objective value !
def objective_function_topass(model,X_train, y_train, X_valid, y_valid):
model.fit(X_train,y_train)
P=log_loss(y_valid,model.predict_proba(X_valid))
return P
# import an algorithm !
from zoofs import GravitationalOptimization
# create object of algorithm
algo_object=GravitationalOptimization(objective_function_topass,n_iteration=50,
population_size=50,g0=100,eps=0.5,minimize=True)
import lightgbm as lgb
lgb_model = lgb.LGBMClassifier()
# fit the algorithm
algo_object.fit(lgb_model,X_train, y_train, X_valid, y_valid, verbose=True)
#plot your results
algo_object.plot_history()
```
</details>
## Support `zoofs`
The development of ``zoofs`` relies completely on contributions.
#### Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
## First roll out
18,08,2021
## License
[apache-2.0](https://choosealicense.com/licenses/apache-2.0/)
| zoofs | /zoofs-0.1.26.tar.gz/zoofs-0.1.26/README.md | README.md |
import argparse
import os
def get_parser():
parser = argparse.ArgumentParser(description="A simple healthcheck for ZooKeeper. It checks if ZooKeeper is 'ok' via 'ruok' and "
"checks if it is in a mode determined as healthy via 'stat'. "
"Healthy modes can be set as desired.")
parser.add_argument("--port",
default=os.environ.get("HEALTHCHECK_PORT", "12181"),
dest="healthcheck_port",
type=int,
nargs="?",
help="The port for the healthcheck HTTP server."
)
parser.add_argument("--zookeeper-host",
default=os.environ.get("HEALTHCHECK_ZOOKEEPER_HOST", "localhost"),
dest="zookeeper_host",
nargs="?",
help="The host of the ZooKeeper instance that the health check will be run against."
)
parser.add_argument("--zookeeper-port",
default=os.environ.get("HEALTHCHECK_ZOOKEEPER_PORT", "2181"),
dest="zookeeper_port",
type=int,
nargs="?",
help="The port of the ZooKeeper instance that the health check will be run against."
)
parser.add_argument("--healthy-modes",
default=os.environ.get("HEALTHCHECK_HEALTHY_MODES", "leader,follower").lower(),
dest="healthy_modes",
nargs="?",
help="A comma separated list of ZooKeeper modes to be marked as healthy. Default: leader,follower."
)
parser.add_argument("--log-level",
default=os.environ.get("HEALTHCHECK_LOG_LEVEL", "INFO").upper(),
dest="log_level",
nargs="?",
help="The level of logs to be shown. Default: INFO.")
return parser | zookeeper-healthcheck | /zookeeper_healthcheck-0.0.1-py3-none-any.whl/zookeeper_healthcheck/parser.py | parser.py |
from __future__ import unicode_literals
import logging
import subprocess
class Health:
def __init__(self, zookeeper_host, zookeeper_port, healthy_modes):
self.zookeeper_host = zookeeper_host
self.zookeeper_port = zookeeper_port
self.healthy_modes = [x.lower().strip() for x in healthy_modes]
self.log_initialization_values()
def get_health_result(self):
try:
is_ok = self.is_zookeeper_ok()
is_in_healthy_mode = self.is_zookeeper_in_healthy_mode()
is_healthy = is_ok and is_in_healthy_mode
health_result = {"healthy": is_healthy, "is_ok": is_ok, "is_in_healthy_mode": is_in_healthy_mode}
except Exception as ex:
logging.error("Error while attempting to calculate health result. Assuming unhealthy. Error: {}".format(ex))
logging.error(ex)
health_result = {
"healthy": False,
"message": "Exception raised while attempting to calculate health result, assuming unhealthy.",
"error": "{}".format(ex)
}
return health_result
def log_initialization_values(self):
logging.info("Server will report healthy for modes: '{}'".format(", ".join(self.healthy_modes)))
logging.info("Server will healthcheck against zookeeper host: {}".format(self.zookeeper_host))
logging.info("Server will healthcheck against zookeeper port: {}".format(self.zookeeper_port))
def is_zookeeper_ok(self):
process_one = subprocess.Popen(["echo", "ruok"], stdout=subprocess.PIPE)
process_two = subprocess.Popen(["nc", "{}".format(self.zookeeper_host), "{}".format(self.zookeeper_port)],
stdin=process_one.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
process_one.stdout.close()
(output, err) = process_two.communicate()
exit_code = process_two.wait()
output = output.decode("utf-8").strip()
if exit_code == 0:
is_ok = output == "imok"
if is_ok:
logging.info("ZooKeeper isok check returned response: {}".format(output))
else:
logging.warning("ZooKeeper isok is not healthy: {}".format(output))
return is_ok
else:
logging.warning("ZooKeeper isok returned exit code: {}, marking unhealthy...".format(exit_code))
return False
def is_zookeeper_in_healthy_mode(self):
process_one = subprocess.Popen(["echo", "stat"], stdout=subprocess.PIPE)
process_two = subprocess.Popen(["nc", "{}".format(self.zookeeper_host), "{}".format(self.zookeeper_port)],
stdin=process_one.stdout,
stdout=subprocess.PIPE)
process_three = subprocess.Popen(["grep", "Mode"],
stdin=process_two.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
process_one.stdout.close()
process_two.stdout.close()
(output, err) = process_three.communicate()
exit_code = process_three.wait()
output = output.decode("utf-8").strip()
if exit_code == 0:
is_in_healthy_mode = any(mode in output for mode in self.healthy_modes)
if is_in_healthy_mode:
logging.info("ZooKeeper mode returned response: {}".format(output))
else:
logging.warning("ZooKeeper is not in a healthy mode: {}".format(output))
return is_in_healthy_mode
else:
logging.warning("ZooKeeper mode returned exit code: {}, marking unhealthy...".format(exit_code))
return False | zookeeper-healthcheck | /zookeeper_healthcheck-0.0.1-py3-none-any.whl/zookeeper_healthcheck/health.py | health.py |
# Zookeeper
[](https://github.com/larq/zookeeper/actions?workflow=Unittest) [](https://codecov.io/github/larq/zookeeper?branch=main) [](https://pypi.org/project/zookeeper/) [](https://pypi.org/project/zookeeper/) [](https://github.com/plumerai/zookeeper/blob/main/LICENSE) [](https://github.com/ambv/black)
A small library for configuring modular applications.
### Installation
```console
pip install zookeeper
```
### Components
The fundamental building blocks of Zookeeper are components. The
[`@component`](zookeeper/component.py) decorator is used to turn classes into
components. These component classes can have configurable fields, which are
declared with the `Field` constructor and class-level type annotations. Fields
can be created with or without default values. Components can also be nested,
with `ComponentField`s, such that child componenents can access the field values
defined on their parents.
For example:
```python
from zookeeper import component
@component
class ChildComponent:
a: int = Field() # An `int` field with no default set
b: str = Field("foo") # A `str` field with default value `"foo"`
@component
class ParentComponent:
a: int = Field() # The same `int` field as the child
child: ChildComponent = ComponentField() # A nested component field, of type `ChildComponent`
```
After instantiation, components can be 'configured' with a configuration
dictionary, containing values for a tree of nested fields. This process
automatically injects the correct values into each field.
If a child sub-component declares a field which already exists in some
containing ancestor component, then it will pick up the value that's set on the
parent, unless a 'scoped' value is set on the child.
For example:
```
from zookeeper import configure
p = ParentComponent()
configure(
p,
{
"a": 5,
"child.a": 4,
}
)
>>> 'ChildComponent' is the only concrete component class that satisfies the type
>>> of the annotated parameter 'ParentComponent.child'. Using an instance of this
>>> class by default.
print(p)
>>> ParentComponent(
>>> a = 5,
>>> child = ChildComponent(
>>> a = 4,
>>> b = "foo"
>>> )
>>> )
```
### Tasks and the CLI
The [`@task`](zookeeper/task.py) decorator is used to define Zookeeper tasks and
can be applied to any class that implements an argument-less `run` method. Such
tasks can be run through the Zookeeper CLI, with parameter values passed in
through CLI arguments (`configure` is implicitly called).
For example:
```python
from zookeeper import cli, task
@task
class UseChildA:
parent: ParentComponent = ComponentField()
def run(self):
print(self.parent.child.a)
@task
class UseParentA(UseChildA):
def run(self):
print(self.parent.a)
if __name__ == "__main__":
cli()
```
Running the above file then gives a nice CLI interface:
```
python test.py use_child_a
>>> ValueError: No configuration value found for annotated parameter 'UseChildA.parent.a' of type 'int'.
python test.py use_child_a a=5
>>> 5
python test.py use_child_a a=5 child.a=3
>>> 3
python test.py use_parent_a a=5 child.a=3
>>> 5
```
### Using Zookeeper to define Larq or Keras experiments
See [examples/larq_experiment.py](examples/larq_experiment.py) for an example of
how to use Zookeeper to define all the necessary components (dataset,
preprocessing, and model) of a Larq experiment: training a BinaryNet on
MNIST. This example can be easily adapted to other Larq or Keras models and
other datasets.
| zookeeper | /zookeeper-1.3.2.tar.gz/zookeeper-1.3.2/README.md | README.md |
zookeeper_monitor
==================
|image0|_ |image1|_
.. |image0| image:: https://api.travis-ci.org/kwarunek/zookeeper_monitor.png?branch=master
.. _image0: https://travis-ci.org/kwarunek/zookeeper_monitor
.. |image1| image:: https://landscape.io/github/kwarunek/zookeeper_monitor/master/landscape.svg?style=flat
.. _image1: https://landscape.io/github/kwarunek/zookeeper_monitor
Module lets you call ZooKeeper commands - four letters commands over TCP - https://zookeeper.apache.org/doc/r3.1.2/zookeeperAdmin.html#sc_zkCommands. It also has built-in web monitor. Based on Tornado, compatibile with Python 2.7.x, 3.x and above. It doesn't require zookeeper, nor zookeeper's headers (since it doesn't utilize zkpython).
Installation
------------
It can be installed from pypi or directly from git repository.
.. code-block:: bash
pip install zookeeper_monitor
#or
git clone https://github.com/kwarunek/zookeeper_monitor.git
cd zookeeper_monitor/
python setup.py install
Usage
------------
Example:
.. code-block:: python
from zookeeper_monitor import zk
@tornado.gen.coroutine
def some_coroutine()
host = zk.Host('zookeeper.addr.ip', 2181)
# you can run each command as a coroutine example:
# get srvr data
srvr_data = yield host.srvr()
# get stat data
stat_data = yield host.stat()
# get server state
ruok = yield host.ruok()
# stop zookeeper
yield host.kill()
You can wrap it to sync code if you are not using tornado
.. code-block:: python
from tornado.ioloop import IOLoop
IOLoop.instance().run_sync(some_coroutine)
Web monitor
-----------
To run web monitor you need to provide configuration, if you don't, it will used `localhost:2181` by default.
.. code-block:: bash
python -m zookeeper_monitor.web
# with configuration file
python -m zookeeper_monitor.web -c /somepath/cluster.json
# to see available options
python -m zookeeper_monitor.web --help
Next you navigate to http://127.0.0.1:8080/ (or whatever you specified).
Configuration
-------------
Defining cluster `cluster.json` (json or yaml)
.. code-block:: json
{
"name": "brand-new-zookeeper-cluster",
"hosts": [
{"addr": "10.1.15.1", "port": 2181, "dc":"eu-west"},
{"addr": "10.2.31.2", "port": 2181, "dc":"us-east"},
{"addr": "10.1.12.3", "port": 2181, "dc":"eu-west"}
]
}
* name (string) - cluster name.
* hosts (list) - List of hosts running ZooKeeper connected in cluster:
- addr (string): IP or domain, mandatory
- port (int): ZooKeeper port, optional, default 2181
- dc (string): datacenter/location name, optional
Screenshots
-----------
Cluster view
|image22|_
.. |image22| image:: https://cloud.githubusercontent.com/assets/670887/5609840/172c1e38-94aa-11e4-92e5-9b4e8a06632c.png
.. _image22: https://cloud.githubusercontent.com/assets/670887/5609840/172c1e38-94aa-11e4-92e5-9b4e8a06632c.png
Node stat view
|image23|_
.. |image23| image:: https://cloud.githubusercontent.com/assets/670887/5609842/1be19584-94aa-11e4-8cd1-5df63c1bfaaf.png
.. _image23: https://cloud.githubusercontent.com/assets/670887/5609842/1be19584-94aa-11e4-8cd1-5df63c1bfaaf.png
License
-------
MIT
TODO
----
- more tests
- more stats in webmonitor
- parse zookeeper version
- new commands in zookeeper 3.3 and 3.4
- parse output of dump, reqs
Changelog
---------
0.3.0 - implemented `mntr`, credits to `Robb Wagoner <https://github.com/robbwagoner>`_
0.2.5 - implemented `with_timeout`, handlers get_template, py3.3 gen.Task in Host, css colors
0.2.4 - separate getter template/static dir
0.2.3 - fix import in py3 web
0.2.2 - clean ups: pylint, README, classifiers
0.2.1 - fix package, fix tests
0.2.0 - implement more commands, updated docs
0.1.2 - **release** - pypi
0.1.1 - clean up
0.1.0 - public standalone
0.0.3 - 0.0.9 - refactor, tests
0.0.2 - working draft
0.0.1 - initial concept
| zookeeper_monitor | /zookeeper_monitor-0.3.0.tar.gz/zookeeper_monitor-0.3.0/README.rst | README.rst |
===============
Zoom API Helper
===============
.. image:: https://img.shields.io/pypi/v/zoom-api-helper.svg
:target: https://pypi.org/project/zoom-api-helper
.. image:: https://img.shields.io/pypi/pyversions/zoom-api-helper.svg
:target: https://pypi.org/project/zoom-api-helper
.. image:: https://github.com/rnag/zoom-api-helper/actions/workflows/dev.yml/badge.svg
:target: https://github.com/rnag/zoom-api-helper/actions/workflows/dev.yml
.. image:: https://readthedocs.org/projects/zoom-api-helper/badge/?version=latest
:target: https://zoom-api-helper.readthedocs.io/en/latest/?version=latest
:alt: Documentation Status
.. image:: https://pyup.io/repos/github/rnag/zoom-api-helper/shield.svg
:target: https://pyup.io/repos/github/rnag/zoom-api-helper/
:alt: Updates
Utilities to interact with the `Zoom API v2`_
* Free software: MIT license
* Documentation: https://zoom-api-helper.readthedocs.io.
Installation
------------
The Zoom API Helper library is available `on PyPI`_, and can be installed with ``pip``:
.. code-block:: shell
$ pip install zoom-api-helper
You'll also need to create a Server-to-Server OAuth app as outlined `in the docs`_.
Features
--------
* `Zoom API v2`_: List users, create meetings, and bulk create meetings.
* Support for a `Server-to-Server OAuth`_ flow.
* Local caching of access token retrieved from OAuth process.
Quickstart
----------
Start by creating a helper
client (``ZoomAPI``) to interact with the Zoom API:
.. code-block:: python
>>> from zoom_api_helper import ZoomAPI
>>> zoom = ZoomAPI('<CLIENT ID>', '<CLIENT SECRET>',
... # can also be specified via `ZOOM_ACCOUNT_ID` env variable
... account_id='<ACCOUNT ID>')
Retrieve a list of users via ``ZoomAPI.list_users()``:
.. code-block:: python
>>> zoom.list_users()
{'page_count': 3, 'page_number': 1, 'page_size': 300, 'total_records': 700, 'users': [{'id': '-abc123', 'first_name': 'Jon', 'last_name': 'Doe', 'email': '[email protected]', 'timezone': 'America/New_York', ...}, ...]}
Or, a mapping of each Zoom user's *Email* to *User ID*:
.. code-block:: python
>>> zoom.user_email_to_id(use_cache=True)
{'[email protected]': '-abc123', '[email protected]': '-xyz321', ...}
Create an individual meeting via ``ZoomAPI.create_meeting()``:
.. code-block:: python
>>> zoom.create_meeting(topic='My Awesome Meeting')
{'uuid': 'T9SwnVWzQB2dD1zFQ7PxFA==', 'id': 91894643201, 'host_id': '...', 'host_email': '[email protected]', 'topic': 'My Awesome Meeting', 'type': 2, ...}
To *bulk create* a list of meetings in a concurrent fashion, please see the
section on `Bulk Create Meetings`_ below.
Local Storage
-------------
This library uses a local storage for cache purposes, located under
the user home directory at ``~/.zoom/cache`` by default -- though this
location can be customized, via the ``CACHE_DIR`` environment variable.
The format of the filenames containing cached data will look something similar to this::
{{ Purpose }}_{{ Zoom Account ID }}_{{ Zoom Client ID }}.json
Currently, the helper library utilizes a local file cache for two purposes:
* Storing the access token retrieved from `the OAuth step`_, so that the token
only needs to be refreshed after *~1 hour*.
* Storing a cached mapping of Zoom User emails to User IDs, as generally
the Zoom APIs only require the User ID's.
* As otherwise, retrieving this mapping from the API can sometimes
be expensive, especially for Zoom accounts that have a lot of Users (1000+).
.. _`the OAuth step`: https://marketplace.zoom.us/docs/guides/build/server-to-server-oauth-app/#use-account-credentials-to-get-an-access-token
Bulk Create Meetings
--------------------
In order to *bulk create meetings* -- for example, if you need to create 100+
meetings in a short span of time -- use the ``ZoomAPI``'s `bulk_create_meetings()`_
method.
This allows you to pass in an Excel (*.xlsx*) file containing the meetings to
create, or else pass in the ``rows`` with the meeting info directly.
.. _`bulk_create_meetings()`: https://zoom-api-helper.readthedocs.io/en/latest/zoom_api_helper.html#zoom_api_helper.v2.ZoomAPI.bulk_create_meetings
Example
~~~~~~~
Suppose you have an Excel file (``meeting-info.xlsx``) with the following data:
+---------------------------+------------------+--------------------------------------------+---------------+---------------+--------------+---------------+--------------+-------------+-----------+
| Group Name | Zoom Username | Topic | Meeting Date | Meeting Time | Duration Hr | Duration Min | Meeting URL | Meeting ID | Passcode |
+===========================+==================+============================================+===============+===============+==============+===============+==============+=============+===========+
| A-BC:TEST:Sample Group 1 | [email protected] | TEST Meeting #1: Just an example | 10/26/25 | 3:30 PM | 1 | 30 | | | |
+---------------------------+------------------+--------------------------------------------+---------------+---------------+--------------+---------------+--------------+-------------+-----------+
| A-BC:TEST:Sample Group 2 | [email protected] | TEST Meeting #2: Here's another one | 11/27/25 | 7:00 PM | 1 | 0 | | | |
+---------------------------+------------------+--------------------------------------------+---------------+---------------+--------------+---------------+--------------+-------------+-----------+
| A-BC:TEST:Sample Group 3 | [email protected] | TEST Meeting #3: This is the last for now | 9/29/25 | 9:00 PM | 1 | 15 | | | |
+---------------------------+------------------+--------------------------------------------+---------------+---------------+--------------+---------------+--------------+-------------+-----------+
Then, here is a sample code that would allow you to *bulk create* the specified
meetings in the Zoom Account.
Note: replace the credentials such as ``<CLIENT ID>`` below as needed.
.. code-block:: python3
from datetime import datetime
from zoom_api_helper import ZoomAPI
from zoom_api_helper.models import *
def main():
zoom = ZoomAPI('<CLIENT ID>', '<CLIENT SECRET>', '<ACCOUNT ID>')
# (optional) column header to keyword argument
col_name_to_kwarg = {'Group Name': 'agenda',
'Zoom Username': 'host_email'}
# (optional) predicate function to initially process the row data
def process_row(row: 'RowType', dt_format='%Y-%m-%d %I:%M %p'):
start_time = f"{row['Meeting Date'][:10]} {row['Meeting Time']}"
row.update(
start_time=datetime.strptime(start_time, dt_format),
# Zoom expects the `duration` value in minutes.
duration=int(row['Duration Hr']) * 60 + int(row['Duration Min']),
)
return True
# (optional) function to update row(s) with the API response
def update_row(row: 'RowType', resp: dict):
row['Meeting URL'] = resp['join_url']
row['Meeting ID'] = resp['id']
row['Passcode'] = resp['password']
# create meetings with dry run enabled.
zoom.bulk_create_meetings(
col_name_to_kwarg,
excel_file='./meeting-info.xlsx',
default_timezone='America/New_York',
process_row=process_row,
update_row=update_row,
# comment out below line to actually create the meetings.
dry_run=True,
)
if __name__ == '__main__':
main()
Credits
-------
This package was created with Cookiecutter_ and the `rnag/cookiecutter-pypackage`_ project template.
.. _Zoom API v2: https://marketplace.zoom.us/docs/api-reference/introduction/
.. _Server-to-Server OAuth: https://marketplace.zoom.us/docs/guides/build/server-to-server-oauth-app/
.. _on PyPI: https://pypi.org/project/zoom-api-helper/
.. _in the docs: https://marketplace.zoom.us/docs/guides/build/server-to-server-oauth-app/
.. _Cookiecutter: https://github.com/cookiecutter/cookiecutter
.. _`rnag/cookiecutter-pypackage`: https://github.com/rnag/cookiecutter-pypackage
| zoom-api-helper | /zoom-api-helper-0.1.1.tar.gz/zoom-api-helper-0.1.1/README.rst | README.rst |
.. highlight:: shell
============
Contributing
============
Contributions are welcome, and they are greatly appreciated! Every little bit
helps, and credit will always be given.
You can contribute in many ways:
Types of Contributions
----------------------
Report Bugs
~~~~~~~~~~~
Report bugs at https://github.com/rnag/zoom-api-helper/issues.
If you are reporting a bug, please include:
* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the bug.
Fix Bugs
~~~~~~~~
Look through the GitHub issues for bugs. Anything tagged with "bug" and "help
wanted" is open to whoever wants to implement it.
Implement Features
~~~~~~~~~~~~~~~~~~
Look through the GitHub issues for features. Anything tagged with "enhancement"
and "help wanted" is open to whoever wants to implement it.
Write Documentation
~~~~~~~~~~~~~~~~~~~
Zoom API Helper could always use more documentation, whether as part of the
official Zoom API Helper docs, in docstrings, or even on the web in blog posts,
articles, and such.
Submit Feedback
~~~~~~~~~~~~~~~
The best way to send feedback is to file an issue at https://github.com/rnag/zoom-api-helper/issues.
If you are proposing a feature:
* Explain in detail how it would work.
* Keep the scope as narrow as possible, to make it easier to implement.
* Remember that this is a volunteer-driven project, and that contributions
are welcome :)
Get Started!
------------
Ready to contribute? Here's how to set up `zoom-api-helper` for local development.
1. Fork the `zoom-api-helper` repo on GitHub.
2. Clone your fork locally::
$ git clone [email protected]:your_name_here/zoom-api-helper.git
3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development::
$ mkvirtualenv zoom-api-helper
$ cd zoom-api-helper/
$ make init
4. Create a branch for local development::
$ git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
5. When you're done making changes, check that your changes pass flake8 and the
tests, including testing other Python versions with tox::
$ make lint
$ make test
$ tox
To get flake8 and tox, just pip install them into your virtualenv.
6. Commit your changes and push your branch to GitHub::
$ git add .
$ git commit -m "Your detailed description of your changes."
$ git push origin name-of-your-bugfix-or-feature
7. Submit a pull request through the GitHub website.
Pull Request Guidelines
-----------------------
Before you submit a pull request, check that it meets these guidelines:
1. The pull request should include tests.
2. If the pull request adds functionality, the docs should be updated. Put
your new functionality into a function with a docstring, and add the
feature to the list in README.rst.
3. The pull request should work for Python 3.7, 3.8, 3.9 and 3.10, and for PyPy. Check
https://github.com/rnag/zoom-api-helper/actions/workflows/dev.yml
and make sure that the tests pass for all supported Python versions.
Tips
----
To run a subset of tests::
$ pytest tests/unit/test_zoom_api_helper.py::test_my_func
Deploying
---------
.. note:: **Tip:** The last command below is used to push both the commit and
the new tag to the remote branch simultaneously. There is also a simpler
alternative as mentioned in `this post`_, which involves running the following
command::
$ git config --global push.followTags true
After that, you should be able to simply run the below command to push *both
the commits and tags* simultaneously::
$ git push
A reminder for the maintainers on how to deploy.
Make sure all your changes are committed (including an entry in HISTORY.rst).
Then run::
$ bump2version patch # possible: major / minor / patch
$ git push && git push --tags
GitHub Actions will then `deploy to PyPI`_ if tests pass.
.. _`deploy to PyPI`: https://github.com/rnag/zoom-api-helper/actions/workflows/release.yml
.. _`this post`: https://stackoverflow.com/questions/3745135/push-git-commits-tags-simultaneously
| zoom-api-helper | /zoom-api-helper-0.1.1.tar.gz/zoom-api-helper-0.1.1/CONTRIBUTING.rst | CONTRIBUTING.rst |
.. highlight:: shell
============
Installation
============
Stable release
--------------
To install Zoom API Helper, run this command in your terminal:
.. code-block:: console
$ pip install zoom-api-helper
This is the preferred method to install Zoom API Helper, as it will always install the most recent stable release.
If you don't have `pip`_ installed, this `Python installation guide`_ can guide
you through the process.
.. _pip: https://pip.pypa.io
.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/
From sources
------------
The sources for Zoom API Helper can be downloaded from the `Github repo`_.
You can either clone the public repository:
.. code-block:: console
$ git clone git://github.com/rnag/zoom-api-helper
Or download the `tarball`_:
.. code-block:: console
$ curl -OJL https://github.com/rnag/zoom-api-helper/tarball/master
Once you have a copy of the source, you can install it with:
.. code-block:: console
$ python setup.py install
.. _Github repo: https://github.com/rnag/zoom-api-helper
.. _tarball: https://github.com/rnag/zoom-api-helper/tarball/master
| zoom-api-helper | /zoom-api-helper-0.1.1.tar.gz/zoom-api-helper-0.1.1/docs/installation.rst | installation.rst |
zoom\_api\_helper package
=========================
Submodules
----------
zoom\_api\_helper.constants module
----------------------------------
.. automodule:: zoom_api_helper.constants
:members:
:undoc-members:
:show-inheritance:
zoom\_api\_helper.log module
----------------------------
.. automodule:: zoom_api_helper.log
:members:
:undoc-members:
:show-inheritance:
zoom\_api\_helper.models module
-------------------------------
.. automodule:: zoom_api_helper.models
:members:
:undoc-members:
:show-inheritance:
zoom\_api\_helper.oauth module
------------------------------
.. automodule:: zoom_api_helper.oauth
:members:
:undoc-members:
:show-inheritance:
zoom\_api\_helper.utils module
------------------------------
.. automodule:: zoom_api_helper.utils
:members:
:undoc-members:
:show-inheritance:
zoom\_api\_helper.v2 module
---------------------------
.. automodule:: zoom_api_helper.v2
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: zoom_api_helper
:members:
:undoc-members:
:show-inheritance:
| zoom-api-helper | /zoom-api-helper-0.1.1.tar.gz/zoom-api-helper-0.1.1/docs/zoom_api_helper.rst | zoom_api_helper.rst |
from __future__ import annotations
import json
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from pathlib import Path
from typing import Any
import requests
from .constants import *
from .log import LOG
from .models import *
from .oauth import get_access_token
from .utils import *
class ZoomAPI:
# noinspection GrazieInspection
"""
Helper client to interact with the `Zoom API v2`_
.. _Zoom API v2: https://marketplace.zoom.us/docs/api-reference/zoom-api/
"""
__slots__ = (
# required for `@cached_property`
'__dict__',
# instance attributes
'_session',
'_account_id',
'_access_token',
'_client_id',
)
def __init__(self, client_id: str,
client_secret: str,
account_id: str = None,
local=False):
self._session = session = requests.Session()
self._account_id = account_id = account_id or os.getenv('ZOOM_ACCOUNT_ID')
self._client_id = client_id
if local:
self._access_token = token = 'abc12345'
else:
self._access_token = token = get_access_token(
session, account_id, client_id, client_secret,
)
session.headers['Authorization'] = f'Bearer {token}'
session.headers['Content-Type'] = 'application/json'
@classmethod
def dummy_client(cls):
"""Create a dummy :class:`ZoomAPI` client, for testing purposes."""
return cls('...', '...', local=True)
def __repr__(self):
cls_name = self.__class__.__name__
masked_token = f'{self._access_token[:5]}***'
return (f'{cls_name}(access_token={masked_token!r}, '
f'account_id={self._account_id!r}, '
f'client_id={self._client_id!r})')
def _new_session(self) -> requests.Session:
session = requests.Session()
session.headers['Authorization'] = f'Bearer {self._access_token}'
session.headers['Content-Type'] = 'application/json'
return session
def _get(self, url: str, params: dict = None, session: requests.Session | None = None):
LOG.debug('GET %s, params=%s', url, params)
return (session or self._session).get(url, params=params)
def _post(self, url: str, data: dict = None, session: requests.Session | None = None):
LOG.debug('POST %s, data=%s', url, data)
return (session or self._session).post(url, json=data)
@log_time
def bulk_create_meetings(self, col_header_to_kwarg: dict[str, str] = None,
*,
rows: list[RowType] = None,
excel_file: str | os.PathLike[str] = None,
max_threads=10,
process_row: ProcessRow = None,
update_row: UpdateRow = None,
out_file: str | os.PathLike[str] = None,
default_timezone='UTC',
dry_run=False):
# noinspection GrazieInspection
"""``POST /users/{userId}/meetings``: Use this API to *bulk*-create meetings, given
a list of meetings to create.
If the rows containing meetings to create lives in an Excel (.xlsx) file,
then `excel_file` must be passed in, and contain the filepath of the Excel
file to retrieve the meeting details from; else, `rows` must be passed in
with a list of meetings to create.
Note that to read from Excel, the ``sheet2dict`` library is required;
this can be installed easily via::
$ pip install zoom-api-helper[excel]
``col_header_to_kwarg`` is a mapping of column headers to keyword arguments,
as accepted by the :meth:`create_meeting` method. If the header names are
all title-cased versions of the keyword arguments, then this argument does
*not* need to be passed in. See also, :attr:`constants.CREATE_MEETING_KWARGS`
for a full list of acceptable keywords for the *Create Meeting* API; note
that these are specified as *values* in the key-value pairing.
``process_row`` is an optional function or callable that will be called with
a copy of each *row*, or individual meeting info. The function can modify
the row in place as desired.
``update_row`` is an optional function or callable that will be called with
the HTTP response data from the Create Meetings API, and the associated
row from the Excel file. The function can modify the row in place as desired.
If ``dry_run`` is enabled, then no API calls will be made, and this function
will essentially be a no-op; however, useful logging output is printed for
debugging purposes. Enable this parameter along with the :func:`setup_logging`
helper function, in a debug environment.
**How It Works**
This function scans in a list of rows containing a list of meetings
to create, either from a local file or from the ``rows`` parameter.
Then, it calls ``process_row`` on each row, and also retrieves a
mapping of column name to keyword argument via ``col_header_to_kwarg``.
Then, it concurrently creates a list of meetings via the Zoom
**Create Meetings** API. Finally, it calls ``update_row`` on each
response and row pair, and writes out the updated meeting info to
an output CSV file named ``out_file``, which defaults to
``{excel-file-name-without-ext}}.out.csv`` if an output filepath
is not specified.
**References**
API documentation:
- https://marketplace.zoom.us/docs/api-reference/zoom-api/methods/#operation/meetingCreate
If a naive `datetime` object is provided for ``start_time`` or any other field
(i.e. one with no timezone information) the value for ``timezone`` will determine
which timezone to associate with the `datetime` object - defaults to *UTC* time
if not specified.
For a list of supported timezones, please see:
- https://marketplace.zoom.us/docs/api-reference/other-references/abbreviation-lists/#timezones
"""
# noinspection PyUnresolvedReferences
import sheet2dict
def to_snake_case(s: str):
return s.replace(' ', '_').replace('-', '_').lower()
if rows:
col_headers = rows[0].keys()
else:
ws = sheet2dict.Worksheet()
ws.xlsx_to_dict(excel_file)
col_headers = ws.sheet_items[0].keys()
rows = ws.sheet_items
header_to_kwarg = {kwarg: kwarg for kwarg in CREATE_MEETING_KWARGS}
if not col_header_to_kwarg:
col_header_to_kwarg = {h: to_snake_case(h) for h in col_headers}
for h in col_headers:
kwarg = col_header_to_kwarg.get(h) or to_snake_case(h)
if kwarg in CREATE_MEETING_KWARGS:
header_to_kwarg[h] = kwarg
meetings_to_create = []
if process_row is None:
def do_nothing(_row): return True
process_row = do_nothing
for row in rows:
# copy row so as not to modify it directly.
copied_row = row.copy()
# optional: process the row.
is_valid = process_row(copied_row)
if not is_valid:
continue
# retrieve meeting info.
mtg = {header_to_kwarg[h]: copied_row[h] for h in header_to_kwarg
if h in copied_row}
# add default fields.
if 'timezone' not in mtg:
mtg['timezone'] = default_timezone
meetings_to_create.append(mtg)
# if it's a dry run, print useful info for debugging purposes, then quit.
if dry_run:
print('Column Header to Keyword Argument:')
print(json.dumps(header_to_kwarg, indent=2))
print()
print(f'Have {len(meetings_to_create)} Meetings to Create:')
print(json.dumps(meetings_to_create, indent=2, cls=CustomEncoder))
return
LOG.debug('Column Header to Keyword Argument: %s', header_to_kwarg)
if out_file is None:
p = Path(excel_file)
out_file = p.with_name(f'{p.stem}.out.csv')
LOG.debug('Output File: %s', out_file.absolute())
def create_meeting(mtg_: RowType):
# use a separate session for each thread.
session = self._new_session()
return self.create_meeting(session=session, **mtg_)
if update_row is None:
update_row = dict.update
with ThreadPoolExecutor(max_workers=max_threads) as executor:
# Start the create meeting operations and mark each future with its row index
future_to_row_idx = {executor.submit(create_meeting, mtg): i
for i, mtg in enumerate(meetings_to_create)}
for future in as_completed(future_to_row_idx):
idx = future_to_row_idx[future]
row = rows[idx]
try:
resp = future.result()
except Exception as exc:
LOG.error('[%d] %r generated an exception: %s', idx, row, exc)
else:
update_row(row, resp)
write_to_csv(out_file, rows)
def create_meeting(self, *,
session: requests.Session | None = None,
host_id: str | None = None,
host_email: str | None = None,
topic: str = 'My Meeting',
agenda: str = 'My Description',
start_time: datetime | str | None = None,
timezone: str | None = 'UTC',
type: Meeting | None = None,
**request_data) -> dict[str, Any]:
"""``POST /users/{userId}/meetings``: Use this API to create a meeting for a user.
Ref:
- https://marketplace.zoom.us/docs/api-reference/zoom-api/methods/#operation/meetingCreate
If a naive `datetime` object is provided for `start_time` or any other field
(i.e. one with no timezone information) the value for`timezone` will determine
which timezone to associate with the `datetime` object - defaults to *UTC* time
if not specified.
For a list of supported timezones, please see:
- https://marketplace.zoom.us/docs/api-reference/other-references/abbreviation-lists/#timezones
:return:
"""
if host_id:
user_id = host_id
elif host_email:
user_id = self._user_email_to_id_cached[host_email]
else:
user_id = 'me'
if agenda:
request_data['agenda'] = agenda
if topic:
request_data['topic'] = topic
if start_time:
request_data['start_time'] = start_time.isoformat() \
if isinstance(start_time, datetime) else start_time
if timezone:
request_data['timezone'] = timezone
if type:
request_data['type'] = type.value
r = self._post(f'https://api.zoom.us/v2/users/{user_id}/meetings', request_data, session)
r.raise_for_status()
return r.json()
@cached_property
def _user_email_to_id_cached(self):
return self.user_email_to_id(use_cache=True)
def user_email_to_id(self, status: str | None = 'active', *, use_cache=False):
filename = CACHE_DIR / f'users_{self._account_id}_{self._client_id}.json'
if use_cache:
users = read_json_file_if_exists(filename)
if users:
return users
users = self.list_users(status)['users']
email_to_id = {u['email']: u['id'] for u in users}
# save list of users to cache
save_json_file(filename, email_to_id)
return email_to_id
def list_users(self, status: str | None = 'active', page_size=300, page=1, all_pages=True):
# noinspection GrazieInspection
"""``GET /users``: Use this API to list your account's users.
Ref:
- https://marketplace.zoom.us/docs/api-reference/zoom-api/methods/#operation/users
:param status: The user's status, one of: active, inactive, pending
:param page_size: The number of records returned within a single API call.
:param page: The page number of the current page in the returned records.
:param all_pages: True to paginate and retrieve all records (pages).
:return: A `dict` object, where the `users` key contains a list of users.
"""
params = {'page_size': page_size, 'page_number': page}
if status:
params['status'] = status
res = self._get(API_USERS, params=params)
final_data = data = res.json()
if all_pages:
while data['page_count'] > data['page_number']:
params['page_number'] += 1
res = self._get(API_USERS, params=params)
data = res.json()
final_data['users'].extend(data['users'])
return final_data | zoom-api-helper | /zoom-api-helper-0.1.1.tar.gz/zoom-api-helper-0.1.1/zoom_api_helper/v2.py | v2.py |
# zoom_audio_transcribe


[](https://pypi.org/project/zoom-audio-transcribe/ )
[](https://pypi.org/project/zoom-audio-transcribe/)
[](https://github.com/python/black)

Transcribe zoom meetings audio locally.
Transcribe zoom meetings audio locally, using .
## Install
Supported python version >=3.6. Supported OS, Linux. Support for Windows and OSX will come in second version.
```bash
pip install zoom_audio_transcribe
```
## Usage
```bash
$ zoom_audio_transcribe
```

Once you are at the menu, select the appropiate meeting and let it run.

Once the transcription is done the, file will be saved in the same folder as the zoom meetings recording. For linux users its `/home/$USER/Documents/Zoom/{meeting_which_was_selected}
| zoom-audio-transcribe | /zoom_audio_transcribe-0.1.1.tar.gz/zoom_audio_transcribe-0.1.1/README.md | README.md |
import json
import logging
import os
import shutil
import wave
import zipfile
from pathlib import Path
import requests
from halo import Halo
from vosk import KaldiRecognizer, Model, SetLogLevel
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
SetLogLevel(-1)
MODEL_PATH = os.path.join(Path(__file__).parent, "model")
@Halo(text="Downloading models.", text_color="green")
def _download_model() -> bool:
"""Downloads vosk model."""
if os.path.exists(MODEL_PATH) and os.listdir(MODEL_PATH):
logger.info("Model already exist.")
return True
logging.info("Model not found. Starting the download.")
model = requests.get(
"http://alphacephei.com/vosk/models/vosk-model-small-en-us-0.3.zip"
)
with open("/tmp/en-small.zip", "wb") as f:
f.write(model.content)
logger.info("File download complete, unzipping.")
with zipfile.ZipFile("/tmp/en-small.zip", "r") as zip_ref:
zip_ref.extractall("/tmp/")
os.mkdir(MODEL_PATH)
for file_name in os.listdir("/tmp/vosk-model-small-en-us-0.3/"):
shutil.move(
"/tmp/vosk-model-small-en-us-0.3/{}".format(file_name),
"{}/{}".format(MODEL_PATH, file_name),
)
logger.info("Model download complete.")
return True
@Halo(text="Transcribing", text_color="green")
def transcribe(path: str) -> str:
"""Transcribe."""
# check if the models is already present
if not _download_model():
raise ValueError("Unable to automatically download the model.")
exit(1)
wf = wave.open(path, "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
logger.info("Audio file must be WAV format mono PCM.")
exit(1)
model = Model(MODEL_PATH)
rec = KaldiRecognizer(model, wf.getframerate())
while True:
data = wf.readframes(wf.getnframes())
if len(data) == 0:
break
if rec.AcceptWaveform(data):
full_result = rec.Result()
text = json.loads(full_result)["text"]
else:
partial_result = rec.PartialResult()
text = json.loads(partial_result)["partial"]
return text | zoom-audio-transcribe | /zoom_audio_transcribe-0.1.1.tar.gz/zoom_audio_transcribe-0.1.1/src/zoom_audio_transcribe/transcribe.py | transcribe.py |
import ctypes
import os
import sys
from datetime import datetime
from getpass import getuser
from pathlib import Path
from re import search
import pyautogui
class UkrainianWriter:
__path = Path('text.txt')
__notepad_butt = 'buttons/8.png'
def __init__(self, ukrainian_text: str):
self.__text = ukrainian_text
def copy_ukrainian_text(self):
self.__write_text_into_file()
self.__open_file_by_notepad()
self.__copy_text()
self.__close_notepad()
self.__delete_text_file()
def __write_text_into_file(self):
self.__check_file_exists()
with open(f'{self.__path}', 'w', encoding='utf-8') as text_file:
print(self.__text, end='', file=text_file)
def __open_file_by_notepad(self):
os.system(f'start notepad {self.__path}')
def __copy_text(self):
self.__find_butt(self.__notepad_butt)
pyautogui.hotkey('ctrl', 'a')
pyautogui.hotkey('ctrl', 'c')
@staticmethod
def __find_butt(butt_name: str) -> None:
while True:
butt_cord = pyautogui.locateOnScreen(butt_name)
if butt_cord is not None:
break
@staticmethod
def __close_notepad():
pyautogui.hotkey('alt', 'f4')
def __delete_text_file(self):
os.remove(self.__path)
def __check_file_exists(self):
counter = 0
while True:
if not Path(self.__path).exists():
break
counter += 1
self.__set_path(f'text{counter}.txt')
def __set_path(self, new_path):
self.__path = Path(new_path)
class ScheduleParser:
__dir_path = Path('Schedule')
__file_name = 'Schedule.txt'
def __init__(self):
self.__check_directory()
self.__check_file()
def __check_file(self) -> None:
full_file_path = 'Schedule/Schedule.txt'
list_dir = os.listdir('Schedule')
if self.__file_name not in list_dir:
with open(full_file_path, 'w') as _:
pass
if not os.path.getsize(full_file_path):
pyautogui.alert(f'1. Here is an empty "Schedule.txt" file.\n'
f'2. Fill "Schedule.txt" file with your info.',
title='ATTENTION')
self.__exit()
@staticmethod
def __check_directory() -> None:
if not Path.is_dir(ScheduleParser.__dir_path):
Path.mkdir(ScheduleParser.__dir_path)
@staticmethod
def __get_full_list(list_to_validate: list[str]) -> list[str]:
return [row.strip() for row in list_to_validate
if ('Інд' in row or 'Ст' in row)
and '-' in row and ':' not in row]
def __get_list_by_day(self, data_list: list[str]) -> list[str]:
result_list = []
week = {
0: 'MONDAY',
1: 'TUESDAY',
2: 'WEDNESDAY',
3: 'THURSDAY',
4: 'FRIDAY',
}
weekday = week.get(datetime.now().weekday())
if weekday == 'MONDAY':
for row in data_list:
if 'пн' in row or ('ср' in row and row.startswith('Ст')):
result_list.append(row)
elif weekday == 'TUESDAY':
for row in data_list:
if 'вт' in row or ('чт' in row and row.startswith('Ст')):
result_list.append(row)
elif weekday == 'WEDNESDAY':
for row in data_list:
if 'ср' in row or ('пн' in row and row.startswith('Ст')):
result_list.append(row)
elif weekday == 'THURSDAY':
for row in data_list:
if 'чт' in row or ('вт' in row and row.startswith('Ст')):
result_list.append(row)
elif weekday == 'FRIDAY':
for row in data_list:
if 'пт' in row:
result_list.append(row)
else:
pyautogui.alert(f'1. It\'s holiday today.\n'
f'2. Run program not on holiday.',
title='ATTENTION')
self.__exit()
return result_list
def __get_all_rows_from_file(self) -> list[str]:
file_path = self.__dir_path.joinpath(self.__file_name)
with open(file_path, encoding='utf-8') as text_file:
return text_file.readlines()
@staticmethod
def __get_sorted_list(list_to_sort: list[str]) -> list[str]:
list_to_sort = list(set(list_to_sort))
pattern = r"[0-9]{2}-[0-9]{2}"
list_to_sort.sort(key=lambda row: search(pattern, row).group())
return list_to_sort
def get_schedule_list(self) -> list[str]:
all_rows = self.__get_all_rows_from_file()
full_list = self.__get_full_list(all_rows)
list_by_day = self.__get_list_by_day(full_list)
sorted_list = self.__get_sorted_list(list_by_day)
return sorted_list
@staticmethod
def __exit():
sys.exit()
class ZoomStarter:
__butt_1 = r'buttons/1.png'
__butt_2 = r'buttons/2.png'
__butt_3 = r'buttons/3.png'
__butt_4 = r'buttons/4.png'
__butt_5 = r'buttons/5.png'
__butt_6 = r'buttons/6.png'
__butt_7 = r'buttons/7.png'
__schedule_without_free_rooms = ScheduleParser().get_schedule_list()
__free_rooms = [f'Вільна зала {i}' for i in range(1, 5)]
__schedule = __schedule_without_free_rooms + __free_rooms
__schedule_len = len(__schedule)
def run(self):
CreateImages().create_buttons_images()
self.__check_language()
self.__start_zoom()
self.__start_conference()
self.__create_rooms()
self.__fill_info()
self.__open_rooms()
@staticmethod
def __start_zoom():
os.system(rf'start C:\Users\{getuser()}\AppData\Roaming\Zoom\bin\Zoom.exe')
def __start_conference(self):
self.__click_butt(self.__butt_1)
self.__click_butt(self.__butt_2)
def __create_rooms(self):
self.__click_butt(self.__butt_3)
self.__click_butt(self.__butt_4)
self.__click_butt(self.__butt_5)
self.__enter_count_of_rooms()
self.__click_butt(self.__butt_6)
pyautogui.moveTo(1, 1)
@staticmethod
def __find_butt(butt_name: str) -> tuple:
while True:
butt_cord = pyautogui.locateOnScreen(butt_name)
if butt_cord is not None:
return butt_cord
def __click_butt(self, name: str):
pyautogui.sleep(0.25)
pyautogui.click(self.__find_butt(name))
def __enter_count_of_rooms(self):
pyautogui.sleep(0.25)
pyautogui.hotkey('ctrl', 'a')
pyautogui.sleep(0.25)
pyautogui.write(f'{self.__schedule_len}')
def __fill_info(self):
for i in range(self.__schedule_len):
UkrainianWriter(self.__schedule[i]).copy_ukrainian_text()
pyautogui.press('tab')
pyautogui.press('down')
pyautogui.press('tab')
pyautogui.press('enter')
pyautogui.hotkey('ctrl', 'v')
pyautogui.press('enter')
def __open_rooms(self):
self.__click_butt(self.__butt_7)
pyautogui.sleep(0.25)
pyautogui.press('escape')
@staticmethod
def __check_language():
while True:
current_lang = LanguageChecker().get_keyboard_language()
if not current_lang.startswith('English'):
pyautogui.hotkey('alt', 'shift')
class CreateImages:
__folder_name = Path('buttons')
__img_1 = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01&\x00\x00\x00-\x08\x06\x00\x00\x00\x03t\xc6\xad\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7o\xa8d\x00\x00\x07\x97IDATx^\xed\x99On\xdc:\x0c\xc6\xdfYz\x82w\x92\xac{\x8e\x00Y\x15=Av]f\xd3\xcdlz\x86 @\xce\x10\xa0\xdb\xa0\xdb\xf4\x12~\xa6mY\x14ER\xd4LfFy\xf9~\x80\x01\xcb"%\xea\x0f?k<\xffL\x00\x000\x18\x10&\x00\xc0p@\x98\x00\x00\xc3\x01a\x02\x00\x0c\x07\x84\t\x000\x1c\x10&\x00\xc0p@\x98\xae\xc5\xeb\xcf\xe9\xe6\xcb\xbf\xd3\x17\xe5\xba{\xdal\x12\x95\xed\xf7I\x9a,(mVmY\x84|\x9f\xa7;aS\xc5\xe2\x8ck\xbf\xee\x9e7c\xc1\xb1\xbe\xbb\xdf\xd7\xe9\xe1u{\x96p\xda,\xc7\x17\x18\x1b\xb8\x18\x10\xa6k\xf1\xf4]$A\xbex\xc2\xbc>|Um\xaa$t\xda\xbby\xf8\xb3\x19\x19\x04}\xedXX\x02\x07\xc4\xc5\x8c\xa7\xdbW\x8a\x89"L\'\xcf3\xc4\xe9\x1a@\x98\xae\xc5\x9e0\xde\xc6\xe7\x89\x97\xec\xd8\xb3\x9b\x9f\xd3\x9a\x87\x7f\xa6\x87\x1bi\xa7=\xd3\x88\xfb\xbe>|/\x12\xff\xe9.\xd9\xb4Of9\xf1\xbdXtT_Up<a\xf2\xfb=el\xe0\xfd\x810]\x89=\xd9vqQ`\xc9\xa7\x9f\\R"2\xb1b?ubbp\x82/\x8b\xcfM^v\x12j\x9e\xde$\x96\xef\xd67=\xcb"R\x0bSh\x9e5\xa2c\x03g\x01\xc2t%\xdeG\x98r\xd2\xec\xc9\xc9\xda\xd3\x9ei\x1c\xe7\x1b=\x91\xb1\xb6\x1av\x1a\x11\xdfl\xf3^\xc2\x14\x1f\x1b8\x0f\x10\xa6+\xc1\xc5%_"\xb1\xf87\x97=\xb1x\xd2p\xc1\x92\xdf[\xd2\x15I\xac\xb8o\x16\x01\xdb\xa6\x80\x8f\xc1\xfa\xe8m\x11\xf4\r\tSq\xd5vD\xf7\xd8\xc0\xd9\x800]\x89:\t\xf2\x95\x7f:\x94"\xa4]\xfc$\xa5\xb6\x19<)D}U;G4\xb20\xe8b\xe0\x11\xf5\xcd1\xd5v\xb1y^\xe9\x1d\x1b8\x1f\x10\xa6A(\xde\xecB\x10\xca\x84\x99\xdf\xe2\xd5\xf7\x0f.`[r\xaa\xa7-\x8d\xe3}y\\\xc5\xf7\x9f\x1d\xedC}\x94\xb8\xaf\'L\x12o\x9e9\xed\xb1\x81s\x02a\x1a\x86\xf8w\x8d\xea$a}\xa8\x8d|\xc0=\xc5\xb7%\x1e\xac\x8d\xee\xe4\xee\xf0\xed\x11\xa6\xf8<\x9f"\xaa\xe0T L\xc3\xc0\x12\xc6M\x04\xc5\xce\x12\x11v\xf21\x93\xfb\x14\xdfF\xf2\xf6\tFI\x8f\xef\xd1\xc2\xe4\xce3\x84\xe9\x9a@\x98\xae\xc2\x9c\x1cw\xe5f/~b\xb0\xef\x1aOO\xe57\x0e\xfe\x13c\x17\x12\xe3#\xb1j+\t\xfb\xce\x89*\x12\xd4\x8ay%*\x00\x1a}\xbe\xb60E\xe7\xb9wl\xe0\xdc@\x98\xae\x02K\xbc\xea*\x7f^p\x81(.\x91,\xa6\x1d]\x8d\xc4\x8a\xf9\xb2\x13Du)?\x89\x0c\xc1\x0b\xd1\xe9\xeb\nSh\x9e;\xc7\x06\xce\x0e\x84\xe9J\xa8b\xa0$\xa1fg\x9e~\xd8\xcf\xb2\xa6\xad$\xe0\x1b\x8dy\xa1\xe3\x1bQE\xa7\xaf-L\xf1\x98\xbb\xc6\x06\xce\x0e\x84\t\x000\x1c\x10&\x00\xc0p@\x98\x00\x00\xc3\x01a\x02\x00\x0c\x07\x84\t\x000\x1c\x10&\x00\xc0p@\x98\x00\x00\xc3\x01a\x02\x00\x0c\x07\x84\t\x000\x1c\x10&\x00\xc0p@\x98\x00\x00\xc3q\x19az\xf95\xdd\xde?OoK\xe1\xf7t\xb8\xfd1=\xae\x85\x8f\xc1G\x8f\x1f\x80\x0f\x86"L\x94x\xdf\xa6\xdb\xc3\xef\xad\xac@\x89\xda\x99\x9c/\x87\xb9Mjw\xbe\x0e/\xdb\xc3\x0f\xc4G\x8f\xbf\x06\x02\x1b\xe7s\xce\xd5\xdb\xe3\x8fM\x076M\xd8/>\x17\xbdzA\xf6\xbf&J\xa1%\xa7\x0c?C\x98~L\xf7\xf7\xd6B\xfc\x9d\x1e\xe7:\xbb\x1e|\x0c>g\xb2\x1d\xc7\'\x9c\xab\xb7\xe79\xc7\xf5_\t\x8b`\x89\xba\xb8^\x90\xfd*L\xa9N\xf33\x85\xe9pHjYBA\xdd?>W\x0b\xc5O\x149hB,j\xf3\xb4E\xc1\xb2\xb6v[\xaf\x1dQW\x94{\xea\x12\x8e\x8d\x1b\x7f\xdbvY\xd4jl\x04\x1f7\x7f.cLe9O\xc9\xaf\x15\x83\xe6\x976\n\xe1\xf9\x97u\xeb\x9ao\xbe\x8b]ns=UZ1R]\xf2\xdf.m\xcf\xbc\xcc\xc9\xb1\xfb\xf1\x18%N\\{y\xbb\xbc\xbdY\x95[sE4\xd6\xcd\x1dC\xc3W-\xd3=o\x87\x97\x85\x9f\xb3v\xda\xde\xe4\xd0\x9c\xdd?\xfe\xddJ\xc2\xb7(\xaf\xf7q\xbd {\x16?\xc5\xa1\xf8\x99\xc2Tm\xf0\x05\xbd\xaeT\xd0m#\xec\x9dq\xdby!\xe6\x01\xdcW\xedr\xb8\xbdu/\xdb)\xe3\xb1\xfd\x08\xaf.a\xd9\xb4\xe2o\xdb\xd2\xdc\xacI[\xf6]\xcc\x99\xf3\xb6\xea+\xd71\xe4~\x98\xdd\xb2I\xb5\xcdm\xcfs\xb9\xe6d\xc7\x12\xbeh\x8f\x901F\xf6\xcc\\f\xf5\xd2\xbe\xc4\x8a+\xd2\x0f\x8f\xab,\xb7\xe7J\xb4W\xad\x9b?\x06\xdf\xd7\x8a\x8b\xee\xe5\xdc\xf6\xad\x9d\xb573s}q\x92\xe1\xbe\x04/\xa7{iChut\xcf\xe2/\xc6\x9dq\x84i\x9b\xc8}\x11yYv\xa4\x05\xa4L\xd6\xbc\xa8\x87\x17\xcd\x9ec\xf8\xba\xed\xc86\x8f\xadK\x186\xcd\xf8[\xb6|\xc1\x8d>\x16,;\xa2\xa3\xec\xce\x13\xbf\xa7\xfe\x14\xc1\xb4\xfc\x1f\xa5\xf0H\xb8\x0f\xd1*\x13\xf4L[\xf7\x84\xf6,\xb1\xd5Uq\xf5\xf6\xc3\xcb\xd6\xbd1W\x0b\xde\xba\x11V\x9bDt\xcd\xe9^\x8eQ\x19\x8f\xb7\xf6\xa1}l\xcfc)\xb0\xb9.\xae\x17V\xfc\x19W\x98\xe2\xf7\xb2a\xcd\x96&\x9e\xecx\x9d\x82\xf9\xe6\xf0\xda\xe1\x9b\x85\x90~\xf3\x9b\xa9\xb8\xec\xba\xf5\xf8*\xfd\xad~%-[*\xa7\xb9\xe2ut_\xc6\xe1\xc5\x18;\xf6+1\xd0\xdc\xaa\xfd\xcf{u~{\x97c\xd7\xc6@\xf7k\x0cy\xaeW\x96M\xd8\x15c\x8a#!\xfb\xe1\xf6\x04\xc5#\x9f%\xac\xb8"\xfd\xf0\x98Y\xdc\xe1\xb92\xfc\x85\xcf\n\x1fC\xcb\xd7\xab\xe3c\xe2\xe5\xd4\xa7\xb5vV\x9d\xa0:\xc5\x90-\x8fE\xf6/\xfbh\xdds\x7f}]\x1b\xc2\xb4m\xb8Y\xf5J5\xb4:M\xf0\xce\xb7\xfa\xf9mV\'}M\xb3\x1f\xab\x9d\xf9-`/$\xefOi3\xd5-\x9b\x91\xca\x8aM(~\xdf\x96\xc6\xb6>\'\x94>\xbc6\xf7\xba`Y\x8d\xc1\xba\xa7\xcd!N\x01\x9e\xff\xf2\xdd$=\x9b\xa1\xb9\xaf62\xabo\x96\tz&\xf6\x8cY/\xd9\xece\\\xdd\xfd\xf0\xb2u\xaf\xccU\xd1~B\xab\xa3g\xde\x18\x13\xb2\x8e\x97y\x1b\x84\xd2\xa6\xb7v\xe1},\xfb\xf0ls]L/\xac\xf83MaZ\xcb<\xd1\x89\xd2f\xf9\xad\xcc6f\xf1\xdby\xf7\x17\x93\xb7\xb7\xc5\xe1\x8bNp\xdb\x9ev\xa4\x1f\xb7s\xeaLa\xea\xe9\xd7\xb2\x95~e\xb9\x9c3\x8e\xef\xa7\x97\xedxs?\xec\xf9"\xea\xdc>0\x86\xc5\x87\xdd\xb3\xf5_6%\xebS\xc6@\x84\xf6\x0c\x9b\x0f{~\x08#.*6\xfb\xb1\xe3\xcc\xb6\xb2\xfd47\xb2=N{\x0c\xbe\xaf\x15\x17\xdd\xe7\xfe\xcb\xf2\xd6\xa7\xb9vV\x9dD\x9eb<[Y\x97\xfa\xb1\xfc\xe9\xde\x8a?\x13\x10\xa6\xac\x82\x99\xdaf\x99\xe4%\xa0\xf9\xaa\xde\x9e\xde\x17\xfe\xc4*J\xb5/\x1fP\xa4\x1dB\xfaq\xbb\xbaM~\xd2\xd2\xdf4=\xfdj\xb6\xebs\xdeO\xbe\xe4\xa6\xda\xae}\x1ed\x7f\x91\xb2\x17\xef6\xcf\xbc\xaf\xb0\x7f\xd9\xd6*@\xf4")\xdb\xac\xff\xb5\x951\xac\xf8{f\xb6\x9f\xdf\xeez\xbd\xc4\x8ak-7\xfb\xd9\x1f\xc8rk\xae\x08\xf2a\xf5r\xdd\xdc14|wc^\x16>\xe9Z\xf2s\xad\xb3\xd7\xce\xdb\x17%4g\xfa\x01AR\xd7\xf9zA\xf7L\x88H\xe8\x15qV\x84\t\xbc?b1v\xac\xe7\x97\xa0\xdeP\xe30Zl\xc7\xc4s\xc11\x18\xc9}\x12\xd5w\xa6s Of\x19\x08\xd3E\xb0\x04\xc8z~\tFK~\xceh\xb1\x1d\x13\xcf\x05\xc7p\x0ea\x9a\xa9O>\xef\x8b\xfdS\x16\xc2\xf4\x89\x810\xc5\x19\\\x98\xfe\x87@\x98\x00\x00\xc3\x01a\x02\x00\x0c\xc64\xfd\x07xFP8\r\xd7\xf3\r\x00\x00\x00\x00IEND\xaeB`\x82'
__img_2 = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00A\x00\x00\x00\x17\x08\x06\x00\x00\x00T "\xaf\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7o\xa8d\x00\x00\x01\x05IDATXG\xed\x93\xcd\r\x830\x0cF;Awb\x9e\xdeX\x83#+\xb0\x04b\x15\x16\xe0\xc0\x01q@HH\xae\xf3\x03$&\x84\x80R\x89\xb6\xfe\xa4w\xc0I\x8c\xf3Z\x1e\xcf\xb4\x85\x7f\x87% ,\x01a\t\x08K@\x02$t\x907 S\x16d\xad\x18\xd5B3@b\xd6\xbf\x0c\x96\x80\xb0\x04$\xb2\x84u\xef\x9a\x11^\x01\xfbUo\xdf\xf9\x1eJ]\xb1#\xd6\xe7\xb5\t\xf2L\xbf\xeb\x04\xa7$\xec\xc6+AD_\xe4\x92\x04\x11\xf3\xa24\xb7\x93@!\xc3\x1dJ\xa0\xb8.\x17Z\x0b\'\xf2\xe70\x0fCC$\xd0\x7f\x06F\xf5>8o\xbd\xc3U#\xd9\xfdql\xa2JH\xaaI>\xd6U\xa7\xd6\xb3\x01jY\xd1\x03/\xcf\xdb\x88\xde\x87\xe7\xe5{}\x12\xe6\xda:\xf3\xd2\xcb\xc3G$,i\xa6\xcd%\xcc=u\xd5[\xbdC\xce\xdf^\x82\xb9W\r\xe4\x1a\xd8\x84\xf6\x0e9\xef\xab\x91\xc4\xfb\x1c~\x1f\x96\x80\xb0\x04\x84% ,\x01a\t\x08K@XB\xda\xc2\x1bw\x83j\x0f\xed\xc1\xd5\x15\x00\x00\x00\x00IEND\xaeB`\x82'
__img_3 = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x1c\x00\x00\x00\x1e\x08\x06\x00\x00\x00?\xc5~\x9f\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7o\xa8d\x00\x00\x00\xbfIDATHK\xed\x941\x0e\xc3 \x10\x04\xf3\x0e>\x06|\x0e((\xf8%\xd1\x15\x1b\xed\xd9\x10l\t\x119\xa2\x98\x06/;\x92u\xc7\xcb\x18SW\xb2\x85\xd3QB\xe7\\M)\xd5R\xca\t9\xf7\xde\x7f\xb2\xd6\xda\xafY\xe9\xe2n\xa0\x841\xc6f\x01\x90"dC\x08\xcd\x0c\xe0,\xa3\x84\xad\x8bG\x90\xcd97\xbf3\xdc\r\xb6\xf0\x04\xb2\xcf\x14\xf6\xc6\x1c\xdc\x99R\x99x\xee\x06J({\xd6\x93\xca9\xef\xe1\x9d\x9de\x94p\x05\xbf\x15\x8e~\x93<gW\xb3S\x9e6\x19\x14d{2 \xdf\xb9\x1b(a\xeb"#\xabp5+p7\xd8B\xc5\xf3\x85\xa3\xc9\x9b>\xa5\xa3\xa7\x8dw\xeb\xce3\xc8(\xe1\n\xb6p:\xff.4\xf5\r\x93nM\xa1\xdc\xaen\xe0\x00\x00\x00\x00IEND\xaeB`\x82'
__img_4 = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00z\x00\x00\x00\x13\x08\x06\x00\x00\x00_\xa2\x19v\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7o\xa8d\x00\x00\x02\x18IDAThC\xed\x95\xcd\x8d\xc4 \x0c\x85\xb7\x96\xa9`+\xc9y\x1a\xc9q\x1a\xc9e*\x19i*\x89\xa6\x13\x96\x07\t\xd8\xe6\'&\x9b=\xac\xe0\x93"%`\x1b\xdb\x0f\xc8\x97\x19t\xc1\x10\xba\x13\x86\xd0\x9d\xb0\t\xfd6\xf3\xedn\x96\xd5\x7fEJ\xe3\x83\xff\xc6\x10\xba\x13\xda\x84~=\xcc\xed\xf6\x1d\x9e\xf9\x95\x1f\x9f\x96\xcf6!\xe3*\xe3\x9d\xf2\xfb\x98e\x8ac\xfe\x81\x8f\x8cU\x03\xb6<FR\xcb\xebi\xa60\xff0\xa1\x053\xb5\xb5 \xc7\xe9i\xd6j-\xe59}<o\x1brv6)\rB\xdbF\xce$\x88kv,4\xb0\xa2\x11\xfbx\xb9\x90z\xbc\xb3~\xa0\xe6{\x84\xb0Mj\xe1\x8d\\\x97{\xfcF\x1e\xf3\xdb\x8d\x83(T-\x9f\xca\x9c2\x1e\xcb\xc1\xe2D\'~;Dh\xb2+\xd8C\x13\xa1\xc8$7\xd0\x9c\xb0p\xa5\x90\x04:w\xd6\x0f\xb4\xf8J\x84m\xb5\x16@\xc7\xf0\xbeo\n\xdc.\x9aM{4w\x14\x0f\xe3\xf4&\xb4\xb0\xcd\x19i\xba\xba\xdd\xee)m\x02w\xb20F\x17\x81?\xb5\xe7>\xe5x\xb2\x80\x86<\x92Z\xd2\x1c\xd8\x95\xc8\x90\xb6\xb2\x16\x1a\x17 \xcf8\x86\xd3\xe4rF\xb3\xc3\xa9\xaa\xd5\x92\xe6Fk\xc9\xc7\x93>2\xa7\\\x9e-BCHrE\xa8|\x12\x9b\x86xa\xe3\x88\x82\x0e\xf3h\xfd\xa6\xd4ls~\x18#\x9b\x01\xb9YA\xb0\x11\xd9)+\xd5R]\xcf\x92\x8dGm\xfe\xe2D\x8b\x06\xfbSu\xe0\x93\xc4=\x13\x0f\xb4\xf8U\xd6\x04\xae\x11\x8au\x1c\xf4\x1b\xefV$\xf2\xffK\xff\x87\xd6\xc6^\xb1xd\xa3#2fi=\x90\x8b\xc7m\\\x0e\xa4\x1f\x8a\x7f4]`\x87\x8e\xfb\xdd\xb3\xef\xcaiy\x869\xdfl:\xb7_\x8d\x99\xc4\x15\xf1RZ\xfcrkF{\xef\xa3\xbd\xba3\xb5,\xe4t\xb2\x9b\xc5Sjt\x84\xe6\x97\xcb\x95~\x176\x13\xb3\xe1\xfd\xc8\xe5\x046\xa1\x07\xc7\xa4"\xe4\x800\xec*\xfd%W\xc5\x1bB\xabQ\x08]\xf8?\x9e\xe6\xc2xCh5u\xa1\xdd\x15\xab8\xf1Z\xae\x8e7\x84\xee\x84!t\'\x0c\xa1;a\x08\xdd\x05\xc6\xfc\x00\x87\xff\x12J\xf75\xeaM\x00\x00\x00\x00IEND\xaeB`\x82'
__img_5 = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00+\x00\x00\x00\x12\x08\x06\x00\x00\x00\xc2('\xa5\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7o\xa8d\x00\x00\x00\xa3IDATHK\xed\xd5\xc1\t\xc3 \x18\x86\xe1\xce\xe2\x04\x9d\xa4\xe7N\xe0\x06=f\x06\x05=\xb9\x80\x8e\xd1IB\x87\xd0\x9b\xf2\xb5\xbf\xb4`\x03\xa9\xd0b0\xc5\x07\xc2\xcfw{\x0f\x01\x0f\xd8\x91\x11\xfb\x8b\x10\x02\xb4\xd6\xf9.u\x15\x9bR\x82\x94\x12\x9c\xf3|i\x97*\xb1W\\\xd8\x11's{\xee\xb6\x9cs9\xf4\xf5\xd1.\xad\xc6\xce\xe6\x0c\xc6&\x98\xc7\xdd*\xb6\xa6\xfa\x1bP\xf4\x88\xfd\xc2\x88me\xc4\xb6\xf2_\xb1[\xb2\xd6\xbe=\n\xb4K]\xc5\xc6\x18!\x84\xc8\xa1\xf4\xdc\xd2.u\x15K\xbc\xf7PJ\xe5\xbb\xd4]\xec';\x8a\x05\xee\x02\x05\xd7]\xfe\x86k\xda\x00\x00\x00\x00IEND\xaeB`\x82"
__img_6 = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00C\x00\x00\x00\x17\x08\x06\x00\x00\x00P\xd5\xf2\x92\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7o\xa8d\x00\x00\x01iIDATXG\xed\x96A\x8e\xc20\x0cE\xe7\x04s\'\xce\xc3n\xae\xc1\x92+\xf4\x12\x15\xb7`\xcd\x05\xba`\x81X \xa4J\x9e4\x8d\x93/\xc7q\xab\xd1 @\xf8K\x7fA\x9c:\xf1s\x9a\xf2\xf5\xfds&\xf7l\x87\x01v\x18`\x87\x01v\x18\xe0U06\x87\x91\xa4N\x87\x8b:\xf7\x9d\xbd\x00\xe3J}*^\xea\xc3`\\h?\xa4\xcai\xa4\xfd\x0eb\xbb\x1b\xf5\x1f\x05#\x14|\xd2@(\xde\x1e\xe3\xc4\xa2\xe3\x15\xe2\xf5\xe9\x92\xa7\xaaz>\xa8\xcc\xc1\xa6\xb0\xee\xb4m\xe4\x9e5\xc59\xb6\xbc\x7fv\x1bFw\x8f\xa9h\xb8\xd1F\x8bGk\x1bM\xca\xcfi\x1b\xc6\r\xea9l\x18\x93\xb0`\xa9\x7f\x86\x91/M\x0b\x06\x03\xc3\x05\xf3\x89"\xea;\x98\x1b\xcd\x1b\xe4\xce\xca\xb1Rx\xfbN\xd2\x8a\\;f{\xf9d\x18\xc9t`\xa5\xa0\x0c#\xe7\n\x92p9\x16_-\r\x06\x17%\xb5\x16\x86\x90\xd1\\\xe3\x02\xc5d\xd8\xc9`\xbe@s\x91\x107\xef\x1a.\x96c\xad\xdf\x05\x06\x03\xcfp\xd4\xfc\x16\x8cvni\x03F0vThNX\x16\xa8\xc4\x1dh\xe4\xe8;\xe3\xd9\xa4i\x8d\xea?\xce0>\tF4\x9e\x10\x16.\xaa\x14\x85_\x13\x05\xc6"\xc8\xa4z\xde\xb4\xee\x9a\xc2qL\xe8o\xaf\xc9\xa3\x9d\x8a\xd46\x97\x00\xb6:\xf8(;\x0c\xb0\xc3\x00?\x11\xc6\xeb\xd9a\x80\x1d\x06\xd8a\x80\x1dF\xf6\x99~\x01t\xa2\x11b \x82\x079\x00\x00\x00\x00IEND\xaeB`\x82'
__img_7 = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00:\x00\x00\x00\x0f\x08\x02\x00\x00\x00:nKa\x00\x00\x00\tpHYs\x00\x00\x0e\xc4\x00\x00\x0e\xc4\x01\x95+\x0e\x1b\x00\x00\x02\x1eIDATH\x89\xd5U1k\xdb@\x18}\xf6\t\x1f\x08d\x110U\xc8\xaa\xc5\x04\x04E\xfe\x07\xc6qi\x86\x0c\x85l\xf6\x90\xfd\x96\x88@\x0b\x9e\x03\r\x18u\xd1\x96\xa1\x83\xbd\x05:tH\xa9k\xfc\x0fl\n\x82\xd2\xc5\xab\x89\x12\x81Q\x05\x82\x0b\x11t\x90d\xcb\xa9m\xb5\xc5\xd4\xcd\x9b\x8eO\xa7w\xef\xfb\xbew\xdf\xe5\x8a\xa7wx:\x10RkzeJ\xf5x\x1dZ\xedik\xb2\rEk\x91\x8b\xab\xabK^\x83>\xfa6\xeeO\xf5\xebp\x0b\xa2V#\x0f\x00\xa0W\x91V\xdb\x97\rW6\xdcj?\x04\xa0\xd6\xc4\xe66\xb5-\x81\x00\x00z\xa1\x0e\x00\x9c\xbd\xe7Qtx\xfd\xc3\xd2v\x98B\x8f\xf4\xa0|\xb0\xc3\x94\xd4\x1f\xb6/\x7f&\xa33Qu\x82\xeaE\xb0\x7fR\xb24\xc0\t\xaa\x1d\\F\xc1/d\xd0\xa0\x987'\xf2\x18g\x86\xdf\x99\xb3\xcc\x82A\xf9\xf5:\xfe\xe1\xa2\xdc<\x80\xca\xae\x00\x00\xf6}\x8a.\xfc~\x0b\x00\xea\xae\x805\xd0%K\x03\xc0\xd9\x9c\x97^&\xa6Rk\xc5\xf3\xbd\xec\x82\xfd\x11\xf2Y\x1b\x1eZ\x17\xael\xf8=\x00\xe0\xccp\xe5\xa4\x03\x00ys@\x01\xf4\xba\xa9\xb2)\xf8\xd4ve\xc3e6\x00\xf2\xf29\xc9\xe2\x0fW\xf3/\x81\x00`x\xf3\x00\x10h\x85&xr0)?\x03\x80\xf1\xcd\xea\xab\xa6\xd0\xc8B\x1fG\xa9\xa0\xc3?L\x00\xe0\x9b\x13BKk\xa5\x96I-\x00\xb1I\xb2\xb2\x00\xa0\x88\x03S\x8cR\x9a\x8d\xa9<\x00\x8c\xee{\x11\xe3I\xdc\xc7\xcaa\x91)\xbfHy\x04\x87\xf7\x1c\x00\xf4\xf40%K!\xfb\x00@^i\x04\x0b\xd9rf\xc4U\xfc\xdd\x1b\xec\x04U\xc3\x95\xbb\x1c \xecE,,\xb2&?\xee\x16\xbc\x06\x85&y\xa64\xdb\xbf\xd0\xe5%\x08\xdfv\x02\xf5LTk\xc5\xf3\xaf\xd3V\x1c\x9cW1#\xdb\xbfB\xe2\xdd\x91/\xb7\x83qJ\x8a\xd5v\x8f3\x0f\x9b\x04\xefl\x00\x845\xc5J\x14q\x02\xd6\x0f\x13\x86\x85Q`\x99%\xcf\x94\xea\xd9UH\xa0\x88\x03\xb3\xe45hzd\xe56\xf6\x08\xef\x89\xab\xa6\xcf\x06\x919\x19\xfe/<1\xb9\x9b3\xc3?\xc1O\x15\xa5\xe5[\x0b\x8c4v\x00\x00\x00\x00IEND\xaeB`\x82"
__img_8 = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\xc2\x00\x00\x00\xaa\x08\x06\x00\x00\x00\xffF\x90\x06\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7o\xa8d\x00\x00\x01\x80IDATx^\xed\xd3\x01\x01\x00\x00\x08\xc3 \xfb\x97\xbe\x0b\x02\x1d\xb8\x01\x13\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01"\x02D\x04\x88\x08\x10\x11 "@D\x80\x88\x00\x11\x01\xb6=\x8f\xd2j\xc0\xa7\xa8\xa4z\x00\x00\x00\x00IEND\xaeB`\x82'
__images = (
__img_1,
__img_2,
__img_3,
__img_4,
__img_5,
__img_6,
__img_7,
__img_8
)
def __init__(self):
self.__check_folder()
def __check_folder(self):
if not self.__folder_name.exists():
Path.mkdir(self.__folder_name)
def create_buttons_images(self):
for i in range(len(self.__images)):
with open(f'{self.__folder_name}/{i + 1}.png', 'wb') as img_file:
img_file.write(self.__images[i])
class LanguageChecker:
__languages = {'0x436': "Afrikaans - South Africa", '0x041c': "Albanian - Albania",
'0x045e': "Amharic - Ethiopia",
'0x401': "Arabic - Saudi Arabia",
'0x1401': "Arabic - Algeria", '0x3c01': "Arabic - Bahrain", '0x0c01': "Arabic - Egypt",
'0x801': "Arabic - Iraq", '0x2c01': "Arabic - Jordan",
'0x3401': "Arabic - Kuwait", '0x3001': "Arabic - Lebanon", '0x1001': "Arabic - Libya",
'0x1801': "Arabic - Morocco", '0x2001': "Arabic - Oman",
'0x4001': "Arabic - Qatar", '0x2801': "Arabic - Syria", '0x1c01': "Arabic - Tunisia",
'0x3801': "Arabic - U.A.E.", '0x2401': "Arabic - Yemen",
'0x042b': "Armenian - Armenia", '0x044d': "Assamese", '0x082c': "Azeri (Cyrillic)",
'0x042c': "Azeri (Latin)", '0x042d': "Basque",
'0x423': "Belarusian", '0x445': "Bengali (India)", '0x845': "Bengali (Bangladesh)",
'0x141A': "Bosnian (Bosnia/Herzegovina)", '0x402': "Bulgarian",
'0x455': "Burmese", '0x403': "Catalan", '0x045c': "Cherokee - United States",
'0x804': "Chinese - People's Republic of China",
'0x1004': "Chinese - Singapore", '0x404': "Chinese - Taiwan",
'0x0c04': "Chinese - Hong Kong SAR",
'0x1404': "Chinese - Macao SAR", '0x041a': "Croatian",
'0x101a': "Croatian (Bosnia/Herzegovina)", '0x405': "Czech", '0x406': "Danish",
'0x465': "Divehi",
'0x413': "Dutch - Netherlands", '0x813': "Dutch - Belgium",
'0x466': "Edo", '0x409': "English - United States", '0x809': "English - United Kingdom",
'0x0c09': "English - Australia", '0x2809': "English - Belize",
'0x1009': "English - Canada", '0x2409': "English - Caribbean",
'0x3c09': "English - Hong Kong SAR",
'0x4009': "English - India", '0x3809': "English - Indonesia",
'0x1809': "English - Ireland", '0x2009': "English - Jamaica", '0x4409': "English - Malaysia",
'0x1409': "English - New Zealand", '0x3409': "English - Philippines",
'0x4809': "English - Singapore", '0x1c09': "English - South Africa",
'0x2c09': "English - Trinidad",
'0x3009': "English - Zimbabwe", '0x425': "Estonian",
'0x438': "Faroese", '0x429': "Farsi", '0x464': "Filipino", '0x040b': "Finnish",
'0x040c': "French - France", '0x080c': "French - Belgium",
'0x2c0c': "French - Cameroon", '0x0c0c': "French - Canada",
'0x240c': "French - Democratic Rep. of Congo", '0x300c': "French - Cote d'Ivoire",
'0x3c0c': "French - Haiti", '0x140c': "French - Luxembourg", '0x340c': "French - Mali",
'0x180c': "French - Monaco", '0x380c': "French - Morocco",
'0xe40c': "French - North Africa", '0x200c': "French - Reunion", '0x280c': "French - Senegal",
'0x100c': "French - Switzerland",
'0x1c0c': "French - West Indies", '0x462': "Frisian - Netherlands",
'0x467': "Fulfulde - Nigeria",
'0x042f': "FYRO Macedonian", '0x083c': "Gaelic (Ireland)",
'0x043c': "Gaelic (Scotland)", '0x456': "Galician", '0x437': "Georgian",
'0x407': "German - Germany",
'0x0c07': "German - Austria", '0x1407': "German - Liechtenstein",
'0x1007': "German - Luxembourg", '0x807': "German - Switzerland", '0x408': "Greek",
'0x474': "Guarani - Paraguay", '0x447': "Gujarati", '0x468': "Hausa - Nigeria",
'0x475': "Hawaiian - United States", '0x040d': "Hebrew", '0x439': "Hindi",
'0x040e': "Hungarian",
'0x469': "Ibibio - Nigeria", '0x040f': "Icelandic",
'0x470': "Igbo - Nigeria", '0x421': "Indonesian", '0x045d': "Inuktitut",
'0x410': "Italian - Italy",
'0x810': "Italian - Switzerland", '0x411': "Japanese",
'0x044b': "Kannada", '0x471': "Kanuri - Nigeria", '0x860': "Kashmiri",
'0x460': "Kashmiri (Arabic)",
'0x043f': "Kazakh", '0x453': "Khmer", '0x457': "Konkani",
'0x412': "Korean", '0x440': "Kyrgyz (Cyrillic)", '0x454': "Lao", '0x476': "Latin",
'0x426': "Latvian",
'0x427': "Lithuanian", '0x043e': "Malay - Malaysia",
'0x083e': "Malay - Brunei Darussalam", '0x044c': "Malayalam", '0x043a': "Maltese",
'0x458': "Manipuri",
'0x481': "Maori - New Zealand", '0x044e': "Marathi",
'0x450': "Mongolian (Cyrillic)", '0x850': "Mongolian (Mongolian)", '0x461': "Nepali",
'0x861': "Nepali - India", '0x414': "Norwegian (Bokmål)",
'0x814': "Norwegian (Nynorsk)", '0x448': "Oriya", '0x472': "Oromo", '0x479': "Papiamentu",
'0x463': "Pashto", '0x415': "Polish", '0x416': "Portuguese - Brazil",
'0x816': "Portuguese - Portugal", '0x446': "Punjabi", '0x846': "Punjabi (Pakistan)",
'0x046B': "Quecha - Bolivia", '0x086B': "Quecha - Ecuador",
'0x0C6B': "Quecha - Peru", '0x417': "Rhaeto-Romanic", '0x418': "Romanian",
'0x818': "Romanian - Moldava", '0x419': "Russian", '0x819': "Russian - Moldava",
'0x043b': "Sami (Lappish)", '0x044f': "Sanskrit", '0x046c': "Sepedi",
'0x0c1a': "Serbian (Cyrillic)",
'0x081a': "Serbian (Latin)", '0x459': "Sindhi - India",
'0x859': "Sindhi - Pakistan", '0x045b': "Sinhalese - Sri Lanka", '0x041b': "Slovak",
'0x424': "Slovenian", '0x477': "Somali", '0x042e': "Sorbian",
'0x0c0a': "Spanish - Spain (Modern Sort)", '0x040a': "Spanish - Spain (Traditional Sort)",
'0x2c0a': "Spanish - Argentina", '0x400a': "Spanish - Bolivia",
'0x340a': "Spanish - Chile", '0x240a': "Spanish - Colombia", '0x140a': "Spanish - Costa Rica",
'0x1c0a': "Spanish - Dominican Republic",
'0x300a': "Spanish - Ecuador", '0x440a': "Spanish - El Salvador",
'0x100a': "Spanish - Guatemala",
'0x480a': "Spanish - Honduras", '0xe40a': "Spanish - Latin America",
'0x080a': "Spanish - Mexico", '0x4c0a': "Spanish - Nicaragua", '0x180a': "Spanish - Panama",
'0x3c0a': "Spanish - Paraguay", '0x280a': "Spanish - Peru",
'0x500a': "Spanish - Puerto Rico", '0x540a': "Spanish - United States",
'0x380a': "Spanish - Uruguay",
'0x200a': "Spanish - Venezuela", '0x430': "Sutu",
'0x441': "Swahili", '0x041d': "Swedish", '0x081d': "Swedish - Finland", '0x045a': "Syriac",
'0x428': "Tajik", '0x045f': "Tamazight (Arabic)",
'0x085f': "Tamazight (Latin)", '0x449': "Tamil", '0x444': "Tatar", '0x044a': "Telugu",
'0x041e': "Thai", '0x851': "Tibetan - Bhutan",
'0x451': "Tibetan - People's Republic of China", '0x873': "Tigrigna - Eritrea",
'0x473': "Tigrigna - Ethiopia", '0x431': "Tsonga", '0x432': "Tswana",
'0x041f': "Turkish", '0x442': "Turkmen", '0x480': "Uighur - China", '0x422': "Ukrainian",
'0x420': "Urdu", '0x820': "Urdu - India", '0x843': "Uzbek (Cyrillic)",
'0x443': "Uzbek (Latin)", '0x433': "Venda", '0x042a': "Vietnamese", '0x452': "Welsh",
'0x434': "Xhosa",
'0x478': "Yi", '0x043d': "Yiddish", '0x046a': "Yoruba",
'0x435': "Zulu", '0x04ff': "HID (Human Interface Device)"
}
def get_keyboard_language(self):
"""
Gets the keyboard language in use by the current
active window process.
"""
user32 = ctypes.WinDLL('user32', use_last_error=True)
# Get the current active window handle
handle = user32.GetForegroundWindow()
# Get the thread id from that window handle
threadid = user32.GetWindowThreadProcessId(handle, 0)
# Get the keyboard layout id from the threadid
layout_id = user32.GetKeyboardLayout(threadid)
# Extract the keyboard language id from the keyboard layout id
language_id = layout_id & (2 ** 16 - 1)
# Convert the keyboard language id from decimal to hexadecimal
language_id_hex = hex(language_id)
# Check if the hex value is in the dictionary.
if language_id_hex in self.__languages.keys():
return self.__languages[language_id_hex]
else:
# Return language id hexadecimal value if not found.
return str(language_id_hex)
if __name__ == '__main__':
ZoomStarter().run() | zoom-auto-creator | /zoom_auto_creator-0.0.4.tar.gz/zoom_auto_creator-0.0.4/zoom_auto_creator.py | zoom_auto_creator.py |
import datetime
import json
import os
import urllib
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
OSX_ZOOM_DIR = f"/Users/{os.getlogin()}/Library/Application Support/zoom.us/data/VirtualBkgnd_Custom/"
def read_config_file() -> dict:
"""Read the config file at $HOME/.zoom-background-changer.
Use config file's contents to build values for `weather` and `temperature`.
`weather` is built by calling to https://wttr.in/{city}?format=j1
`temperature` is built by calling to https://wttr.in/{city}?format=j1
Returns:
dict: The config file as a dictionary."""
config_file_path = os.path.expanduser("~/.zoom-background-changer")
# if the config file doesn't exist, create it
if not os.path.exists(config_file_path):
with open(config_file_path, "w") as f:
f.write(
json.dumps(
{
"city": "Boston",
}
)
)
config = json.load(open(config_file_path))
if "city" in config:
config["city"] = urllib.parse.quote(config["city"])
city_wttr = json.load(
urllib.request.urlopen(f"https://wttr.in/{config['city']}?format=j1")
)
config["weather"] = city_wttr["current_condition"][0]["weatherDesc"][0]["value"]
config["temperature"] = city_wttr["current_condition"][0]["temp_F"]
return config
def build_prompt(config: dict) -> str:
"""Build the prompt for the OpenAI API.
Args:
config (dict): The config file as a dictionary.
Returns:
str: The prompt for the OpenAI API."""
if "city" in config:
template = """A colorful Zoom background for {date} in {city}. \
The weather in {city} is {weather} and {temperature} degrees fahrenheit today. \
Include the {city} skyline. \
Photo, Skyline, Weather, Real Photo, Real Skyline, Real Weather. \
"""
else:
template = """A colorful Zoom background for {date}. \
Photo, Skyline, Weather, Real Photo, Real Skyline, Real Weather. \
"""
try:
template = config["prompt"]
except KeyError:
pass
today = datetime.datetime.now()
prompt = template.format(
date=today,
**config
)
return prompt
def generate_new_image() -> str:
"""Return URL of new image from openai."""
return openai.Image.create(
prompt=build_prompt(read_config_file()),
n=2,
size="1024x1024",
)["data"][0]["url"]
def main():
"""Generate new image and replace the existing zoom background."""
# Generate a new image URL
new_image_url = generate_new_image()
# Get the name of the current file in the directory
current_file = os.listdir(OSX_ZOOM_DIR)[0]
# Download the new image from the URL and save it as the current file
urllib.request.urlretrieve(new_image_url, OSX_ZOOM_DIR + current_file)
if __name__ == "__main__":
main() | zoom-background-changer | /zoom_background_changer-0.2.0-py3-none-any.whl/zoom_background_changer/main.py | main.py |
import os
import subprocess
from dataclasses import dataclass
from datetime import datetime, timedelta
from logging import INFO, basicConfig, getLogger
from pathlib import Path
from re import DOTALL
from re import compile as re_compile
from typing import AbstractSet, Any, List, Optional
from click import option
from typer import Argument, Context, Exit, Option, Typer, echo
from zoom_chat_anonymizer import __version__
from zoom_chat_anonymizer.logic.anonymize_chat import anonymize_chat_internal
from zoom_chat_anonymizer.logic.clean_artemis_file import clean_artemis_file_internal
from zoom_chat_anonymizer.logic.create_html_from_markdown import (
create_html_from_markdown_internal,
)
from zoom_chat_anonymizer.logic.sort_moodle_csv import sort_moodle_csv_internal
app = Typer()
def _version_callback(value: bool) -> None:
if value:
echo(f"zoom-chat-anonymizer {__version__}")
raise Exit()
@app.callback()
def _call_back(
_: bool = Option(
None,
"--version",
"-v",
is_flag=True,
callback=_version_callback,
expose_value=False,
is_eager=True,
help="Version",
)
) -> None:
"""
:return:
"""
_LOGGER = getLogger(__name__)
basicConfig(
format="%(levelname)s: %(asctime)s: %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=INFO,
filename="zoom-chat-anomymizer.log",
filemode="w",
)
_INPUT_FOLDER_OPTION = Argument(
".",
file_okay=False,
exists=True,
resolve_path=True,
help="The folder with the chat files.",
)
_INPLACE = Option(False, "--inplace", "-I", is_flag=True)
def _print_version(ctx: Context, _: Any, value: Any) -> None:
"""
:param ctx:
:param _:
:param value:
:return:
"""
if not value or ctx.resilient_parsing:
return
echo(__version__)
ctx.exit()
_PATTERN = re_compile(r"^([0-9:]+)\t(.*):\t(.*)\n$", DOTALL)
@app.command()
def convert_to_old_format(
input_file: Path = Argument(
None, help="The file to convert", exists=True, dir_okay=False
),
) -> None:
"""
Convert to old format.
:param input_file:
:return:
"""
with input_file.open() as f:
lines = f.readlines()
new_lines = []
for line in lines:
if len(line) > 0:
if (match := _PATTERN.match(line)) is not None:
t = datetime.strptime(match.group(1), "%H:%M:%S")
new_t = t + timedelta(hours=14)
new_lines.append(
f"{new_t.strftime('%H:%M:%S')} Von {match.group(2)} an Alle : {match.group(3)}\n"
)
else:
echo(line)
with input_file.open("w") as f:
f.writelines(new_lines)
@app.command()
def anonymize_zoom_chats(
input_folder: Path = _INPUT_FOLDER_OPTION,
output_folder: Path = Option(
"out",
"--output-folder",
"-o",
file_okay=False,
writable=True,
resolve_path=True,
help="The script will write the anonymized files in this folder.",
),
tutor: List[str] = Option(
None,
"--tutor",
"-t",
help="The tutors' names. The script will preserve these names in the chat protocol.",
),
pause_file: Optional[Path] = Option(
None,
"--pause-file",
"-p",
dir_okay=False,
resolve_path=True,
exists=True,
help="A JSON file with the pauses made during the lecture/tutorial.",
),
starting_time: str = Option(
"14:15",
"--starting-time",
"-s",
help="The starting time of the lecture/tutorial.",
),
) -> None:
"""
Anonymize Zoom chats.
"""
tutor_set: AbstractSet[str] = frozenset(t.lower() for t in tutor)
anonymize_chat_internal(
input_folder, output_folder, tutor_set, pause_file, starting_time
)
@app.command()
def create_html_from_markdown(
input_folder: Path = _INPUT_FOLDER_OPTION,
bib_file: Optional[Path] = Option(
None, "--bib-file", exists=True, dir_okay=False, resolve_path=True
),
) -> None:
"""
Create HTML files from the markdown files.
"""
create_html_from_markdown_internal(bib_file, input_folder)
_INPUT_FILE = option(
"--input_file", "-i", type=Path(dir_okay=False, resolve_path=True, exists=True)
)
@dataclass(frozen=True)
class Remote(object):
"""
Remote
"""
name: str
link: str
type: str
@dataclass(frozen=True)
class Submodule(object):
"""
Submodule
"""
commit_hash: str
path: Path
branch: str
_WHITE = re_compile(r"\s")
@app.command()
def add_artemis_submodules(
submodule_directory: Path = Argument(
"exercise",
help="The subdirectory with the submodules to add.",
file_okay=False,
exists=True,
)
) -> None:
"""
Add all submodules.
"""
submodule_output = subprocess.check_output(["git", "submodule", "status"]).decode(
"utf8"
)
submodule_output_lines = submodule_output.split(os.linesep)
submodules = [
Submodule(
commit_hash=(parts := _WHITE.split(lin.strip()))[0],
path=Path(parts[1]),
branch=parts[2].lstrip("(").rstrip(")"),
)
for lin in submodule_output_lines
if lin != ""
]
subdirs = [d for d in submodule_directory.iterdir() if d.is_dir()]
for subdir in sorted(subdirs):
try:
existing_submodule = next(s for s in submodules if s.path == subdir)
echo(f"There is an existing submodule {existing_submodule} for {subdir}")
continue
except StopIteration:
echo(f"No existing submodule for {subdir}")
output = subprocess.check_output(
["git", "remote", "-v"], cwd=str(subdir)
).decode("utf8")
lines = output.split(os.linesep)
remotes = [
Remote(name=(parts := _WHITE.split(line))[0], link=parts[1], type=parts[2])
for line in lines
if line != ""
]
try:
artemis = next(r for r in remotes if "artemis" in r.name.casefold())
except StopIteration:
try:
artemis = next(
r for r in remotes if "bitbucket.ase.in.tum.de" in r.link.casefold()
)
except StopIteration:
echo(f"We could not find the artemis repo... for {subdir}")
raise Exit(1)
command = ["git", "submodule", "add", artemis.link, str(subdir)]
echo(" ".join(command))
result = subprocess.check_call(command)
if result != 0:
echo("Something went wrong ...")
raise Exit(1)
def clean_artemis_file(input_file: Path, inplace: bool = _INPLACE) -> None:
"""
Clean Artemis JSON.
"""
clean_artemis_file_internal(inplace, input_file)
def sort_moodle_csv(input_file: Path) -> None:
"""
Moodle.
"""
sort_moodle_csv_internal(input_file)
if __name__ == "__main__":
app() | zoom-chat-anonymizer | /zoom_chat_anonymizer-0.1.9-py3-none-any.whl/zoom_chat_anonymizer/main.py | main.py |
from logging import getLogger
from os import linesep, remove
from pathlib import Path
from subprocess import call
from typing import MutableSequence, Optional, Sequence
_LOGGER = getLogger(__name__)
def create_pdf_from_markdown_internal(
clean_up: bool,
latex_path: Path,
markdown_paths: Sequence[Path],
output_path: Path,
sheet_number: int,
title: str,
) -> None:
"""
:param clean_up:
:param latex_path:
:param markdown_paths:
:param output_path:
:param sheet_number:
:param title:
:return:
"""
tex_paths: MutableSequence[Path] = []
for markdown_path in markdown_paths:
_LOGGER.info(f"Translating {markdown_path} into LaTex...")
tex_path = markdown_path.parent.joinpath(markdown_path.stem + ".tex")
call(
[
"pandoc",
str(markdown_path),
"--to",
"latex",
"--no-highlight",
"-o",
str(tex_path),
]
)
tex_paths.append(tex_path)
_LOGGER.info(f"Done!")
output_tex_path = output_path.parent.joinpath(output_path.stem + ".tex")
_LOGGER.info(f"Writing {output_tex_path}...")
with output_tex_path.open("w") as f_read:
f_read.write(
r"\providecommand{\mysheetnumber}{" + str(sheet_number) + "}" + linesep
)
f_read.write(r"\providecommand{\mysheettitle}{" + str(title) + "}" + linesep)
f_read.write(latex_path.read_text())
f_read.write(r"\begin{document}" + linesep)
for tex_path in tex_paths:
f_read.write(r"\input{" + str(tex_path) + "}" + linesep)
f_read.write(r"\end{document}")
_LOGGER.info("... done!")
_LOGGER.info(f"Translating {output_tex_path} into PDF...")
call(
["pdflatex", f"-output-directory={output_path.parent}", str(output_tex_path),]
)
call(
["pdflatex", f"-output-directory={output_path.parent}", str(output_tex_path),]
)
_LOGGER.info("... done!")
if clean_up:
_LOGGER.info("Removing intermediate files.")
for tex_path in tex_paths:
remove(tex_path)
remove(output_tex_path)
_LOGGER.info("... done!")
for p in output_path.parent.glob(output_path.stem + "*"):
if p.suffix.strip().casefold().endswith("pdf"):
continue
_LOGGER.info(f"Removing {p}")
remove(p) | zoom-chat-anonymizer | /zoom_chat_anonymizer-0.1.9-py3-none-any.whl/zoom_chat_anonymizer/logic/create_pdf_from_markdown.py | create_pdf_from_markdown.py |
from datetime import datetime, time, timedelta
from functools import partial
from json import loads
from logging import getLogger
from os import linesep
from pathlib import Path
from re import DOTALL
from re import compile as re_compile
from typing import (
AbstractSet,
List,
Mapping,
MutableMapping,
Optional,
Pattern,
Sequence, Union,
)
from zoom_chat_anonymizer.classes.message import Message
from zoom_chat_anonymizer.classes.pause import Pause, PausesStart
_PATTERN = re_compile(r"^([0-9:]+)\s+Von\s+(.*)\s+an\s+(.*) : (.*)$", DOTALL)
_REFERENCE = re_compile(r"@([^:]+):")
_QUOTE_PATTERN: Pattern[str] = re_compile(r"
? ?>(.*)
")
_STAR_SPACE_BEFORE: Pattern[str] = re_compile(r"\n\* +")
_STAR_SPACE_AFTER: Pattern[str] = re_compile(r" +\* *\n")
_LOGGER = getLogger(__name__)
def anonymize_chat_internal(
input_folder_path: Path,
output_folder_path: Path,
tutor_set: AbstractSet[str],
pauses_file: Optional[Path],
starting_time_string: str,
) -> None:
"""
:param pauses_file:
:param input_folder_path:
:param output_folder_path:
:param tutor_set:
:return:
"""
t = datetime.strptime(starting_time_string, "%H:%M").time()
starting_time: timedelta = timedelta(hours=t.hour, minutes=t.minute)
if not output_folder_path.is_dir():
output_folder_path.mkdir()
pauses_object = _parse_pauses_file(pauses_file, starting_time)
for file in input_folder_path.glob("**/*.txt"):
new_file = output_folder_path.joinpath(file.stem + ".md")
pauses = pauses_object[file.stem] if file.stem in pauses_object else None
_anonymize_single_file(file, new_file, tutor_set, pauses, starting_time)
def _parse_pauses_file(
pauses_file: Optional[Path], start_time: timedelta
) -> Mapping[str, PausesStart]:
pauses_object: MutableMapping[str, PausesStart] = {}
if pauses_file is not None:
json_pauses = loads(pauses_file.read_text())
for key in json_pauses.keys():
current_pauses_with_start: Mapping[
str, Union[str, Sequence[Mapping[str, str]]]
] = json_pauses[key]
current_pauses: Sequence[Mapping[str, str]] = current_pauses_with_start["pauses"] # type: ignore
current_pauses_with_times = [
{
att: datetime.strptime(p[att], "%H:%M").time()
for att in ["from_time", "to_time"]
}
for p in current_pauses
]
strat: timedelta
if current_pauses_with_start.get("start") is not None:
start_string : str = current_pauses_with_start["start"] # type: ignore
t = datetime.strptime(
start_string, "%H:%M"
).time()
strat = timedelta(hours=t.hour, minutes=t.minute)
else:
strat = start_time
pauses_object[key] = PausesStart(
start=strat, pauses=[Pause(**p) for p in current_pauses_with_times]
)
return pauses_object
def _find_name_in_dict_with_tutors(
c_name: str, tutors: AbstractSet[str], author_to_anonymised_name: Mapping[str, str]
) -> str:
"""
:param c_name:
:param tutors:
:param author_to_anonymised_name:
:return:
"""
strip = c_name.lower().strip()
if strip in author_to_anonymised_name.keys():
return author_to_anonymised_name[strip]
for key, value in author_to_anonymised_name.items():
if strip in key.lower().replace(" ", ""):
return value
if strip == "everyone" or strip == "everybody":
return "everyone"
for tutor in tutors:
if strip in tutor:
return c_name
raise Exception(f"Name {c_name} is not known!")
def _process_line(line: str) -> str:
match = _QUOTE_PATTERN.search(line)
if match is None:
return line.replace("
", "\n").strip()
new_lines = _QUOTE_PATTERN.sub("\n\n*\\1* \n\n", line).strip()
return _STAR_SPACE_AFTER.sub("*\n", _STAR_SPACE_BEFORE.sub("\n*", new_lines))
def _anonymize_single_file(
input_file: Path,
output_file: Path,
tutors: AbstractSet[str],
pauses: Optional[PausesStart],
starting_time: timedelta,
) -> None:
"""
:param starting_time:
:param pauses:
:param tutors:
:param input_file:
:param output_file:
:return:
"""
_LOGGER.info(f"Processing {input_file}")
if pauses is not None:
starting_time = pauses.start
with input_file.open() as f_read:
content = f_read.readlines()
content = [_process_line(line) for line in content]
messages: List[Message] = []
author_to_anonymised_name: MutableMapping[str, str] = {}
find_name_in_dict = partial(
_find_name_in_dict_with_tutors,
tutors=tutors,
author_to_anonymised_name=author_to_anonymised_name,
)
last_message = None
was_the_last_message_a_private_message = False
for line in content:
match = _PATTERN.match(line)
if match:
time_string = match.group(1)
parts = time_string.split(":")
c_hour = int(parts[0])
c_minute = int(parts[1])
c_second = int(parts[2])
recipient = match.group(3)
message = Message(
text=match.group(4),
current_time=time(hour=c_hour, minute=c_minute, second=c_second),
author=match.group(2),
anonymized_author="",
)
if "direktnachricht" in recipient.casefold():
_LOGGER.debug(f"Ignoring private message {message}")
was_the_last_message_a_private_message = True
else:
if message.author.lower() in tutors:
_LOGGER.debug(
f"{message.author} is a tutor. Thus, we will not remove this name."
)
message.anonymized_author = message.author
else:
if message.author.lower() not in author_to_anonymised_name.keys():
_LOGGER.debug(
f"{message.author} has not asked before. Thus, we need a new name."
)
author_to_anonymised_name[
message.author.lower()
] = "Student {}".format(len(author_to_anonymised_name.keys()))
message.anonymized_author = author_to_anonymised_name[
message.author.lower()
]
references: List[str] = _REFERENCE.findall(message.text)
if len(references) > 0:
for reference in references:
if "+" in reference:
names = reference.split("+")
name_dict = {n.strip(): find_name_in_dict(n) for n in names}
for name, anonymized_name in name_dict.items():
message.text = message.text.replace(
name, anonymized_name
)
else:
anonymized_name = find_name_in_dict(reference)
message.text = message.text.replace(
reference, anonymized_name
)
messages.append(message)
last_message = message
was_the_last_message_a_private_message = False
else:
if not was_the_last_message_a_private_message and last_message is not None:
last_message.text += linesep + line
for message in messages:
message.sanitize()
message.make_time_relative(
pauses.pauses if pauses is not None else [], starting_time=starting_time
)
_LOGGER.info(f"Done with {input_file}")
_LOGGER.info(f"Writing {output_file}")
with output_file.open("w") as f_write:
for message in messages:
f_write.write(str(message) + linesep + linesep) | zoom-chat-anonymizer | /zoom_chat_anonymizer-0.1.9-py3-none-any.whl/zoom_chat_anonymizer/logic/anonymize_chat.py | anonymize_chat.py |
from dataclasses import dataclass
from typing import Any, TypedDict
class ArtemisJSONStudent(TypedDict):
"""
Artemis.
"""
id: int
firstName: str
lastName: str
email: str
@dataclass(frozen=True)
class Student(object):
"""
Artemis.
"""
first_name: str
last_name: str
email: str
class MoodleStudentCSV(TypedDict):
"""
Moodle.
"""
Vorname: str
Nachname: str
Matrikelnummer: str
@dataclass(frozen=True)
class MoodleStudent(Student):
"""
Artemis.
"""
matriculation_number: str
@staticmethod
def create_from_json(json_student: MoodleStudentCSV) -> "MoodleStudent":
"""
:param json_student:
:return:
"""
if json_student["Matrikelnummer"] == "":
json_student["Matrikelnummer"] = "-1"
return MoodleStudent(
first_name=json_student["Vorname"],
last_name=json_student["Nachname"],
matriculation_number=json_student["Matrikelnummer"],
email=json_student["E-Mail-Adresse"], # type: ignore
)
def __lt__(self, other: Any) -> bool:
m_a = int(self.matriculation_number)
m_b = int(other.matriculation_number)
if m_a == -1 and m_b == -1:
return bool(self.last_name < other.last_name)
return m_a < m_b
@dataclass(frozen=True)
class ArtemisStudent(Student):
"""
Artemis.
"""
id: int
@staticmethod
def create_from_json(json_student: ArtemisJSONStudent) -> "ArtemisStudent":
"""
:param json_student:
:return:
"""
if json_student.get("lastName") is None:
# PS: LMU exception ...
return ArtemisStudent(
id=json_student["id"],
first_name=json_student["firstName"].split(" ")[0],
last_name=json_student["firstName"].split(" ")[-1],
email=json_student["email"],
)
return ArtemisStudent(
id=json_student["id"],
first_name=json_student["firstName"],
last_name=json_student["lastName"],
email=json_student["email"],
)
def __lt__(self, other: "ArtemisStudent") -> bool:
return self.id < other.id | zoom-chat-anonymizer | /zoom_chat_anonymizer-0.1.9-py3-none-any.whl/zoom_chat_anonymizer/classes/artemis.py | artemis.py |
import datetime
import logging
import sys
import jwt
import requests
from requests.exceptions import RequestException
from zoom_client.modules import dashboard
from zoom_client.modules import group
from zoom_client.modules import report
from zoom_client.modules import users
# set recursion limit higher for rate limitations functions
sys.setrecursionlimit(20000)
class Client:
"""Zoom client class which assists with performing work using Zoom API"""
def __init__(self, config_data):
"""
params:
config_data: data used to configure the zoom api client
"""
# set api client specific vars
self.config_data = config_data
# initialize module classes
self.users = users.Users(self)
self.group = group.Group(self)
self.report = report.Report(self)
self.dashboard = dashboard.Dashboard(self)
# initialize user model
self.model = {"users": None}
def generate_jwt(self):
"""Generate valid jwt token for use in Zoom API requests"""
headers = {
"alg": "HS256",
"typ": "JWT",
}
encoded = jwt.encode(
{
"iss": self.config_data["api_key"],
"exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=30),
},
self.config_data["api_secret"],
algorithm="HS256",
headers=headers,
)
return {
"Authorization": f"Bearer {encoded}",
"Content-type": "application/json",
}
def do_request(self, request_type, resource, request_parameters, body=None):
"""Perform API request using the specified parameters"""
if request_type == "get":
rsp = requests.get(
self.config_data["root_request_url"] + resource,
params=request_parameters,
headers=self.generate_jwt(),
verify=True,
)
elif request_type == "delete":
rsp = requests.delete(
self.config_data["root_request_url"] + resource,
params=request_parameters,
headers=self.generate_jwt(),
verify=True,
)
elif request_type == "patch":
rsp = requests.patch(
self.config_data["root_request_url"] + resource,
params=request_parameters,
data=body,
headers=self.generate_jwt(),
verify=True,
)
elif request_type == "post":
rsp = requests.post(
self.config_data["root_request_url"] + resource,
params=request_parameters,
data=body,
headers=self.generate_jwt(),
verify=True,
)
if "Retry-After" in rsp.headers.keys():
logging.warning("Retry-After detected: %s", rsp.headers["Retry-After"])
logging.warning("X-RateLimit-Limit: %s", rsp.headers["X-RateLimit-Limit"])
logging.warning(
"X-RateLimit-Remaining: %s", rsp.headers["X-RateLimit-Remaining"]
)
try:
result = rsp.json()
except RequestException:
result = rsp
rsp.close()
return result | zoom-client | /zoom_client-0.0.5-py3-none-any.whl/zoom_client/client.py | client.py |
import logging
from ratelimit import limits, sleep_and_retry
class Dashboard:
"""
zoom_client class for gathering data from dashboard api queries
"""
def __init__(self, client):
self.zoom = client
def get_past_meetings(self, from_date: str, to_date: str) -> list:
"""
Finds Zoom meetings in provided date range.
Note: only one request per minute may be made due to Zoom rate limits.
params:
from_date: date to begin search for meetings in format ("%Y-%m-%d")
to_date: date to end search for meetings in format ("%Y-%m-%d")
returns:
list of dictionaries containing relevant meeting information from Zoom.
"""
logging.info("Gathering Zoom meetings data...")
# Note: artificial rate limit
# more detail can be found here:
# https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits
@sleep_and_retry
@limits(calls=19, period=65)
def make_requests(
page_number: int = 1, next_page_token: str = None, result_list: list = None
) -> list:
logging.info("Making meeting request %s", page_number)
result = self.zoom.do_request(
"get",
"metrics/meetings",
{
"from": from_date,
"to": to_date,
"type": "past",
"page_size": 300,
"next_page_token": next_page_token,
},
)
page_number += 1
if "meetings" in result.keys():
result_list += result["meetings"]
else:
result_list += [
{"error_code": result["code"], "error": result["message"]}
]
if "code" in result.keys():
logging.error("Error: %s %s", result["code"], result["message"])
elif "next_page_token" in result.keys() and result["next_page_token"] != "":
make_requests(
page_number=page_number,
next_page_token=result["next_page_token"],
result_list=result_list,
)
return result_list
result_list = make_requests()
return result_list
def get_past_meeting_participants(self, meeting_uuid: str) -> list:
"""
Finds Zoom meeting participants from given meeting_uuid (specific instance of Zoom meeting).
Note only one request per second may be made due to Zoom rate limits.
params:
meeting_uuid: meeting uuid which you'd like to find participants for
returns:
list of dictionaries containing relevant meeting information from Zoom.
"""
logging.info("Gathering Zoom meeting participant data...")
# Note: artificial rate limit
# more detail can be found here:
# https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits
@sleep_and_retry
@limits(calls=39, period=5)
def make_requests(
page_number: int = 1, next_page_token: str = None, result_list: list = None
) -> list:
logging.info("Making meeting partcipants request %s", page_number)
result = self.zoom.do_request(
"get",
"metrics/meetings/" + meeting_uuid + "/participants",
{"type": "past", "page_size": 300, "next_page_token": next_page_token},
)
page_number += 1
if "participants" in result.keys():
result_list += result["participants"]
else:
result_list += [
{"error_code": result["code"], "error": result["message"]}
]
if "code" in result.keys():
logging.error("Error: %s %s", result["code"], result["message"])
if "next_page_token" in result.keys() and result["next_page_token"] != "":
make_requests(
page_number=page_number,
next_page_token=result["next_page_token"],
result_list=result_list,
)
return result_list
result_list = make_requests()
return result_list | zoom-client | /zoom_client-0.0.5-py3-none-any.whl/zoom_client/modules/dashboard.py | dashboard.py |
import logging
import json
import time
class Group:
"""
zoom_client group class for gathering data and making changes to Zoom groups
"""
def __init__(self, client):
self.zoom = client
@staticmethod
def chunks(big_list, count):
"""Helper method for chunking big lists into smaller ones"""
for i in range(0, len(big_list), count):
yield big_list[i : i + count]
def add_members(self, group_id, user_emails):
"""Add members to Zoom group in batch by list of userid's"""
# Special note: uses user emails as opposed to ID's
logging.info("Adding %s users to group with id %s", len(user_emails), group_id)
for chunk in list(self.chunks(user_emails, 30)):
logging.info("Processing adding chunk of 30 or less users to group...")
post_data = {"members": [{"email": x} for x in chunk]}
result = self.zoom.client.do_request(
"post",
"groups/" + group_id + "/members",
"",
body=json.dumps(post_data),
)
# simple check to make sure we don't exceed rate limits, this needs improvement!
time.sleep(5)
return result
def delete_members(self, group_id, user_ids):
"""Delete members from Zoom group in batch by list of userid's"""
# Special note: uses user ID's as oppposed to emails
logging.info("Removing %s users from group with id %s", len(user_ids), group_id)
for chunk in list(self.chunks(user_ids, 30)):
logging.info("Processing removing chunk of 30 or less users from group...")
for user_id in chunk:
result = self.zoom.client.do_request(
"delete", "groups/" + group_id + "/members/" + user_id, ""
)
# simple check to make sure we don't exceed rate limits, this needs improvement!
# 30 requests per second are permissable and well below actual Edu account limits
time.sleep(1)
return result | zoom-client | /zoom_client-0.0.5-py3-none-any.whl/zoom_client/modules/group.py | group.py |
import json
import logging
import time
from datetime import datetime
from ratelimit import limits, sleep_and_retry
class Users:
"""
zoom_client users class for gathering data about or
changing properties of existing Zoom users
"""
def __init__(self, client):
self.zoom = client
def update_user(self, user_id, update_properties=json.dumps({})):
"""Update single Zoom user property by userid"""
logging.info(
"Updating user with ID: "
+ user_id
+ " with properties: "
+ update_properties
)
result = self.zoom.do_request(
"patch", "users/" + user_id, "", body=update_properties
)
return result
def batch_update_users(self, user_list, update_properties=json.dumps({})):
"""Update Zoom user properties in batch using provided list of userid's"""
number_users_updated = 0
time_interval_request_count = 0
start_time_interval = datetime.now()
for user_id in user_list:
resp = self.update_user(user_id, update_properties)
time_interval_request_count += 1
if resp.status_code == 204:
logging.info("Updated user %s successfully.", user_id)
number_users_updated += 1
# update the current time interval to accoutn for time restrictions in Zoom API
cur_time_interval = datetime.now()
# Check to see if less than a second has passed and 10 requests have already been made
# If so, sleep for the remaining time until the next second begins
if (
cur_time_interval - start_time_interval
).seconds < 1 and time_interval_request_count == 10:
logging.info(
"Waiting to ensure Zoom request time restrictions are met."
)
time.sleep(
(1 / 1000000)
* (
1000000
- (cur_time_interval - start_time_interval).microseconds
+ 1000
)
)
start_time_interval = datetime.now()
time_interval_request_count = 1
# Else, if greater than a second has passed reset values to begin time
# restriction counts again.
elif (cur_time_interval - start_time_interval).seconds >= 1:
start_time_interval = datetime.now()
time_interval_request_count = 1
return number_users_updated
def delete_user(self, user_id):
"""Delete single Zoom user by userid"""
logging.info("Deleting user with ID: %s", user_id)
result = self.zoom.do_request(
"delete", "users/" + user_id, {"action": "delete"}
)
return result
def batch_delete_users(self, user_list):
"""Delete Zoom users in batch based on provided list of userid's"""
number_users_deprovisioned = 0
time_interval_request_count = 0
start_time_interval = datetime.now()
for user_id in user_list:
resp = self.delete_user(user_id)
time_interval_request_count += 1
if resp.status_code == 204:
logging.info("Deprovisioned user %s successfully.", user_id)
number_users_deprovisioned += 1
# update the current time interval to accoutn for time restrictions in Zoom API
cur_time_interval = datetime.now()
# Check to see if less than a second has passed and 10 requests have already been made
# If so, sleep for the remaining time until the next second begins
if (
cur_time_interval - start_time_interval
).seconds < 1 and time_interval_request_count == 10:
logging.info(
"Waiting to ensure Zoom request time restrictions are met."
)
time.sleep(
(1 / 1000000)
* (
1000000
- (cur_time_interval - start_time_interval).microseconds
+ 1000
)
)
start_time_interval = datetime.now()
time_interval_request_count = 1
# Else, if greater than a second has passed reset values to begin time
# restriction counts again.
elif (cur_time_interval - start_time_interval).seconds >= 1:
start_time_interval = datetime.now()
time_interval_request_count = 1
return number_users_deprovisioned
def get_current_users(self):
"""Gather current Zoom user data from account"""
logging.info("Gathering current Zoom user data ...")
# Note: artificial rate limit
# more detail can be found here:
# https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits
@sleep_and_retry
@limits(calls=60, period=5)
def make_requests(
page_number: int = 1, page_count: int = 0, result_list: list = []
) -> list:
logging.info("Making user request %s of %s", page_number, page_count)
# make the Zoom api request and parse the result for the data we need
result = self.zoom.do_request(
"get", "users", {"page_size": "300", "page_number": page_number}
)
# if no users are returned in the result, we break our loop
if "users" in result.keys():
user_results = result["users"]
result_list += user_results
page_number += 1
if page_number <= int(result["page_count"]):
make_requests(
page_number=page_number,
page_count=result["page_count"],
result_list=result_list,
)
return result_list
users_listing = make_requests()
self.zoom.model["users"] = users_listing
return users_listing
def get_users_from_list(self, user_list):
"""Gather user data based on list of Zoom userid's provided"""
logging.info("Gathering current Zoom user data from list...")
result_list = []
for user in user_list:
result = self.zoom.client.do_request(
"get", "users/" + user, {"userId": user}
)
result_list.append(result)
self.zoom.model["users"] = result_list
return result_list
def get_current_user_type_counts(self):
"""Gather current user type counts from Zoom account"""
logging.info("Gathering current Zoom user metrics...")
# create various counts which will help provide metrics
pro_account_count = 0
basic_account_count = 0
corp_account_count = 0
account_count = 0
account_count = len(self.zoom.model["users"])
for user_data in self.zoom.model["users"]:
# change type from integer to human-readable value
# also make counts of the number of accounts per type
if user_data["type"] == 1:
basic_account_count += 1
user_data["type"] = "Basic"
elif user_data["type"] == 2:
pro_account_count += 1
user_data["type"] = "Pro"
elif user_data["type"] == 3:
corp_account_count += 1
user_data["type"] = "Corp"
# Share various metrics with the user on
# total, basic, pro and deprovisioning information to better
# inform them before proceeding.
logging.info("Total accounts: %s", account_count)
logging.info("Basic accounts: %s", basic_account_count)
logging.info("Pro accounts: %s", pro_account_count)
logging.info("Corp accounts: %s", corp_account_count)
return {
"Basic Accounts": basic_account_count,
"Pro Accounts": pro_account_count,
"Corp Accounts": corp_account_count,
"Total Accounts": account_count,
} | zoom-client | /zoom_client-0.0.5-py3-none-any.whl/zoom_client/modules/users.py | users.py |
"""Define useful methods to be used globally."""
import argparse
import os
from http.cookiejar import MozillaCookieJar
import collections
import io
import sys
from typing import List
class ZoomdlCookieJar(MozillaCookieJar):
"""Define a cookie jar.
Code freely adapted from Youtube-DL's YoutubeCookieJar
https://github.com/ytdl-org/youtube-dl/
For file format, see https://curl.haxx.se/docs/http-cookies.html
"""
_HTTPONLY_PREFIX = '#HttpOnly_'
_ENTRY_LEN = 7
_CookieFileEntry = collections.namedtuple(
'CookieFileEntry',
('domain_name', 'include_subdomains', 'path',
'https_only', 'expires_at', 'name', 'value'))
def load(self, filename=None, ignore_discard=True, ignore_expires=True):
"""Load cookies from a file."""
if filename is None:
if self.filename is not None:
filename = self.filename
else:
raise ValueError()
def prepare_line(line):
# print("Prepping line '{}'".format(line))
if line.startswith(self._HTTPONLY_PREFIX):
line = line[len(self._HTTPONLY_PREFIX):]
# comments and empty lines are fine
if line.startswith('#') or not line.strip():
return line
cookie_list = line.split('\t')
if len(cookie_list) != self._ENTRY_LEN:
raise ValueError('invalid length %d' % len(cookie_list))
cookie = self._CookieFileEntry(*cookie_list)
if cookie.expires_at and not cookie.expires_at.isdigit():
raise ValueError('invalid expires at %s' % cookie.expires_at)
return line
cf = io.StringIO()
with io.open(filename, encoding='utf-8') as f:
for line in f:
try:
cf.write(prepare_line(line))
except ValueError as e:
print(
'WARNING: skipping cookie file entry due to %s: %r\n'
% (e, line), sys.stderr)
continue
cf.seek(0)
self._really_load(cf, filename, ignore_discard, ignore_expires)
# Session cookies are denoted by either `expires` field set to
# an empty string or 0. MozillaCookieJar only recognizes the former
# (see [1]). So we need force the latter to be recognized as session
# cookies on our own.
# Session cookies may be important for cookies-based authentication,
# e.g. usually, when user does not check 'Remember me' check box while
# logging in on a site, some important cookies are stored as session
# cookies so that not recognizing them will result in failed login.
# 1. https://bugs.python.org/issue17164
for cookie in self:
# Treat `expires=0` cookies as session cookies
if cookie.expires == 0:
cookie.expires = None
cookie.discard = True
def _check_positive(value):
"""Ensure a given value is a positive integer."""
int_value = int(value)
if int_value < 0:
raise argparse.ArgumentTypeError(
"%s is an invalid positive int value" % value)
return int_value
def _valid_path(value):
if not (os.path.exists(value) and os.path.isfile(value)):
raise argparse.ArgumentTypeError(
"%s doesn't seem to be a valid file." & value)
return value
def parseOpts(args: List[str]):
"""Parse command line arguments.
Returns:
argparse.Namespace: Namespace of the parsed arguments.
"""
PARSER = argparse.ArgumentParser(
description="Utility to download zoom videos",
prog="zoomdl",
formatter_class=(lambda prog:
argparse.HelpFormatter(prog,
max_help_position=10,
width=200)
))
PARSER.add_argument("-u", "--url",
help=("Enter the url of the video to download. "
"Looks like 'zoom.us/rec/play/...'"),
type=str,
required=True,
metavar="url")
PARSER.add_argument("-f", "--filename",
help=("The name of the output video file without "
"extension. Default to the filename according "
"to Zoom. Extension is automatic."),
metavar="filename")
PARSER.add_argument("-d", "--filename-add-date",
help=("Add video meeting date if it is specified. "
"Default is not to include the date."),
default=False,
action='store_true')
PARSER.add_argument("--user-agent",
help=("Use custom user agent."
"Default is real browser user agent."),
type=str)
PARSER.add_argument("-p", "--password",
help="Password of the video (if any)",
metavar="password")
PARSER.add_argument("-c", "--count-clips",
help=("If multiple clips, how many to download. "
"1 = only current URL (default). "
"0 = all of them. "
"Other positive integer, count of clips to "
"download, starting from the current one"),
metavar="Count",
type=_check_positive,
default=1)
PARSER.add_argument("-v", "--log-level",
help=("Chose the level of verbosity. 0=debug, 1=info "
"(default), 2=warning 3=Error, 4=Critical, "
"5=Quiet (nothing printed)"),
metavar="level",
type=int,
default=1)
PARSER.add_argument("--cookies", help=("Path to a cookies file "
"in Netscape Format"),
metavar=("path/to/the/cookies.txt"),
required=False)
PARSER.add_argument("--save-chat",
help=("Save chat in the meeting as a plain-text "
"file or .srt subtitle. "
"Specify mode as \"txt\" for plain-text, "
"or \"srt\" for .srt subtitle"),
metavar="mode",
choices=["txt", "srt"],
default=None)
PARSER.add_argument("--chat-subtitle-dur",
help=("Duration in seconds that a chat message"
"appears on the screen"),
metavar="number",
type=_check_positive,
default=3)
PARSER.add_argument("--save-transcript",
help=("Save transcripts in the meeting as a "
"plain-text file or .srt subtitle. Specify"
" mode as \"txt\" for plain-text, "
"or \"srt\" for .srt subtitle"),
metavar="mode",
choices=["txt", "srt"],
default=None)
PARSER.add_argument("--dump-pagemeta",
help=("Dump page metas in json format"
" for further usages"),
default=False,
action='store_true')
return PARSER.parse_args(args) | zoom-downloader | /zoom_downloader-1.0.0-py3-none-any.whl/zoomdl/utils.py | utils.py |
"""Define the main ZoomDL class and its methods."""
import os
import re
import sys
import demjson3
import requests
from tqdm import tqdm
from typing import Optional
import datetime
import json
from .utils import ZoomdlCookieJar
class ZoomDL():
"""Class for ZoomDL."""
def __init__(self, args):
"""Init the class."""
self.args = args
self.loglevel = args.log_level
self.page = None
self.url, self.domain, self.subdomain = "", "", ""
self.metadata = None
self.session = requests.session()
self.loglevel = self.args.log_level
if self.args.cookies:
cookiejar = ZoomdlCookieJar(self.args.cookies)
cookiejar.load()
self.session.cookies.update(cookiejar)
@property
def recording_name(self):
"""Return name of the current recording."""
name = (self.metadata.get("topic") or
self.metadata.get("r_meeting_topic")).replace(" ", "_")
if self.args.filename_add_date:
recording_start_time = datetime.datetime.fromtimestamp(
self.metadata["fileStartTime"] / 1000)
name = name + "_" + recording_start_time.strftime("%Y-%m-%d")
return name
def _print(self, message, level=0):
"""Print to console, if level is sufficient.
This is meant to override the default print. When you need to
print something, you use this and specify a level. If the level is
sufficient, it will be printed, otherwise it will be discarded.
Levels are:
* 0: Debug
* 1: Info
* 2: Warning
* 3: Errors
* 4: Critical
* 5: Quiet (nothing to print)
By default, only display Info and higher. Don't input level > 5
Args:
level (int, optional): Level of verbosity of the message.
Defaults to 2.
"""
if level < 5 and level >= self.loglevel:
print(message)
def _change_page(self, url):
"""Change page, with side methods."""
self._print("Changing page to {}".format(url), 0)
self.page = self.session.get(url)
# self.check_captcha()
def get_page_meta(self) -> Optional[dict]:
"""Retrieve metadata from the current self.page.
Returns:
dict: dictionary of all relevant metadata
"""
# default case
text = self.page.text
meta = dict(re.findall(r'type="hidden" id="([^"]*)" value="([^"]*)"',
text))
# if javascript was correctly loaded, look for injected metadata
meta2_match = re.search("window.__data__ = ({(?:.*\n)*});",
self.page.text)
if meta2_match is not None:
try:
meta2 = demjson3.decode(meta2_match.group(1))
except demjson3.JSONDecodeError:
self._print("[WARNING] Error with the meta parsing. This "
"should not be critical. Please contact a dev.", 2)
meta.update(meta2)
else:
self._print("Advanced meta failed", 2)
# self._print(self.page.text)
# look for injected chat messages
chats = []
chat_match = re.findall(
r"window.__data__.chatList.push\(\s*?({(?:.*\n)*?})\s*?\)",
self.page.text)
if len(chat_match) > 0:
for matched_json in chat_match:
try:
message = demjson3.decode(matched_json)
chats.append(message)
except demjson3.JSONDecodeError:
self._print("[WARNING] Error with the meta parsing. This "
"should not be critical. "
"Please contact a dev.", 2)
else:
self._print("Unable to extract chatList from page", 0)
meta["chatList"] = chats
# look for injected transcripts
transcripts = []
transcript_match = re.findall(
r"window.__data__.transcriptList.push\(\s*?({(?:.*\n)*?})\s*?\)",
self.page.text)
if len(transcript_match) > 0:
for matched_json in transcript_match:
try:
message = demjson3.decode(matched_json)
transcripts.append(message)
except demjson3.JSONDecodeError:
self._print("[WARNING] Error with the meta parsing. This "
"should not be critical. "
"Please contact a dev.", 2)
else:
self._print("Unable to extract transcriptList from page", 0)
meta["transcriptList"] = transcripts
self._print("Metas are {}".format(meta), 0)
if len(meta) == 0:
self._print("Unable to gather metadata in page")
return None
if "viewMp4Url" not in meta:
self._print("No video URL in meta, going bruteforce", 2)
vid_url_match = re.search((r"source src=[\"']"
"(https?://ssrweb[^\"']+)[\"']"),
text)
if vid_url_match is None:
self._print("[ERROR] Video not found in page. "
"Is it login-protected? ", 4)
self._print(
"Try to refresh the webpage, and export cookies again", 4)
return None
meta["url"] = vid_url_match.group(1)
return meta
def dump_page_meta(self, fname, clip: int = None):
"""
Dump page meta in json format to fname.
"""
self._print("Dumping page meta...", 0)
filepath = get_filepath(fname, self.recording_name, "json", clip)
with open(filepath, "w", encoding="utf-8") as f:
json.dump(self.metadata, f)
self._print(f"Dumped page meta to '{filepath}'.", 1)
def download_vid(self, fname, clip: int = None):
"""Download one recording and save it at fname.
Including videos, chat, and transcripts
"""
self._print("Downloading filename {}, clip={}".format(
fname, str(clip)), 0)
all_urls = {
"camera": self.metadata.get("viewMp4Url"),
"screen": self.metadata.get("shareMp4Url"),
# the link below is rarely valid
# (only when both the two links above are invalid)
"unknown": self.metadata.get("url"),
}
for key, url in all_urls.copy().items():
if url is None or url == "":
all_urls.pop(key)
if len(all_urls) > 1:
self._print((f"Found {len(all_urls)} screens, "
"downloading all of them"),
1)
self._print(all_urls, 0)
for vid_name, vid_url in all_urls.items():
extension = vid_url.split("?")[0].split("/")[-1].split(".")[1]
self._print("Found name is {}, vid_name is {}, extension is {}"
.format(self.recording_name, vid_name, extension), 0)
vid_name_appendix = f"_{vid_name}" if len(all_urls) > 1 else ""
filepath = get_filepath(
fname, self.recording_name, extension, clip, vid_name_appendix)
filepath_tmp = filepath + ".part"
self._print("Full filepath is {}, temporary is {}".format(
filepath, filepath_tmp), 0)
self._print("Downloading '{}'...".format(
filepath.split("/")[-1]), 1)
vid_header = self.session.head(vid_url)
total_size = int(vid_header.headers.get('content-length'))
# unit_int, unit_str = ((1024, "KiB") if total_size < 30*1024**2
# else (1024**2, "MiB"))
start_bytes = int(os.path.exists(filepath_tmp) and
os.path.getsize(filepath_tmp))
if start_bytes > 0:
self._print("Incomplete file found ({:.2f}%), resuming..."
.format(100*start_bytes/total_size), 1)
headers = {"Range": "bytes={}-".format(start_bytes)}
vid = self.session.get(vid_url, headers=headers, stream=True)
if vid.status_code in [200, 206] and total_size > 0:
with open(filepath_tmp, "ab") as vid_file:
with tqdm(total=total_size,
unit='B',
initial=start_bytes,
dynamic_ncols=True,
unit_scale=True,
unit_divisor=1024) as pbar:
for data in vid.iter_content(1024):
if data:
pbar.update(len(data))
vid_file.write(data)
vid_file.flush()
self._print("Done!", 1)
os.rename(filepath_tmp, filepath)
else:
self._print(
"Woops, error downloading: '{}'".format(vid_url), 3)
self._print("Status code: {}, file size: {}".format(
vid.status_code, total_size), 0)
sys.exit(1)
# save chat
if self.args.save_chat is not None:
messages = self.metadata["chatList"]
if len(messages) == 0:
self._print(f"Unable to retrieve chat message from url"
f" {self.url} (is there no chat message?)", 2)
else:
# Convert time string to proper format
for message in messages:
message["time"] = shift_time_delta(message["time"])
if self.args.save_chat == "txt":
chat_filepath = get_filepath(
fname, self.recording_name, "txt", clip, ".chat")
with open(chat_filepath, "w", encoding="utf-8") as outfile:
for idx, message in enumerate(messages):
outfile.write("[{}] @ {} :\n".format(
message["username"], message["time"]))
outfile.write(message["content"] + "\n")
if idx + 1 < len(messages):
outfile.write("\n")
elif self.args.save_chat == "srt":
chat_filepath = get_filepath(
fname, self.recording_name, "srt", clip, ".chat")
with open(chat_filepath, "w", encoding="utf-8") as outfile:
for idx, message in enumerate(messages):
end_time = shift_time_delta(
message["time"], self.args.chat_subtitle_dur)
outfile.write(str(idx+1) + "\n")
outfile.write(
f"{message['time']},000 --> {end_time},000\n")
outfile.write(message["username"] +
": " + message["content"] + "\n")
if idx + 1 < len(messages):
outfile.write("\n")
self._print(
f"Successfully saved chat into '{chat_filepath}'!", 1)
# save transcripts
if self.args.save_transcript is not None:
transcripts = self.metadata["transcriptList"]
if len(transcripts) == 0:
self._print("Unable to retrieve transcript from url"
f"{self.url} (is transcript not enabled "
"in this video?)", 2)
else:
if self.args.save_transcript == "txt":
tran_filepath: str = get_filepath(fname,
self.recording_name,
"txt",
clip,
".transcript")
with open(tran_filepath, "w", encoding="utf-8") as outfile:
for idx, transcript in enumerate(transcripts):
outfile.write("[{}] @ {} --> {} :\n".format(
transcript["username"],
transcript["ts"],
transcript["endTs"]))
outfile.write(transcript["text"] + "\n")
if idx + 1 < len(transcripts):
outfile.write("\n")
elif self.args.save_transcript == "srt":
tran_filepath = get_filepath(
fname, self.recording_name, "srt", clip, ".transcript")
with open(tran_filepath, "w", encoding="utf-8") as outfile:
for idx, transcript in enumerate(transcripts):
outfile.write(str(idx+1) + "\n")
outfile.write("{} --> {}\n".format(
transcript["ts"].replace(".", ","),
transcript["endTs"].replace(".", ",")))
outfile.write(transcript["username"] +
": " +
transcript["text"] +
"\n")
if idx + 1 < len(transcripts):
outfile.write("\n")
self._print("Successfully saved transcripts "
f"into '{tran_filepath}'!", 1)
def download(self, all_urls):
"""Exposed class to download a list of urls."""
for url in all_urls:
self.url = url
try:
regex = r"(?:https?:\/\/)?([^.]*\.?)(zoom[^.]*\.(?:us|com))"
self.subdomain, self.domain = re.findall(regex, self.url)[0]
except IndexError:
self._print("Unable to extract domain and subdomain "
"from url {}, exitting".format(self.url), 4)
sys.exit(1)
self.session.headers.update({
# set referer
'referer': "https://{}{}/".format(self.subdomain,
self.domain),
})
if self.args.user_agent is None:
self._print("Using standard Windows UA", 0)
# somehow standard User-Agent
ua = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/74.0.3729.169 Safari/537.36")
else:
ua = self.args.user_agent
self._print("Using custom UA: " + ua, 0)
self.session.headers.update({
"User-Agent": ua
})
self._change_page(url)
if self.args.password is not None:
self.authenticate()
self.metadata = self.get_page_meta()
if self.metadata is None:
self._print("Unable to find metadata, aborting.", 4)
return None
# look for clips
total_clips = int(self.metadata["totalClips"])
current_clip = int(self.metadata["currentClip"])
count_clips = self.args.count_clips
filename = self.args.filename
if count_clips == 1: # only download this
self.download_vid(filename)
if self.args.dump_pagemeta:
self.dump_page_meta(filename)
else: # download multiple
if count_clips == 0:
to_download = total_clips # download this and all nexts
else: # download as many as asked (or possible)
to_download = min(count_clips, total_clips)
for clip in range(current_clip, to_download+1):
self.download_vid(filename, clip)
if self.args.dump_pagemeta:
self.dump_page_meta(filename, clip)
url = self.page.url
next_time = str(self.metadata["nextClipStartTime"])
if next_time != "-1":
if "&startTime" not in url:
url += "&startTime={}".format(next_time)
else:
curr_time = re.findall(r"startTime=(\d+)", url)[0]
url = url.replace(curr_time, next_time)
self._change_page(url)
self.metadata = self.get_page_meta()
# def check_captcha(self):
# """Check whether or not a page is protected by CAPTCHA.
# TO BE IMPLEMENTED!!
# """
# self._print("Checking CAPTCHA", 0)
# captcha = False # FIXME
# if captcha:
# self._print((f"The page {self.page.url} is captcha-protected. "
# "Unable to download"))
# sys.exit(1)
def authenticate(self):
# that shit has a password
# first look for the meet_id
self._print("Using password '{}'".format(self.args.password))
meet_id_regex = re.compile("<input[^>]*")
input_tags = meet_id_regex.findall(self.page.text)
meet_id = None
for inp in input_tags:
input_split = inp.split()
if input_split[2] == 'id="meetId"':
meet_id = input_split[3][7:-1]
break
if meet_id is None:
self._print("[CRITICAL]Unable to find meetId in the page",
4)
if self.loglevel > 0:
self._print("Please re-run with option -v 0 "
"and report it "
"to http://github.com/battleman/zoomdl",
4)
self._print("\n".join(input_tags), 0)
sys.exit(1)
# create POST request
data = {"id": meet_id, "passwd": self.args.password,
"action": "viewdetailpage"}
check_url = ("https://{}{}/rec/validate_meet_passwd"
.format(self.subdomain, self.domain))
self.session.post(check_url, data=data)
self._change_page(self.url) # get as if nothing
def confirm(message):
"""
Ask user to enter Y or N (case-insensitive).
Inspired and adapted from
https://gist.github.com/gurunars/4470c97c916e7b3c4731469c69671d06
`return` {bool} True if the answer is Y.
"""
answer = None
while answer not in ["y", "n", ""]:
answer = input(message + " Continue? [y/N]: ").lower() # nosec
return answer == "y"
def get_filepath(user_fname: str,
file_fname: str,
extension: str,
clip: int = None,
appendix: str = "") -> str:
"""Create an filepath."""
if user_fname is None:
basedir = os.getcwd()
# remove illegal characters
name = os.path.join(basedir, re.sub(
r"[/\\\?*:\"|><]+", "_", file_fname))
else:
name = os.path.abspath(user_fname)
if clip is not None:
name += "_clip{}".format(clip)
name += appendix
filepath = "{}.{}".format(name, extension)
# check file doesn't already exist
if os.path.isfile(filepath):
if not confirm("File {} already exists. This will erase it"
.format(filepath)):
sys.exit(0)
os.remove(filepath)
return filepath
def shift_time_delta(time_str: str,
delta_second: int = 0,
with_ms: bool = False):
"""Shift given time by adding `delta_second` seconds then format it.
`delta_seconds` can be negative.
"""
tmp_timedelta = parse_timedelta(time_str)
total_seconds = int(tmp_timedelta.total_seconds()) + delta_second
hours, rem = divmod(total_seconds, 3600)
minutes, seconds = divmod(rem, 60)
output = f'{hours:02d}:{minutes:02d}:{seconds:02d}'
if with_ms:
output += f'.{tmp_timedelta.microseconds:03d}'
return output
def parse_timedelta(value):
"""
Convert input string to timedelta.
Supported strings are like `01:23:45.678`.
"""
value = re.sub(r"[^0-9:.]", "", value)
if not value:
return
if "." in value:
ms = int(value.split(".")[1])
value = value.split(".")[0]
else:
ms = 0
delta = datetime.timedelta(**{
key: float(val)
for val, key in zip(value.split(":")[::-1],
("seconds", "minutes", "hours", "days"))
})
delta += datetime.timedelta(microseconds=ms)
return delta | zoom-downloader | /zoom_downloader-1.0.0-py3-none-any.whl/zoomdl/downloader.py | downloader.py |
# Zoom Kurokesu
Python library to pilote the dual zoom board controller from Kurokesu. Visit [Kurokesu's website](https://www.kurokesu.com/home/) to get more information about its products.
Install:
```bash
pip install zoom_kurokesu
```
## Use the library
You can get/set either the zoom or focus of both cameras.
There is also three pre defined positions.
- 'in': for close objects
- 'out': for further objects
- 'inter': in between the 'in' and 'out' positions
Because each predined position is relative to the starting position, you **must perform a homing sequence** before sending other commands.
The motors speed can also be changed with this library.
Check the *Demo.ipynb* notebook for use case example and more info.
---
Visit [pollen-robotics.com](https://pollen-robotics.com) to learn more or visit [our forum](https://forum.pollen-robotics.com) if you have any questions.
| zoom-kurokesu | /zoom_kurokesu-1.1.0.tar.gz/zoom_kurokesu-1.1.0/README.md | README.md |
import serial
import time
class ZoomController:
"""Zoom controller class."""
connector = {
'left': 'J1',
'right': 'J2'
}
motors = {
'J1': {'zoom': 'X', 'focus': 'Y'},
'J2': {'zoom': 'Z', 'focus': 'A'}
}
zoom_pos = {
'left': {
'in': {'zoom': 457, 'focus': 70},
'inter': {'zoom': 270, 'focus': 331},
'out': {'zoom': 60, 'focus': 455},
},
'right': {
'in': {'zoom': 457, 'focus': 42},
'inter': {'zoom': 270, 'focus': 321},
'out': {'zoom': 60, 'focus': 445},
},
}
def __init__(
self,
port: str = '/dev/ttyACM0',
baudrate: int = 115200,
timeout: int = 10,
speed: int = 10000) -> None:
"""Connect to the serial port and run the initialisation sequence."""
self.ser = serial.Serial(port=port, baudrate=baudrate, timeout=timeout)
self.speed = speed
init_seq = 'G100 P9 L144 N0 S0 F1 R1'
self.ser.write(bytes(init_seq + '\n', 'utf8'))
response = self.ser.readline()
if response.decode() != 'ok\r\n':
raise IOError('Initialization of zoom controller failed, check that the control board is correctly plugged in.')
def set_zoom_level(self, side: str, zoom_level: str) -> None:
"""Set zoom level of a given camera.
Given the camera side and the zoom level required,
produce the corresponding G-code and send it over the serial port.
Args:
side: 'right' or 'left'
zoom_level: either 'in', 'inter' or 'out'. 'in' level for far
objects, 'out' for close objects, 'inter' is in between
'in' and 'out' levels
"""
zoom, focus = self.zoom_pos[side][zoom_level].values()
self._send_custom_command({side: {'zoom': zoom, 'focus': focus}})
def _send_custom_command(self, commands: dict):
"""Send custom command to camera controller.
Args:
commands: dictionnary containing the requested camera name along
with requested focus and zoom value. Instructions for both cameras
can be sent in one call of this method. However, instructions will
be sent sequentially and there is no synchronization.
"""
for side, cmd in commands.items():
if side not in ['left', 'right']:
raise ValueError("Keys should be either 'left' or 'right'.")
motor = self.motors[self.connector[side]]
for target, value in cmd.items():
if target not in ['zoom', 'focus']:
raise ValueError("Each command should be either on 'focus' or 'zoom'.")
command = f'G1 {motor[target]}{value} F{self.speed}'
self.ser.write(bytes(command + '\n', 'utf8'))
_ = self.ser.readline()
def homing(self, side: str) -> None:
"""Use serial port to perform homing sequence on given camera.
Args:
side: 'right', 'left'.
"""
mot = self.motors[self.connector[side]]
cmd = 'G92 ' + mot['zoom'] + '0 ' + mot['focus'] + '0'
self.ser.write(bytes(cmd + '\n', 'utf8'))
_ = self.ser.readline()
time.sleep(0.1)
self._send_custom_command({side: {'zoom': 0, 'focus': -500}})
time.sleep(1)
self._send_custom_command({side: {'zoom': -600, 'focus': -500}})
time.sleep(1)
cmd = 'G92 ' + mot['zoom'] + '0 ' + mot['focus'] + '0'
self.ser.write(bytes(cmd + '\n', 'utf8'))
_ = self.ser.readline()
time.sleep(0.1)
def set_speed(self, speed_value: int) -> None:
"""Set motors speed.
Args:
speed_value: int between 4000 and 40000
"""
if not (4000 <= speed_value <= 40000):
raise ValueError('Speed value must be between 4000 and 40000')
self.speed = speed_value | zoom-kurokesu | /zoom_kurokesu-1.1.0.tar.gz/zoom_kurokesu-1.1.0/zoom_kurokesu/zoom_piloting.py | zoom_piloting.py |
import json
import os
import tkinter
from tkinter import filedialog
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import pyplot
def _extract_data():
root = tkinter.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
with open(file_path, 'r') as file:
lines = file.readlines()
title = lines[0]
names, data = [], []
for line in lines[1:]:
cols = line.strip().split(',')
names.append(cols[0].strip().title())
data.append([int(x) for x in cols[1:]])
return title, names, data
def _get_config():
if not os.path.isfile('./config.json'):
with open('./config.json', 'w+') as cnf:
cnf.write(json.dumps({}))
with open('./config.json', 'r') as cnf:
config = json.loads(cnf.read())
return config
def _write_config(config):
with open('./config.json', 'w') as cnf:
cnf.write(json.dumps(config))
def _get_class_list():
config = _get_config()
return [cls for cls in config]
def _add_new_names(cls, new_names=None):
config = _get_config()
all_name = config[cls]['all_name']
if new_names:
pass
else:
new_names = []
while True:
name = input("Enter a name. Type 'Exit' to stop").strip().title()
if name == "Exit":
break
else:
new_names.append(name)
new_all_name = sorted([*all_name, *new_names])
config[cls]['all_name'] = new_all_name
_write_config(config)
def _add_name_changes(cls, change_names):
config = _get_config()
config[cls]['change_names'] = change_names
_write_config(config)
def _get_all_name_and_changes(cls=None):
config = _get_config()
if not cls:
while True:
available_classes = '\n'.join(_get_class_list())
print(f'Available classes: \n{available_classes}')
cls = input("Enter class: ").lower()
if config.get(cls):
return config[cls]['all_name'], config[cls]['change_names'], cls
else:
yn = input(f'Class {cls} does not exist. Do you want to create? (yes, no)').lower()
if yn == "yes":
config[cls] = {"all_name": [], "change_names": {}}
_write_config(config)
return [], {}, cls
return config[cls]['all_name'], config[cls]['change_names']
def _suggest_name_change(names, change_names):
cs = ''
for name in names:
if name in change_names:
cs += f'{name} --> {change_names[name]}\n'
if len(cs) != 0:
yn = input(f'{cs}Above will be changed. Do you want to continue?(yes, no)').lower()
if yn == 'yes':
for index, name in enumerate(names):
if name in change_names:
names[index] = change_names[name]
return names
def _refine_data_name(names, data):
all_names, change_names, cls = _get_all_name_and_changes()
new_names = []
names = _suggest_name_change(names, change_names)
for index, name in enumerate(names):
if name not in all_names:
yn = input(f'Type actual name of "{name}" press Enter to skip. ').title()
if len(yn) != 0:
change_names[name] = yn
names[index] = yn
new_names.append(names[index])
all_names.append(names[index])
if new_names:
_add_new_names(cls, new_names)
all_names_str = '\n'.join(all_names)
yn = input(f'Available names:\n{all_names_str}\n Do you want to add new?(yes, no)').strip().lower()
if yn == 'yes':
_add_new_names(cls)
_add_name_changes(cls, change_names)
all_names, change_names = _get_all_name_and_changes(cls)
meeting_length = len(data[0])
for name in all_names:
if name not in names:
names.append(name)
data.append([0 for _ in range(meeting_length)])
return names, data
def _show_graph(title, names, data):
data = np.array(data)
a4_dims = (11.7, 8.27)
fig, ax = pyplot.subplots(figsize=a4_dims)
sns.heatmap(ax=ax, data=data, cbar=False)
ax.set_title(title)
ax.set_yticklabels(names)
plt.setp(ax.get_yticklabels(), rotation=0, ha="right",
rotation_mode="anchor")
for i in range(data.shape[0] + 1):
ax.axhline(i, color='white', lw=2)
plt.show()
def run_attendance_helper():
title, names, data = _extract_data()
names, data = _refine_data_name(names, data)
_show_graph(title, names, data) | zoom-meet-attendance-visualizer | /zoom_meet_attendance_visualizer-1.0.5-py3-none-any.whl/zoom_meet_attendance_helper/main.py | main.py |
import json
import logging
import requests
logger = logging.getLogger("zoom_python_client")
class ApiClient:
def __init__(self, api_base_url: str):
self.api_base_url = api_base_url
def build_headers(self, extra_headers=None) -> dict:
"""Create the headers for a request appending the ones in the params
Args:
extra_headers (dict): Dict of headers that will be appended to the default ones
Returns:
dict: All the headers
"""
headers = {"Content-type": "application/json"}
if extra_headers:
headers.update(extra_headers)
return headers
def make_get_request(self, api_path: str, headers: dict) -> requests.Response:
"""Makes a GET request using requests
Args:
api_path (str): The URL path
headers (dict): The headers of the request
Returns:
dict: A JSON dict
"""
full_url = self.api_base_url + api_path
response = requests.get(full_url, headers=headers)
response.raise_for_status()
return response
def make_post_request(
self, api_path: str, data=None, headers=None
) -> requests.Response:
"""Makes a POST request using requests
Args:
api_path (str): The URL path
data (_type_, optional): The form body. Defaults to None.
headers (_type_, optional): The request headers. Defaults to None.
Returns:
dict: A JSON dict
"""
full_url = self.api_base_url + api_path
response = requests.post(full_url, headers=headers, data=data)
response.raise_for_status()
return response
def make_patch_request(
self, api_path: str, data=None, headers=None
) -> requests.Response:
"""Makes a PATCH request using requests
Args:
api_path (str): The URL path
data (_type_, optional): The form body. Defaults to None.
headers (_type_, optional): The request headers. Defaults to None.
Returns:
dict: A JSON dict
"""
full_url = self.api_base_url + api_path
response = requests.patch(full_url, headers=headers, data=json.dumps(data))
response.raise_for_status()
return response | zoom-python-client | /zoom_python_client-0.2.2-py3-none-any.whl/zoom_python_client/api_client.py | api_client.py |
import logging
import os
from typing import Any, Mapping, Optional, Union
import requests
from dotenv import load_dotenv
from zoom_python_client.api_client import ApiClient
from zoom_python_client.client_components.calendars.calendars_component import (
CalendarsComponent,
)
from zoom_python_client.client_components.meeting_livestreams.meeting_livestreams_component import (
MeetingLiveStreamsComponent,
)
from zoom_python_client.client_components.meetings.meetings_component import (
MeetingsComponent,
)
from zoom_python_client.client_components.rooms.rooms_component import RoomsComponent
from zoom_python_client.client_components.users.users_component import UsersComponent
from zoom_python_client.client_components.webinar_livestreams.webinar_livestreams_component import (
WebinarLiveStreamsComponent,
)
from zoom_python_client.client_components.webinars.webinars_component import (
WebinarsComponent,
)
from zoom_python_client.utils.file_system import get_project_dir
from zoom_python_client.zoom_auth_api.zoom_auth_api_client import ZoomAuthApiClient
from zoom_python_client.zoom_client_interface import ZoomClientInterface
# This goes into your library somewhere
logging.getLogger("zoom_python_client").addHandler(logging.NullHandler())
logger = logging.getLogger("zoom_python_client")
class ZoomClientEnvError(Exception):
pass
class ZoomClientError(Exception):
pass
class ZoomApiClient(ZoomClientInterface):
api_endpoint: str = "https://api.zoom.us/v2"
@staticmethod
def init_from_env(use_path: Optional[str] = None):
try:
account_id = os.environ["ZOOM_ACCOUNT_ID"]
client_id = os.environ["ZOOM_CLIENT_ID"]
client_secret = os.environ["ZOOM_CLIENT_SECRET"]
zoom_client = ZoomApiClient(
account_id, client_id, client_secret, use_path=use_path
)
return zoom_client
except KeyError as error:
raise ZoomClientEnvError(
f"Required key not in environment: {error}"
) from error
@staticmethod
def init_from_dotenv(
custom_dotenv=".env",
use_path: Optional[str] = None,
):
project_dir = get_project_dir()
load_dotenv(os.path.join(project_dir, custom_dotenv), verbose=True)
zoom_client = ZoomApiClient.init_from_env(use_path=use_path)
return zoom_client
def init_components(self):
# Add all the new components here
self.users = UsersComponent(self)
self.meetings = MeetingsComponent(self)
self.meeting_livestreams = MeetingLiveStreamsComponent(self)
self.webinars = WebinarsComponent(self)
self.webinar_livestreams = WebinarLiveStreamsComponent(self)
self.rooms = RoomsComponent(self)
self.calendars = CalendarsComponent(self)
def __init__(
self,
account_id: str,
client_id: str,
client_secret: str,
api_endpoint="https://api.zoom.us/v2",
use_path: Optional[str] = None,
):
self.api_endpoint = api_endpoint
self.use_path = use_path
self.api_client = ApiClient(self.api_endpoint)
self.authentication_client = ZoomAuthApiClient(
account_id, client_id, client_secret, use_path=use_path
)
# Initialize components
self.init_components()
def load_access_token_and_expire_seconds(self):
if self.use_path:
logger.debug("Loading token from file")
# If the token is in a file, we need to get the token from the file
access_token = self.authentication_client.get_access_token_from_file()
expire_seconds = self.authentication_client.get_expire_seconds_from_file()
else:
logger.debug("Loading token from environment")
access_token = os.getenv("ZOOM_ACCESS_TOKEN", default=None)
expire_seconds = os.getenv("ZOOM_ACCESS_TOKEN_EXPIRE", default=None)
return access_token, expire_seconds
def build_zoom_authorization_headers(self, force_token=False) -> dict:
access_token, expire_seconds = self.load_access_token_and_expire_seconds()
token_from = "file" if self.use_path else "environment"
if (
not access_token
or not expire_seconds
or self.authentication_client.is_zoom_access_token_expired(expire_seconds)
or force_token
):
if force_token:
logger.debug("Forcing token refresh")
else:
logger.debug(f"Token is not in the {token_from}. Requesting new token.")
access_token = self.authentication_client.get_acceess_token()
else:
logger.debug(f"The token is the {token_from}. No need for a new token.")
zoom_headers = {"Authorization": "Bearer " + access_token}
headers = self.api_client.build_headers(extra_headers=zoom_headers)
return headers
def build_query_string_from_dict(self, parameters: dict) -> str:
query_string = "?"
for key, value in parameters.items():
if value:
query_string += f"{key}={value}&"
return query_string
def make_get_request(
self, api_path: str, parameters: dict = {}
) -> Union[requests.Response, None]:
headers = self.build_zoom_authorization_headers()
# convert parameters dict to query string
query_string = self.build_query_string_from_dict(parameters)
response = requests.Response()
try:
response = self.api_client.make_get_request(
api_path + query_string, headers=headers
)
# Handle 401 error from requests
except requests.exceptions.HTTPError as error:
if error.response.status_code == 401:
logger.debug(
f"Got 401 error from Zoom API Get ({error}). Retrying with a new token."
)
response = self.retry_get_request(api_path, query_string)
return response
def retry_get_request(self, api_path, query_string):
headers = self.build_zoom_authorization_headers(force_token=True)
response = self.api_client.make_get_request(
api_path + query_string, headers=headers
)
return response
def make_post_request(
self, api_path: str, data: Mapping[str, Any]
) -> Union[requests.Response, None]:
headers = self.build_zoom_authorization_headers()
response = requests.Response()
try:
response = self.api_client.make_post_request(
api_path, headers=headers, data=data
)
# Handle 401 error from requests
except requests.exceptions.HTTPError as error:
if error.response.status_code == 401:
logger.debug(
f"Got 401 error from Zoom API Post ({error}). Retrying with a new token."
)
response = self.retry_post_request(api_path, data)
return response
def retry_post_request(self, api_path, data):
headers = self.build_zoom_authorization_headers(force_token=True)
response = self.api_client.make_post_request(
api_path, headers=headers, data=data
)
return response
def make_patch_request(
self, api_path: str, data: Mapping[str, Any]
) -> Union[requests.Response, None]:
headers = self.build_zoom_authorization_headers()
response = requests.Response()
try:
response = self.api_client.make_patch_request(
api_path, headers=headers, data=data
)
# Handle 401 error from requests
except requests.exceptions.HTTPError as error:
if error.response.status_code == 401:
# Retry generating a new token
logger.debug(
f"Got 401 error from Zoom API Patch ({error}). Retrying with a new token."
)
response = self.retry_patch_request(api_path, data)
return response
def retry_patch_request(self, api_path, data):
headers = self.build_zoom_authorization_headers(force_token=True)
response = self.api_client.make_patch_request(
api_path, headers=headers, data=data
)
return response | zoom-python-client | /zoom_python_client-0.2.2-py3-none-any.whl/zoom_python_client/zoom_api_client.py | zoom_api_client.py |
import logging
import os
from base64 import b64encode
from time import time
from typing import Optional
from zoom_python_client.api_client import ApiClient
logger = logging.getLogger("zoom_python_client")
class ZoomAuthApiClientError(Exception):
pass
class ZoomAuthApiClient:
oauth_base_url: str = "https://zoom.us/oauth"
minimum_expire_time_seconds: int = 300
def __init__(
self,
account_id: str,
client_id: str,
client_secret: str,
use_path: Optional[str] = None,
):
self.account_id = account_id
self.client_id = client_id
self.client_secret = client_secret
self.authentication_client = ApiClient(self.oauth_base_url)
self.use_path = use_path
def base64_encode_auth(self):
encoded_auth = b64encode(
bytes(f"{self.client_id}:{self.client_secret}", "utf-8")
).decode()
return encoded_auth
def is_zoom_access_token_expired(self, expire_seconds):
current_seconds = int(time())
if expire_seconds:
expire_seconds_int = int(expire_seconds)
remaining_seconds = expire_seconds_int - current_seconds
logger.debug(f"Remaining seconds: {remaining_seconds}")
if remaining_seconds > self.minimum_expire_time_seconds:
return False
logger.debug("Access token is expired")
return True
def generate_auth_headers(self):
encoded_auth = self.base64_encode_auth()
authentication_headers = {"Authorization": f"Basic {encoded_auth}"}
headers = self.authentication_client.build_headers(
extra_headers=authentication_headers
)
logger.debug("Auth headers generated")
return headers
def save_token_and_seconds_to_env(self, result):
try:
os.environ["ZOOM_ACCESS_TOKEN"] = result["access_token"]
os.environ["ZOOM_ACCESS_TOKEN_EXPIRE"] = str(
int(time()) + int(result["expires_in"])
)
except ValueError as error:
raise ZoomAuthApiClientError(
"Unable to set access_token expiration. expires_in is not an int"
) from error
def save_token_and_seconds_to_file(self, result):
# Save the token to a file
if self.use_path is None:
raise ZoomAuthApiClientError("use_path is None")
file_path = os.path.join(self.use_path, "access_token")
with open(file_path, "w") as token_file:
token_file.write(result["access_token"])
# Save the expire_seconds to a file
file_path = os.path.join(self.use_path, "expire_seconds")
with open(file_path, "w") as token_file:
new_expire = str(int(time()) + int(result["expires_in"]))
token_file.write(new_expire)
return True
def extract_access_token(self, result):
if "access_token" in result and "expires_in" in result:
if self.use_path:
self.save_token_and_seconds_to_file(result)
else:
self.save_token_and_seconds_to_env(result)
logger.debug("Access token extracted from oauth response")
return result["access_token"]
raise ZoomAuthApiClientError("Unable to get access_token")
def get_acceess_token(self):
api_path = f"/token?grant_type=account_credentials&account_id={self.account_id}"
headers = self.generate_auth_headers()
response = self.authentication_client.make_post_request(
api_path, headers=headers
)
result = response.json()
access_token = self.extract_access_token(result)
return access_token
def get_access_token_from_file(self):
if self.use_path is None:
raise ZoomAuthApiClientError("use_path is None")
# join the path to the file name
file_path = os.path.join(self.use_path, "access_token")
try:
with open(file_path, "r") as token_file:
access_token = token_file.read()
return access_token
except FileNotFoundError:
return None
def get_expire_seconds_from_file(self):
# join the path to the file name
if self.use_path is None:
raise ZoomAuthApiClientError("use_path is None")
file_path = os.path.join(self.use_path, "expire_seconds")
try:
with open(file_path, "r") as token_file:
access_token = token_file.read()
return access_token
except FileNotFoundError: # pragma: no cover
return None | zoom-python-client | /zoom_python_client-0.2.2-py3-none-any.whl/zoom_python_client/zoom_auth_api/zoom_auth_api_client.py | zoom_auth_api_client.py |
import re
from enum import Enum
from typing_extensions import NotRequired, TypedDict
from zoom_python_client.utils.typed_dict_parameters import generate_parameters_dict
from zoom_python_client.zoom_client_interface import ZoomClientInterface
class RoomStatus(Enum):
OFFLINE = "Offline"
AVAILABLE = "Available"
IN_MEETING = "InMeeting"
UNDER_CONSTRUCTION = "UnderConstruction"
class RoomType(Enum):
KIOSK = "Kiosk"
ZOOM_ROOM = "ZoomRoom"
STANDALONE_WHITEBOARD = "StandaloneWhiteboard"
SCHEDULING_DISPLAY_ONLY = "SchedulingDisplayOnly"
DIGITAL_SIGNAGE_ONLY = "DigitalSignageOnly"
class NewPageToken(TypedDict):
"""The parameters for queries that return paginated results.
Args:
next_page_token (str): The token for the next page of results.
page_size (int): The number of records returned with a single API call.
"""
next_page_token: NotRequired[str]
page_size: NotRequired[int]
class RoomsListDict(NewPageToken):
"""The parameters for the get_rooms method.
Args:
status (Status): The status of the room.
type (Type): The type of the room.
unassigned_rooms (bool): Whether or not to include unassigned rooms.
location_id (str): The location ID of the room.
query_name (str): The name of the room.
"""
status: NotRequired[RoomStatus]
type: NotRequired[RoomType]
unassigned_rooms: NotRequired[bool]
location_id: NotRequired[str]
query_name: NotRequired[str]
class RoomsSensorDataDict(NewPageToken):
"""The parameters for the get_sensor_data method.
Args:
from_date (str): The start date and time for the query, should be in yyyy-MM-ddTHH:dd:ssZ format
to_date (str): The end date and time for the query, should be in yyyy-MM-ddTHH:dd:ssZ format
"""
from_date: str
to_date: str
class RoomsComponent:
def __init__(self, client: ZoomClientInterface) -> None:
self.client = client
def get_rooms(self, data: RoomsListDict) -> dict:
api_path = "/rooms"
parameters = generate_parameters_dict(data)
response = self.client.make_get_request(api_path, parameters=parameters)
result = response.json()
return result
def get_room(self, room_id: str) -> dict:
api_path = f"/rooms/{room_id}"
response = self.client.make_get_request(api_path)
result = response.json()
return result
def get_room_sensor_data(self, room_id: str, data: RoomsSensorDataDict) -> dict:
api_path = f"/rooms/{room_id}/sensor_data"
# Validate the date format
regex = r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$" # yyyy-MM-ddTHH:dd:ssZ
if not (
re.match(regex, data["from_date"]) and re.match(regex, data["to_date"])
):
raise ValueError("The date format should be in yyyy-MM-ddTHH:dd:ssZ format")
parameters = generate_parameters_dict(data)
response = self.client.make_get_request(api_path, parameters=parameters)
result = response.json()
return result | zoom-python-client | /zoom_python_client-0.2.2-py3-none-any.whl/zoom_python_client/client_components/rooms/rooms_component.py | rooms_component.py |
import base64
import json
from urllib.parse import urlencode
import requests
from zoom.exceptions import UnauthorizedError, WrongFormatInputError, ContactsLimitExceededError
class Client(object):
URL = "https://api.zoom.us/v2/"
AUTH_URL = "https://zoom.us/oauth/"
headers = {"Content-Type": "application/json", "Accept": "application/json"}
def __init__(self, client_id=None, client_secret=None, redirect_uri=None):
self.CLIENT_ID = client_id
self.CLIENT_SECRET = client_secret
self.REDIRECT_URI = redirect_uri
def authorization_url(self, code_challenge, redirect_uri=None, state=None):
if redirect_uri is not None:
self.REDIRECT_URI = redirect_uri
params = {
"client_id": self.CLIENT_ID,
"redirect_uri": self.REDIRECT_URI,
"response_type": "code",
"code_challenge": code_challenge,
}
if state:
params["state"] = state
return self.AUTH_URL + "authorize?" + urlencode(params)
def auth_headers(self):
encoded_credentials = base64.b64encode(f"{self.CLIENT_ID}:{self.CLIENT_SECRET}".encode("utf-8")).decode("utf-8")
self.headers["Authorization"] = f"Basic {encoded_credentials}"
self.headers["Content-Type"] = "application/x-www-form-urlencoded"
def get_access_token(self, code, code_verifier):
body = {
"code": code,
"grant_type": "authorization_code",
"redirect_uri": self.REDIRECT_URI,
"code_verifier": code_verifier,
}
self.auth_headers()
return self.post("token", auth_url=True, data=body)
def refresh_access_token(self, refresh_token):
body = {"refresh_token": refresh_token, "grant_type": "refresh_token"}
self.auth_headers()
return self.post("token", auth_url=True, data=body)
def set_token(self, access_token):
self.headers.update(Authorization=f"Bearer {access_token}")
def get_current_user(self):
return self.get("users/me")
def list_users(self):
return self.get("users")
def list_meetings(self):
return self.get("users/me/meetings")
def get_meeting(self, meeting_id):
return self.get(f"meetings/{meeting_id}")
def create_meeting(
self,
topic: str,
duration: int,
start_time: str,
type: int = 2,
agenda: str = None,
default_password: bool = False,
password: str = None,
pre_schedule: bool = False,
schedule_for: str = None,
timezone: str = None,
recurrence: dict = None,
settings: dict = None,
):
args = locals()
body = self.set_form_data(args)
return self.post("users/me/meetings", data=json.dumps(body))
def add_meeting_registrant(
self,
meeting_id,
email: str,
first_name: str,
last_name: str = None,
address: str = None,
city: str = None,
state: str = None,
zip: str = None,
country: str = None,
phone: str = None,
comments: str = None,
industry: str = None,
job_title: str = None,
org: str = None,
no_of_employees: str = None,
purchasing_time_frame: str = None,
role_in_purchase_process: str = None,
language: str = None,
auto_approve: bool = None,
):
args = locals()
body = self.set_form_data(args)
return self.post(f"meetings/{meeting_id}/registrants", data=json.dumps(body))
def add_webinar_registrant(
self,
webinar_id,
email: str,
first_name: str,
last_name: str = None,
address: str = None,
city: str = None,
state: str = None,
zip: str = None,
country: str = None,
phone: str = None,
comments: str = None,
industry: str = None,
job_title: str = None,
org: str = None,
no_of_employees: str = None,
purchasing_time_frame: str = None,
role_in_purchase_process: str = None,
language: str = None,
auto_approve: bool = None,
):
args = locals()
body = self.set_form_data(args)
return self.post(f"webinars/{webinar_id}/registrants", data=json.dumps(body))
def get(self, endpoint, **kwargs):
response = self.request("GET", endpoint, **kwargs)
return self.parse(response)
def post(self, endpoint, **kwargs):
response = self.request("POST", endpoint, **kwargs)
return self.parse(response)
def delete(self, endpoint, **kwargs):
response = self.request("DELETE", endpoint, **kwargs)
return self.parse(response)
def put(self, endpoint, **kwargs):
response = self.request("PUT", endpoint, **kwargs)
return self.parse(response)
def patch(self, endpoint, **kwargs):
response = self.request("PATCH", endpoint, **kwargs)
return self.parse(response)
def request(self, method, endpoint, auth_url=False, **kwargs):
return requests.request(
method, self.AUTH_URL + endpoint if auth_url else self.URL + endpoint, headers=self.headers, **kwargs
)
def parse(self, response):
status_code = response.status_code
if "Content-Type" in response.headers and "application/json" in response.headers["Content-Type"]:
try:
r = response.json()
except ValueError:
r = response.text
else:
r = response.text
if status_code == 200:
return r
if status_code == 204:
return None
if status_code == 400:
raise WrongFormatInputError(r)
if status_code == 401:
raise UnauthorizedError(r)
if status_code == 406:
raise ContactsLimitExceededError(r)
if status_code == 500:
raise Exception
return r
def set_form_data(self, args):
data = {}
for arg in args:
if args[arg] is not None and arg != "self":
data.update({f"{arg}": args[arg]})
return data | zoom-python | /zoom_python-0.1.1-py3-none-any.whl/zoom/client.py | client.py |
# Zoom Toolkit
This is a simple yet useful toolkit implemented for working on zoom records. There exists 3 functionalities that
automates the video processing procedure designed specifically for Zoom videos.
## Features
- Silence Cut
- Detecting and eliminating high amount and long duration silent parts in videos.
- Face Removal
- Automatically detects and blurs the portrait of the speaker that shares screen.
- Scene Detect
- Detects important frames.
## Installation
You can simple use pip,
```console
pip install zoom-toolkit
```
Download the source code from <a href="https://github.com/OnurArdaB/Zoom-Toolkit/">here</a> and then just type the command below inside the project folder.
```console
python setup.py install
```
## Quick Start Guide
- Silence Cut
```python
from zoom_toolkit.silencecut import SilenceCut
SilenceCut.operate(FRAME_RATE=30,SAMPLE_RATE=44100,SILENT_THRESHOLD=0.03,FRAME_SPREADAGE=1,NEW_SPEED=[5.00,1.00],FRAME_QUALITY=3,"path to the file","path to output file")
```
- Face Removal
```python
from zoom_toolkit.face_remove import FaceRemover
FaceRemover().face_remove("path to the file",False,1000,1050)
```
Module also allows users to state manual time zones for face removal with blurring or darkening option.
- Scene Detect
```python
from zoom_toolkit.scene_detector import SceneDetect
SceneDetect.Detect(input_vid_name = "video.mp4")
```
Further documentations will be announced soon.
This project has been developed under the supervision of Berrin Yanıkoğlu for ENS-492 (Graduation Project).
| zoom-toolkit | /zoom_toolkit-2.0.tar.gz/zoom_toolkit-2.0/README.md | README.md |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.