code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1
value |
|---|---|---|---|---|---|
import math
__all__ = ['LR_Scheduler', 'LR_Scheduler_Head']
class LR_Scheduler(object):
"""Learning Rate Scheduler
Step mode: ``lr = baselr * 0.1 ^ {floor(epoch-1 / lr_step)}``
Cosine mode: ``lr = baselr * 0.5 * (1 + cos(iter/maxiter))``
Poly mode: ``lr = baselr * (1 - iter/maxiter) ^ 0.9``
Args:
args: :attr:`args.lr_scheduler` lr scheduler mode (`cos`, `poly`),
:attr:`args.lr` base learning rate, :attr:`args.epochs` number of epochs,
:attr:`args.lr_step`
iters_per_epoch: number of iterations per epoch
"""
def __init__(self, mode, base_lr, num_epochs, iters_per_epoch=0,
lr_step=0, warmup_epochs=0):
self.mode = mode
print('Using {} LR scheduler with warm-up epochs of {}!'.format(self.mode, warmup_epochs))
if mode == 'step':
assert lr_step
self.base_lr = base_lr
self.lr_step = lr_step
self.iters_per_epoch = iters_per_epoch
self.epoch = -1
self.warmup_iters = warmup_epochs * iters_per_epoch
self.total_iters = (num_epochs - warmup_epochs) * iters_per_epoch
def __call__(self, optimizer, i, epoch, best_pred):
T = epoch * self.iters_per_epoch + i
# warm up lr schedule
if self.warmup_iters > 0 and T < self.warmup_iters:
lr = self.base_lr * 1.0 * T / self.warmup_iters
elif self.mode == 'cos':
T = T - self.warmup_iters
lr = 0.5 * self.base_lr * (1 + math.cos(1.0 * T / self.total_iters * math.pi))
elif self.mode == 'poly':
T = T - self.warmup_iters
lr = self.base_lr * pow((1 - 1.0 * T / self.total_iters), 0.9)
elif self.mode == 'step':
lr = self.base_lr * (0.1 ** (epoch // self.lr_step))
else:
raise NotImplemented
if epoch > self.epoch and (epoch == 0 or best_pred > 0.0):
print('\n=>Epoch %i, learning rate = %.4f, \
previous best = %.4f' % (epoch, lr, best_pred))
self.epoch = epoch
assert lr >= 0
self._adjust_learning_rate(optimizer, lr)
def _adjust_learning_rate(self, optimizer, lr):
for i in range(len(optimizer.param_groups)):
optimizer.param_groups[i]['lr'] = lr
class LR_Scheduler_Head(LR_Scheduler):
"""Incease the additional head LR to be 10 times"""
def _adjust_learning_rate(self, optimizer, lr):
if len(optimizer.param_groups) == 1:
optimizer.param_groups[0]['lr'] = lr
else:
# enlarge the lr at the head
optimizer.param_groups[0]['lr'] = lr
for i in range(1, len(optimizer.param_groups)):
optimizer.param_groups[i]['lr'] = lr * 10 | /rpa_ocr-0.2.1-py3-none-any.whl/rpa_ocr/Identify_English/lr_scheduler.py | 0.7237 | 0.301475 | lr_scheduler.py | pypi |
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Gaussian(Distribution):
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
def __init__(self, mu=0, sigma=1):
Distribution.__init__(self, mu, sigma)
def calculate_mean(self):
"""Function to calculate the mean of the data set.
Args:
None
Returns:
float: mean of the data set
"""
avg = 1.0 * sum(self.data) / len(self.data)
self.mean = avg
return self.mean
def calculate_stdev(self, sample=True):
"""Function to calculate the standard deviation of the data set.
Args:
sample (bool): whether the data represents a sample or population
Returns:
float: standard deviation of the data set
"""
if sample:
n = len(self.data) - 1
else:
n = len(self.data)
mean = self.calculate_mean()
sigma = 0
for d in self.data:
sigma += (d - mean) ** 2
sigma = math.sqrt(sigma / n)
self.stdev = sigma
return self.stdev
def plot_histogram(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.hist(self.data)
plt.title('Histogram of Data')
plt.xlabel('data')
plt.ylabel('count')
def pdf(self, x):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2)
def plot_histogram_pdf(self, n_spaces = 50):
"""Function to plot the normalized histogram of the data and a plot of the
probability density function along the same range
Args:
n_spaces (int): number of data points
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
mu = self.mean
sigma = self.stdev
min_range = min(self.data)
max_range = max(self.data)
# calculates the interval between x values
interval = 1.0 * (max_range - min_range) / n_spaces
x = []
y = []
# calculate the x values to visualize
for i in range(n_spaces):
tmp = min_range + interval*i
x.append(tmp)
y.append(self.pdf(tmp))
# make the plots
fig, axes = plt.subplots(2,sharex=True)
fig.subplots_adjust(hspace=.5)
axes[0].hist(self.data, density=True)
axes[0].set_title('Normed Histogram of Data')
axes[0].set_ylabel('Density')
axes[1].plot(x, y)
axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation')
axes[0].set_ylabel('Density')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Gaussian distributions
Args:
other (Gaussian): Gaussian instance
Returns:
Gaussian: Gaussian distribution
"""
result = Gaussian()
result.mean = self.mean + other.mean
result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2)
return result
def __repr__(self):
"""Function to output the characteristics of the Gaussian instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}".format(self.mean, self.stdev) | /rpa_olymp-0.0.tar.gz/rpa_olymp-0.0/rpa_olymp/Gaussiandistribution.py | 0.688364 | 0.853058 | Gaussiandistribution.py | pypi |
from typing import List, Optional
from pydantic import BaseModel
from datetime import datetime
from rpa_openapi.Enums import ClientType, ConnectStatus, ClientStatus, DispatchMode, AppMarketStatus, FromType, \
Progress, SchedulesTaskStatus, ScheduleType, TaskBatchStatus
class ErrorResponse(BaseModel):
"""
错误响应的数据格式
"""
timestamp: int
status: str
error: str
message: str
path: str
class Pager(BaseModel):
"""
分页的数据格式
"""
currentPage: int
totalPage: int
pageSize: int
total: int
limit: int
offset: int
class Response(BaseModel):
"""
正常请求响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: List = None
pager: Optional[Pager] = None
class ClientView(BaseModel):
"""
客户端视图信息的数据格式
"""
uuid: str
groupId: str
clientType: ClientType
name: str
ip: str
macAddress: str
status: ClientStatus
dispatchMode: DispatchMode
remark: str = None
connectTime: int
disconnectTime: int = None
userId: str
userName: str
appId: str = None
appName: str = None
taskId: str = None
connectStatus: ConnectStatus
class QueryClientViewsResponse(BaseModel):
"""
查询客户端信息响应的数据格式
"""
requestId: str
success: bool
code: int
msg: str
msgCode: str
data: List[ClientView] = None
pager: Optional[Pager] = None
instanceId: str = None
class Client(BaseModel):
"""
客户端信息的数据格式
"""
uuid: str
groupId: str
clientType: ClientType
name: str
ip: str
macAddress: str
status: ClientStatus
dispatchMode: DispatchMode
class Task(BaseModel):
"""
任务信息的数据格式
"""
uuid: str
taskBatchId: str = None
appId: str
appName: str
clientId: str
status: str
result: str
beginTime: str
endTime: str
triggerType: str
taskTrigger: str = None
client: Client = None
class QueryTaskByClientIdAndStatusResponse(BaseModel):
"""
查询指定客户端对应的任务数响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: List[Task] = None
pager: Optional[Pager] = None
class UpdateClientDispatchModeResponse(BaseModel):
"""
更新机器人调度状态响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: bool = None
pager: Optional[Pager] = None
# 修改机器人客户端状态响应的数据格式
UpdateClientInfoResponse = UpdateClientDispatchModeResponse
# 断开机器人连接状态响应的数据格式
DisconnectClientResponse = UpdateClientDispatchModeResponse
# 删除机器人客户端响应的数据格式
DeleteClientResponse = UpdateClientDispatchModeResponse
class QueryClientByUuidResponse(BaseModel):
"""
根据客户端唯一标识符查询客户端信息响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: Client = None
pager: Optional[Pager] = None
class QueryClientViewByIdResponse(QueryClientViewsResponse):
"""
查询客户端信息响应的数据格式
"""
data: ClientView = None
# 查询用户登录的客户端列表响应的数据格式
QueryMemberClientViewsResponse = QueryClientViewsResponse
class App(BaseModel):
"""
应用信息的数据格式
"""
uuid: str
name: str
catId: str
catName: str
creator: str
creatorName: str
creatorNickName: str
introduction: str
iconUrl: str
status: AppMarketStatus
version: str
groupId: str
fromType: FromType
class QueryAPPSResponse(BaseModel):
"""
获取应用列表响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: List[App] = None
pager: Optional[Pager] = None
class ApplyApp(BaseModel):
"""
申请应用信息的数据格式
"""
uuid: str
appName: str
appId: str
applicant: str
applyTime: int
reviewer: str = None
reviewTime: str = None
progress: Progress
memo: str = None
class ApplyAppResponse(BaseModel):
"""
申请应用响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: ApplyApp = None
pager: Optional[Pager] = None
class ApplyList(BaseModel):
"""
应用列表信息的数据格式
"""
uuid: str
applicantNickName: str
applicantName: str
appName: str
fromType: FromType
progress: Progress
reviewerName: str
reviewerNickName: str
reviewTime: int
applyDate: int
memo: str
class QueryApplyListResponse(BaseModel):
"""
获取申请列表响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: List[ApplyList] = None
pager: Optional[Pager] = None
MyAppApplysResponse = QueryApplyListResponse
class MyApp(BaseModel):
"""
我的应用信息的数据格式
"""
uuid: str
name: str
catId: str
catName: str
creator: str
creatorName: str
creatorNickName: str
introduction: str
iconUrl: str = None
status: AppMarketStatus
version: str
groupId: str
fromType: str
class MyAppsResponse(BaseModel):
"""
查询我的应用响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: List[MyApp] = None
pager: Optional[Pager] = None
class Approve(BaseModel):
"""
申请应用信息的数据格式
"""
uuid: str
# TODO
# appName not null
appName: str = None
appId: str
applicant: str
applyTime: int
reviewer: str = None
reviewTime: int = None
progress: Progress
memo: str = None
class ApproveResponse(BaseModel):
"""
申请应用响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: Approve = None
pager: Optional[Pager] = None
# 拒绝应用申请响应的数据格式
RejectResponse = ApproveResponse
# 取消应用申请响应的数据格式
CancelResponse = ApproveResponse
# 申请应用响应的数据格式
AppApplyResponse = ApproveResponse
class ServiceTask(BaseModel):
"""
服务型任务的数据格式
"""
taskId: str
resultUrl: str
class ServiceTaskResponse(BaseModel):
"""
服务型任务响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: ServiceTask
pager: Optional[Pager] = None
class TaskStatus(BaseModel):
"""
任务状态信息的数据格式
"""
status: SchedulesTaskStatus
statusName: str
result: str = None
class TaskStatusResponse(BaseModel):
"""
查询任务状态响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: TaskStatus
pager: Optional[Pager] = None
class ServiceResultResponse(BaseModel):
"""
查询服务型任务运行结果响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: str = None
pager: Optional[Pager] = None
# 终止任务响应的数据格式
TerminalTaskResponse = UpdateClientDispatchModeResponse
class TaskLog(BaseModel):
"""
任务日志信息的数据格式
"""
taskId: str
level: str
content: str
gmtCreate: str
class TaskLogsResponse(BaseModel):
"""
查询任务日志信息响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: List[TaskLog] = None
pager: Optional[Pager] = None
class TaskSchedules(BaseModel):
"""
计划任务信息的数据格式
"""
uuid: str
appId: str
name: str
groupId: str
status: SchedulesTaskStatus
creator: str
scheduleType: ScheduleType
scheduleExpress: str = None
scheduleCron: str = None
scheduleStartDate: str = None
scheduleEndDate: str = None
nextTaskTime: str = None
clientType: ClientType
appName: str
clientCount: int
creatorName: str
creatorNickName: str
class TaskSchedulesResponse(BaseModel):
"""
查询计划任务响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: List[TaskSchedules] = None
pager: Optional[Pager] = None
# 查询计划任务响应的数据格式
TaskScheduleByClientIdResponse = TaskSchedulesResponse
class TaskBatch(BaseModel):
"""
任务批次信息的数据格式
"""
uuid: str
taskScheduleId: str
status: TaskBatchStatus
result: str = None
beginTime: str
endTime: str
class QueryTaskBatchByTaskScheduleIdResponse(BaseModel):
"""
查询任务批次响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: List[TaskBatch] = None
pager: Optional[Pager] = None
class QueryTaskByTaskBatchIdResponse(BaseModel):
"""
查询任务批次响应的数据格式
"""
requestId: str
success: bool
msg: str
msgCode: str
data: List[Task] = None
pager: Optional[Pager] = None
class AppParam(BaseModel):
"""
应用参数的数据格式
"""
type: int
name: str
default: str = None
value: str = None
if __name__ == '__main__':
external_data = {"timestamp": 1588127383873,
"status": 500,
"error": "Internal Server Error",
"message": "feign.RetryableException: Read timed out executing GET "
"http://127.0.0.1:7002/internal/service/accesskey/queryByKey?key=5147214e66dc1135",
"path": "/rpa/openapi/file/uploadFile"}
error = ErrorResponse(**external_data)
# print(error)
# print(error.timestamp)
# print(datetime.fromtimestamp(error.timestamp / 1000))
# print(error.status)
# print(error.error)
# print(error.message)
# print(error.path)
query_client_views_response_data = {
"requestId": "f163955b-4ce0-474f-ae34-8010a7f303aa",
"success": True,
"code": 0,
"msg": "调用成功",
"msgCode": "result.success",
"data": [
{
"uuid": "771F76A4DB09F694C3655C64FD8F26E4",
"groupId": "b8e097d8-605c-47cf-a5a3-db5d13f8b4ca",
"clientType": "robot",
"name": "ITDA-D-22633726",
"ip": "30.11.92.173",
"macAddress": "A0:63:91:7F:3F:58",
"status": "unauthorized",
"dispatchMode": "attend",
"remark": None,
"connectTime": 1587722444000,
"disconnectTime": None,
"userId": "93bf42a1-6e65-4912-98b2-4d5ec0e6260a",
"userName": "ss-test",
"appId": None,
"appName": None,
"taskId": None,
"connectStatus": "unconnect"
}
],
"pager": {
"currentPage": 1,
"totalPage": 8,
"pageSize": 1,
"total": 8,
"limit": 1,
"offset": 0
}
}
query_client_views_response = QueryClientViewsResponse(**query_client_views_response_data)
print(query_client_views_response)
print(query_client_views_response.data[0].uuid) | /rpa_openapi-1.0.1.tar.gz/rpa_openapi-1.0.1/rpa_openapi/V20200430/ResponseModels.py | 0.537406 | 0.283137 | ResponseModels.py | pypi |
from rpa_openapi.Enums import SchedulesTaskStatus
from rpa_openapi.V20200430.BaseQueryRequest import BaseQueryRequest
from rpa_openapi.V20200430.path import QUERY_TASK_SCHEDULES_PATH
class QueryTaskSchedulesRequest(BaseQueryRequest):
"""
查询计划任务列表
"""
def __init__(self):
super().__init__(QUERY_TASK_SCHEDULES_PATH)
self.task_schedule_name = None
self.__task_schedule_status = None
self.__start_time = None
self.__end_time = None
def __repr__(self) -> str:
return "<QueryTaskSchedulesRequest>: task_schedule_name={}".format(
self.task_schedule_name,
self.__task_schedule_status,
self.__start_time,
self.__end_time,
self.current_page,
self.page_size
)
@property
def task_schedule_name(self) -> str:
return self.task_schedule_name
@task_schedule_name.setter
def task_schedule_name(self, value: str) -> None:
"""
:param value: taskScheduleName 计划任务名称
"""
self.task_schedule_name = value
@property
def task_schedule_status(self) -> str:
return self.__task_schedule_status
@task_schedule_status.setter
def task_schedule_status(self, value: SchedulesTaskStatus) -> None:
"""
:param: value: taskScheduleStatus 计划任务状态
"""
self.__task_schedule_status = value
@property
def start_time(self) -> str:
return self.__start_time
@start_time.setter
def start_time(self, value: str) -> None:
"""
:param value: startTime 计划任务开始时间,例如:"2020-04-28 15:24:24"
"""
self.__start_time = value
@property
def end_time(self) -> str:
return self.__end_time
@end_time.setter
def end_time(self, value: str) -> None:
"""
:param value: endTime: 计划任务结束时间,例如: "2020-04-28 15:24:43"
"""
self.__end_time = value
@property
def params(self) -> dict:
d = {}
if self.task_schedule_name:
d["taskScheduleName"] = self.task_schedule_name
if self.__task_schedule_status:
d["taskScheduleStatus"] = self.__task_schedule_status.value
if self.__start_time:
d["startTime"] = self.__start_time
if self.__end_time:
d["endTime"] = self.__end_time
if self.current_page:
d["currentPage"] = str(self.current_page)
if self.page_size:
d["pageSize"] = str(self.page_size)
return d | /rpa_openapi-1.0.1.tar.gz/rpa_openapi-1.0.1/rpa_openapi/V20200430/QueryTaskSchedulesRequest.py | 0.641871 | 0.155976 | QueryTaskSchedulesRequest.py | pypi |
import json
from json import JSONEncoder
from typing import List
from datetime import date
from rpa_openapi.Enums import SpecifiedValue, ErrorHandling, ScheduleType
from rpa_openapi.V20200430.Request import Request
from rpa_openapi.V20200430.path import CREATE_TASK_SCHEDULE_PATH
from rpa_openapi.RPAException import RPAException
class ScheduleConfig:
"""
计划配置信息
"""
def __init__(self, *, year_month_day=None, hour_minute=None, schedule_end_dt=None, specified_value=None,
interval_minute=None, interval_hour=None, interval_day=None, weeks=None, month=None,
error_handling=None, is_queue_up_type=None, task_number=None, task_priority=None, emails=None,
force_radio=True, task_schedule_start_date=None) -> None:
"""
year_month_day: 指定年月日
hour_minute: 指定时分
schedule_end_dt: 强制结束时间;forceRadio为true是,需要有强制结束时间
specified_value: 间隔值(Enum) :INTERVAL_MINUTE ,INTERVAL_HOUR ,INTERVAL_DAY
interval_minute: 间隔分钟 ,取之范围:0-59
interval_hour: 间隔小时, 取之范围:0-23
interval_day: 间隔天,取之范围:0-29
weeks: 每周第几天重复,例如:[1, 3, 5] 每周一、周三、周五重复
month: 每月第几日重复,例如:[1,10,20] 每月1号、10号、20号重复
error_handling: 错误处理方式(Enum):RESUBMIT 重试,TERMINATION 终止;选传
is_queue_up_type: 是否放入队列;选传
task_number: 任务数;选传
task_priority: 优先级 >=0 数字越大,优先级越高
emails: 邮箱参数,例如:["test1@aliyun.com", "test2@aliyun.com"]
force_radio: 是否有强制结束时间
task_schedule_start_date: 计划任务开始时间
"""
self.__year_month_day = year_month_day
self.__hour_minute = hour_minute
self.__schedule_end_dt = schedule_end_dt
self.__specified_value = specified_value
self.__interval_minute = interval_minute
self.__interval_hour = interval_hour
self.__interval_day = interval_day
self.__weeks = weeks
self.__month = month
self.__error_handling = error_handling
self.__is_queue_up_type = is_queue_up_type
self.__task_number = task_number
self.__task_priority = task_priority
self.__emails = emails
self.__force_radio = force_radio
self.__task_schedule_start_date = task_schedule_start_date
@property
def yearMonthDay(self) -> str:
return self.__year_month_day
@yearMonthDay.setter
def yearMonthDay(self, value: str) -> None:
"""
:param value: 指定年月日,例如:"2020-04-27"
"""
self.__year_month_day = value
@property
def hourMinute(self) -> str:
return self.__hour_minute
@hourMinute.setter
def hourMinute(self, value: str) -> None:
"""
:param value: 指定时分,例如:"15:18"
"""
self.__hour_minute = value
@property
def scheduleEndDt(self) -> str:
return self.__schedule_end_dt
@scheduleEndDt.setter
def scheduleEndDt(self, value: str) -> None:
"""
:param value: 强制结束时间,例如:"2020-05-29 18:20:00";forceRadio为true是,需要有强制结束时间
"""
self.__schedule_end_dt = value
@property
def specifiedValue(self) -> SpecifiedValue:
return self.__specified_value
@specifiedValue.setter
def specifiedValue(self, value: SpecifiedValue) -> None:
"""
:param value: 间隔值(Enum) :INTERVAL_MINUTE ,INTERVAL_HOUR ,INTERVAL_DAY
"""
self.__specified_value = value
@property
def intervalMinute(self) -> int:
return self.__interval_minute
@intervalMinute.setter
def intervalMinute(self, value: int) -> None:
"""
:param value: 间隔分种 ,取之范围:0-59
"""
if value < 0 or value > 59:
raise ValueError("间隔分的取值范围为:0-59")
self.__interval_minute = value
@property
def intervalHour(self) -> int:
return self.__interval_hour
@intervalHour.setter
def intervalHour(self, value: int) -> None:
"""
:param value: 间隔小时, 取之范围:0-23
"""
if value < 0 or value > 23:
raise ValueError("间隔时的取值范围为:0-23")
self.__interval_hour = value
@property
def intervalDay(self) -> int:
return self.__interval_day
@intervalDay.setter
def intervalDay(self, value: int) -> None:
"""
:param value: 间隔天,取之范围:0-29
"""
if value < 0 or value > 29:
raise ValueError("间隔天的取值范围为:0-29")
self.__interval_day = value
@property
def weeks(self) -> str:
return self.__weeks
@weeks.setter
def weeks(self, value: List[int]) -> None:
"""
:param value: 每周第几天重复,例如:[1, 3, 5] 每周一、周三、周五重复
"""
temp_value = [str(i) for i in value]
self.__month = ",".join(temp_value)
@property
def month(self) -> str:
return self.__month
@month.setter
def month(self, value: List[int]) -> None:
"""
:param value: 每月第几日重复,例如:[1, 10, 20] 每月1号、10号、20号重复
"""
temp_value = [str(i) for i in value]
self.__month = ",".join(temp_value)
@property
def errorHandling(self) -> ErrorHandling:
return self.__error_handling
@errorHandling.setter
def errorHandling(self, value: ErrorHandling) -> None:
"""
:param value: 错误处理方式(Enum):RESUBMIT 重试,TERMINATION 终止;选传
"""
self.__error_handling = value
@property
def isQueueUpType(self) -> bool:
return self.__is_queue_up_type
@isQueueUpType.setter
def isQueueUpType(self, value: bool) -> None:
"""
:param value: 是否放入队列;选传
"""
self.__is_queue_up_type = value
@property
def taskNumber(self) -> int:
return self.__task_number
@taskNumber.setter
def taskNumber(self, value: int) -> None:
"""
:param value: 任务数;选传
"""
self.__task_number = value
@property
def tasKPriority(self) -> int:
return self.__task_priority
@tasKPriority.setter
def tasKPriority(self, value: int) -> None:
"""
:param value: 优先级 >=0 数字越大,优先级越高
"""
self.__task_priority = value
@property
def emails(self) -> str:
return self.__emails
@emails.setter
def emails(self, value: list) -> None:
"""
:param value: 邮箱参数,例如:["test1@aliyun.com", "test2@aliyun.com"]
"""
self.__emails = ",".join(value)
@property
def forceRadio(self) -> bool:
return self.__force_radio
@forceRadio.setter
def forceRadio(self, value: bool) -> None:
"""
:param value: 是否有强制结束时间
"""
self.__force_radio = value
@property
def taskScheduleStartDate(self) -> str:
return self.__task_schedule_start_date
@taskScheduleStartDate.setter
def taskScheduleStartDate(self, value: str) -> None:
"""
:param value: 计划任务开始时间,例如:"2020-05-29 18:20:00"
"""
self.__task_schedule_start_date = value
def __getitem__(self, item):
return getattr(self, item)
def keys(self):
attrs = ["yearMonthDay", "hourMinute", "scheduleEndDt", "specifiedValue", "intervalMinute", "intervalHour",
"intervalDay", "weeks", "month", "errorHandling", "isQueueUpType", "taskNumber", "tasKPriority",
"emails", "forceRadio", "taskScheduleStartDate"]
l = []
for i in attrs:
if getattr(self, i) is not None:
l.append(i)
return l
class _JSONEncoder(JSONEncoder):
def default(self, o):
if hasattr(o, '__getitem__'):
return dict(o)
if isinstance(o, SpecifiedValue):
print(o)
return o.value
class CreateTaskScheduleRequest(Request):
"""
创建计划任务
"""
def __init__(self):
super().__init__(CREATE_TASK_SCHEDULE_PATH)
self.__app_id = None
self.__name = None
self.__client_ids = []
self.__schedule_type = None
self.__schedule_config = None
self.__app_params = None
self.method = "POST"
def __repr__(self) -> str:
return "<CreateTaskScheduleRequest>: " \
"app_id={}, name={}, client_ids={}, schedule_type={}, schedule_config={}, app_params={}" \
.format(self.__app_id,
self.__name,
self.__client_ids,
self.__schedule_type,
self.__schedule_config,
self.__app_params)
@property
def app_id(self) -> str:
return self.__app_id
@app_id.setter
def app_id(self, value: str) -> None:
"""
:param value: appId 应用唯一标识符
"""
self.__app_id = value
@property
def name(self) -> str:
return self.__name
@name.setter
def name(self, value: str) -> None:
"""
:param value: name 计划任务名称
"""
self.__name = value
@property
def client_ids(self) -> list:
return self.__client_ids
@client_ids.setter
def client_ids(self, value: list) -> None:
"""
:param value: robotUuid,客户端唯一标识符,一次查询多个客户端的任务时,使用‘,’连接客户端唯一识别符,
如:['5E77DA4EB87BCFB62A8B9527626A47F4', '50E6071F3ABCB36B6DECCE2BB4C2A303']
"""
self.__client_ids = value
@property
def schedule_type(self) -> list:
return self.__schedule_type
@schedule_type.setter
def schedule_type(self, value: ScheduleType) -> None:
"""
:param value: scheduleType 计划任务类型
"""
self.__schedule_type = value
@property
def schedule_config(self) -> str:
return self.__schedule_config
@schedule_config.setter
def schedule_config(self, value: ScheduleConfig) -> None:
"""
:param value: appParams 应用参数
"""
self.__schedule_config = value
@property
def app_params(self) -> str:
return self.__app_params
@app_params.setter
def app_params(self, value: ScheduleConfig) -> None:
"""
:param value: scheduleConfig 计划任务执行所需应用参数
"""
self.__app_params = json.dumps(value)
@property
def params(self) -> dict:
d = {}
if self.__app_id:
d["appId"] = self.__app_id
else:
raise RPAException("appId参数不能为空")
if self.__name:
d["name"] = self.__name
else:
raise RPAException("name参数不能为空")
if self.__client_ids:
d["clientIds"] = ",".join(self.__client_ids)
else:
raise RPAException("clientIds参数不能为空")
if self.__schedule_type:
d["scheduleType"] = self.__schedule_type.value
else:
raise RPAException("scheduleType参数不能为空")
if self.__schedule_config:
d["scheduleConfig"] = json.dumps(self.__schedule_config, cls=_JSONEncoder)
else:
raise RPAException("scheduleConfig参数不能为空")
if self.__app_params:
d["appParams"] = self.__app_params
return d
if __name__ == '__main__':
s = ScheduleConfig()
# s.yearMonthDay = "2020-04-27"
# s.hourMinute = "15:18"
# s.scheduleEndDt = "2020-05-29 18:20:00"
s.specifiedValue = SpecifiedValue.INTERVAL_MINUTE
# s.intervalMinute = 1
# s.intervalHour = 3
# s.intervalDay = 5
s.weeks = ["1", "2"]
s.month = ["1", "2"]
print(json.dumps(s, cls=_JSONEncoder)) | /rpa_openapi-1.0.1.tar.gz/rpa_openapi-1.0.1/rpa_openapi/V20200430/CreateTaskScheduleRequest.py | 0.638948 | 0.174375 | CreateTaskScheduleRequest.py | pypi |
import os.path
from typing import Literal
import subprocess
from pypdf import PdfMerger, PdfReader, PdfWriter
from fpdf import FPDF
from .common import set_x_pos, set_y_pos
class Pdf():
""" Pdf class """
def __init__(self) -> None:
self.__root_dir__: str = os.path.dirname(os.path.abspath(__file__))
self.__fonts_dir__: str = os.path.join(self.__root_dir__, 'fonts')
self.__exec_dir__: str = os.path.join(self.__root_dir__, 'exec')
def compress(self, pdf_file_path: str) -> None:
"""
Compress pdf file to decrease the file size
Args:
pdf_file_path (str): full path of the pdf file
Raises:
FileNotFoundError: when the file has not been found
Exception: other problem occured
"""
try:
if os.path.exists(pdf_file_path) is False:
raise FileNotFoundError(f'{pdf_file_path} does not exist')
writer = PdfWriter()
reader = PdfReader(pdf_file_path)
writer.clone_document_from_reader(reader)
for page in writer.pages:
page.compress_content_streams()
with open(pdf_file_path, 'wb') as pdf:
writer.write(pdf)
except Exception as ex:
raise ex
def text_to_pdf(
self,
text: str,
output_file_path: str,
font_family: str = 'DejaVu Sans',
font_file_path: str | bool = False,
font_unicode: bool = True,
font_style: Literal['', 'B', 'I', 'U', 'BU', 'UB', 'BI', 'IB', 'IU', 'UI', 'BIU', 'BUI', 'IBU', 'IUB', 'UBI', 'UIB'] = '',
font_size: int = 12,
text_vertical_position: Literal['top', 'center', 'bottom'] = 'top',
text_horizontal_position: Literal['left', 'center', 'right'] = 'left',
page_orientation: Literal['portrait', 'landscape'] = 'portrait',
page_units: Literal['mm', 'pt', 'cm', 'in'] = 'mm',
page_format: Literal['A3', 'A4', 'A5', 'Letter', 'Legal'] | tuple[float, float] = 'A4',
page_vertical_margin: int = 10,
page_horizontal_margin: int = 10
) -> None:
"""
Convert text to pdf file.
Args:
text (str): text value
output_file_path (str): full path of the output file
font_family (str, optional): you can change default value by providing the font_family (ex. 'Arial') and the font_file_path (ex. 'c:/windows/fonts/Arial.ttf'). Defaults to 'DejaVu Sans'.
font_file_path (str | bool, optional): font file path; use only with font_family. Defaults to False.
font_unicode (bool, optional): font code format. Defaults to True.
font_style (Literal['', 'B', 'I', 'U', 'BU', 'UB', 'BI', 'IB', 'IU', 'UI', 'BIU', 'BUI', 'IBU', 'IUB', 'UBI', 'UIB'], optional): _description_. Defaults to ''.
font_size (int, optional): font size. Defaults to 12.
text_vertical_position (Literal['top', 'center', 'bottom'], optional): vertical position of the text. Defaults to 'top'.
text_horizontal_position (Literal['left', 'center', 'right'], optional): horizontal position of the text. Defaults to 'left'.
page_orientation (Literal['portrait', 'landscape'], optional): page orientation. Defaults to 'portrait'.
page_units (Literal['mm', 'pt', 'cm', 'in'], optional): _description_. Defaults to 'mm'.
page_format (Literal['A3', 'A4', 'A5', 'Letter', 'Legal'] | tuple[float, float], optional): page format. Defaults to 'A4'.
page_vertical_margin (int, optional): page vertical margin. Defaults to 10.
page_horizontal_margin (int, optional): page horizontal margin. Defaults to 10.
"""
try:
fpdf: FPDF = FPDF(orientation=page_orientation, unit=page_units, format=page_format)
fpdf.compress = True
# set style and size of font that you want in the pdf
fpdf.add_font(font_family, '', font_file_path if isinstance(font_file_path, str) else f'{self.__fonts_dir__}\\DejaVuSans.ttf', font_unicode)
fpdf.set_font(family=font_family, style=font_style, size=font_size)
# add a page
fpdf.add_page()
# get text width
string_width: float = fpdf.get_string_width(text)
# set position of text
x_pos: float = set_x_pos(text_horizontal_position, page_horizontal_margin, fpdf.w, string_width)
y_pos: float = set_y_pos(text_vertical_position, page_vertical_margin, fpdf.h, font_size)
# add text
fpdf.text(x_pos, y_pos, text)
# save the pdf with name .pdf
fpdf.output(output_file_path)
except Exception as ex:
raise ex
def merge(self, pdf_files: list, output_pdf_file_path: str) -> None:
"""
Merge given pdf files
Args:
pdf_files (list): list of paths to pdf files in order
output_pdf_file_path (str): path of the output pdf file (merged)
Raises:
FileNotFoundError: if the file is missing
FileExistsError: if the output file exists and cannot be overwritten
Exception: other errors
"""
try:
# check if input file exists
for file_path in pdf_files:
if os.path.exists(file_path) is False:
raise FileNotFoundError(f'{file_path} does not exist')
merge_file: PdfMerger = PdfMerger()
for pdf_file in pdf_files:
pdf_reader = PdfReader(pdf_file)
merge_file.append(pdf_reader)
merge_file.write(output_pdf_file_path)
merge_file.close()
if os.path.exists(output_pdf_file_path) is False:
raise FileExistsError(f'{output_pdf_file_path} was not generated.')
except Exception as ex:
raise ex
def print(
self,
pdf_file_path: str,
printer: str = 'default',
pages: Literal['all', 'first', 'last'] | list = 'all',
odd_or_even: Literal['odd', 'even'] | bool = False,
orientation: Literal['portrait', 'landscape'] = 'portrait',
scale: Literal['noscale', 'shrink', 'fit'] = 'fit',
color: Literal['color', 'monochrome'] = 'color',
mode: Literal['duplex', 'duplexshort', 'duplexshort', 'simplex'] = 'simplex',
paper: Literal['A2', 'A3', 'A4', 'A5', 'A6', 'letter', 'legal', 'tabloid', 'statement'] = 'A4'
) -> None:
"""
Print PDF document.
Works only on Windows
Args:
pdf_file_path (str): full file path
printer (str, optional): printer name; if empty or default will print on the default printer. Defaults to 'default'.
pages (Literal["all", "first", "last"] | list, optional): determines which pages should be printed; can select "all", "first", "last" or range of pages, ex. 1,3-5,-1 to print pages: 1, 3, 4, 5 and the last one (-1). Defaults to 'all'.
odd_or_even (Literal["odd", "even"] | bool, optional): print only odd or even pages from the selected range. Defaults to False.
orientation (Literal["portrait", "landscape"], optional): page orientation. Defaults to 'portrait'.
scale (Literal["noscale", "shrink", "fit"], optional): scale. Defaults to 'fit'.
color (Literal["color", "monochrome"], optional): determine if print in color or monochrome. Defaults to 'color'.
mode (Literal["duplex", "duplexshort", "duplexshort", "simplex"], optional): print mode. Defaults to 'simplex'.
paper (Literal["A2", "A3", "A4", "A5", "A6", "letter", "legal", "tabloid", "statement"], optional): paper size. Defaults to 'A4'.
Raises:
FileNotFoundError: if file is missing
Exception: general errors
"""
# check if input file exists
if os.path.exists(pdf_file_path) is False:
raise FileNotFoundError(f'{pdf_file_path} does not exist')
sumatra_path: str = f'{self.__exec_dir__}\\sumatra.exe'
printer_mode: str = '-print-to-default' if printer == 'default' else f'-print-to "{printer}"'
settings: list = []
# page range to print
if isinstance(pages, list):
settings.append(",".join(pages))
match pages.lower():
case "first":
settings.append("1")
case "last":
settings.append("-1")
case "all":
settings.append("*")
case _:
raise ValueError("incorrect range of pages to print; correct vaules: all, first, last, or list (ex. [1,2,3-5,-1])")
# page to print: odd or even or all
if isinstance(odd_or_even, str):
match odd_or_even.lower():
case 'odd':
settings.append('odd')
case 'even':
settings.append('even')
case _:
raise ValueError("incorrect value for odd_or_even attribute; correct values: odd, even")
# page orientation
settings.append(orientation)
# content scale
settings.append(scale)
# color
settings.append(color)
# print mode
settings.append(mode)
# paper size
settings.append(f'paper={paper}')
print_settings: str = f'-print-settings "{",".join(settings)}"'
try:
subprocess.run(f'{sumatra_path} {printer_mode} {print_settings} -silent "{pdf_file_path}"', check=True)
except subprocess.CalledProcessError as ex:
raise ex | /rpa-pdf-1.1.13.tar.gz/rpa-pdf-1.1.13/rpa_pdf/Pdf.py | 0.681939 | 0.153232 | Pdf.py | pypi |
from time import sleep
from collections import namedtuple
import win32com.client
from pandas import DataFrame
Cell_Address = namedtuple('Cell_Address', ['row', 'column'])
class GridView:
def __init__(self, sap_gui):
self.sap_gui = sap_gui
def get_object(self, field_id: str):
return self.sap_gui.get_object(field_id)
def count_rows(self, grid_view_id: str) -> int:
"""
Count row of GridView object.
Args:
grid_view_id (str): GridView field id.
Returns:
int: number of rows
"""
grid_view = self.get_object(grid_view_id)
return grid_view.RowCount
def count_columns(self, grid_view_id: str) -> int:
"""
Count columns of GridView object.
Args:
grid_view_id (str): GridView field id.
Returns:
int: number of columns
"""
grid_view = self.get_object(grid_view_id)
return grid_view.ColumnCount
def get_current_cell_value(self, grid_view_id: str) -> object:
"""
Return the value of current GridView cell.
Args:
grid_view_id (str): GridView field id.
Returns:
object: Value of GridView cell
"""
grid_view = self.get_object(grid_view_id)
return grid_view.GetCellValue(grid_view.CurrentCellRow, grid_view.CurrentCellColumn)
def get_current_cell(self, grid_view_id: str):
"""
Return row index and column index of current GridView cell.
Args:
grid_view_id (str): GridView field id.
Returns:
GridViewCell['row', 'column']: object with row and column attributes.
"""
grid_view = self.get_object(grid_view_id)
GridViewCell = namedtuple('GridViewCell', ['row', 'column'])
return GridViewCell(grid_view.CurrentCellRow, self.__get_column_index__(grid_view, grid_view.CurrentCellColumn))
def set_current_cell(self, grid_view_id: str, row_index: int, column_index: int):
"""
Set current cell of GridView object.
Args:
grid_view_id (str): GridView field id.
row_index (int): Row index.
column_index (int): Column index.
"""
grid_view = self.get_object(grid_view_id)
grid_view.SetCurrentCell(row_index, self.__get_column_name__(grid_view, column_index))
def get_current_column_name(self, grid_view_id: str) -> str:
"""
Return the name of current column of the GridView object.
Args:
grid_view_id (str): GridView field id.
Returns:
str: column name
"""
grid_view = self.get_object(grid_view_id)
return grid_view.CurrentCellColumn
def set_current_column_name(self, grid_view_id: str, column_name: str):
"""
Set current column of the GridView by column name
Args:
grid_view_id (str): GridView field id.
column_name (str): Column name.
"""
grid_view = self.get_object(grid_view_id)
grid_view.CurrentCellColumn = column_name
def get_current_column_index(self, grid_view_id: str) -> int:
"""
Return index of current GridView column.
Args:
grid_view_id (str): GridView field id.
Returns:
int: number value.
"""
grid_view = self.get_object(grid_view_id)
for column_index in range(0, grid_view.ColumnOrder.Count):
if grid_view.ColumnOrder[column_index] == grid_view.CurrentCellColumn:
return column_index
def set_current_column_index(self, grid_view_id: str, column_index: int):
"""
Set the index of current column of GridView object.
Args:
grid_view_id (str): GridView field id.
column_index (int): Column Index
"""
grid_view = self.get_object(grid_view_id)
grid_view.CurrentCellColumn = self.__get_column_name__(grid_view, column_index)
def get_current_row_index(self, grid_view_id: str) -> int:
"""
Return the index of current GridView row.
Args:
grid_view_id (str): GridView field id.
Returns:
int: number value
"""
grid_view = self.get_object(grid_view_id)
return grid_view.CurrentCellRow
def set_current_row_index(self, grid_view_id: str, row_index: int):
"""
Set the index of current row of GridView object.
Args:
grid_view_id (str): GridView field id.
row_index (int): Row index.
"""
grid_view = self.get_object(grid_view_id)
grid_view.CurrentCellRow = row_index
def get_selected_rows(self, grid_view_id: str) -> list:
"""
Return indexes of selected GridView rows.
Args:
grid_view_id (str): GridView field id.
Returns:
list: list of selected row indexes
"""
grid_view = self.get_object(grid_view_id)
selected_rows: str = str(grid_view.SelectedRows)
if selected_rows == "":
return None
rows_list: list = []
for row in selected_rows.split(','):
if '-' in row:
index_range: list[str] = row.split('-')
for index in range(index_range[0], index_range[1]):
rows_list.append(index)
rows_list.append(int(row))
return rows_list
def set_selected_rows(self, grid_view_id: str, row_indexes: list[int] | str):
"""
Set selected rows of GridView object.
Args:
grid_view_id (str): GridView field id
row_indexes (list[int] | str): can be a str, ex. "1", or "1,2" or "1-3" if you want to select a range, or the list of int ex. [1,2,3]
"""
selected_rows: str
if isinstance(row_indexes, str):
selected_rows = row_indexes
if isinstance(row_indexes, list[int]):
selected_rows = ','.join([str(item) for item in row_indexes])
grid_view = self.get_object(grid_view_id)
grid_view.SelectedRows(selected_rows)
def clear_selection(self, grid_view_id: str):
"""
Clear row selection of the GridView object.
Args:
grid_view_id (str): GridView field id.
"""
grid_view = self.get_object(grid_view_id)
grid_view.ClearSelection()
def double_click_cell(self, grid_view_id: str, row_index: int = None, column_index: int = None):
"""
Double click the cell of GridView object.
Args:
grid_view_id (str): GridView field id
row_index (int, optional): Row index. Defaults to None.
column_index (int, optional): Column index. Defaults to None.
"""
grid_view = self.get_object(grid_view_id)
if row_index is not None or column_index is not None:
column_name: str = self.__get_column_name__(grid_view, self.get_current_column_index(grid_view_id)) if column_index is None else self.__get_column_name__(grid_view, column_index)
row_index = self.get_current_row_index(grid_view_id) if row_index is None else row_index
grid_view.SetCurrentCell(row_index, column_name)
grid_view.currentCellRow = row_index
grid_view.selectedRows = row_index
grid_view.DoubleClickCurrentCell()
def convert_column_index_to_name(self, grid_view_id: str, column_name: str) -> int:
grid_view = self.get_object(grid_view_id)
column_index: int
for column_index in range(0, grid_view.ColumnCount):
if column_name == grid_view.ColumnOrder[column_index]:
return column_index
raise Exception(f'Cannot find column {column_name}')
def get_cell_address_by_cell_value(self, grid_view_id: str, cell_value: str) -> list[Cell_Address]:
""" Return the list of Cell_Address[row, column] objects
Args:
grid_view_id (str): Field id
cell_value (str): searched value
Returns:
list[Cell_Address]: Cell_Address object with parameters: row and column
Usage:
cell_address = sap.grid_view.get_cell_address_by_cell_value('wnd[0]/shell', 'test)\n\r
cell_address[0].row # contains the index of a row for the first matched cell\n\r
cell_address[0].column # contains the index of a column for the first matched cell\n\r
"""
grid_view = self.get_object(grid_view_id)
indexes = self.__get_cell_address_by_value__(grid_view, cell_value)
if len(indexes) == 0:
raise Exception(f'The GridView row not found for the value: {cell_value}')
return indexes
def get_cell_state(self, grid_view_id: str, row_index: int = None, column_index: int = None) -> str:
grid_view = self.get_object(grid_view_id)
r_index = row_index if row_index is not None else self.get_current_row_index
c_index = column_index if column_index is not None else self.get_current_column_index
return grid_view.GetCellState(r_index, self.__get_column_name__(grid_view, c_index))
def get_cell_value(self, grid_view_id: str, row_index: int = None, column_index: int = None) -> object:
""" Return the value of the GridView cell
Args:
grid_view_id (str): Field id
row_index (int, optional): Row index. Defaults to None.
column_index (int, optional): Column index. Defaults to None.
Returns:
object: value (Any)
"""
grid_view = self.get_object(grid_view_id)
r_index = row_index if row_index is not None else self.get_current_row_index
c_index = column_index if column_index is not None else self.get_current_column_index
return grid_view.GetCellValue(r_index, self.__get_column_name__(grid_view, c_index))
def press_toolbar_button(self, grid_view_id: str, button_id: str):
grid_view = self.get_object(grid_view_id)
grid_view.pressToolbarButton(button_id)
def press_toolbar_context_button(self, grid_view_id: str, button_id: str):
grid_view = self.get_object(grid_view_id)
grid_view.pressToolbarContextButton(button_id)
def press_toolbar_context_button_and_select_context_menu_item(self, grid_view_id: str, button_id: str, function_code: str):
grid_view = self.get_object(grid_view_id)
grid_view.pressToolbarContextButton(button_id)
sleep(1)
grid_view.selectContextMenuItem(function_code)
grid_view.ActiveWindow.setFocus()
def select_all_cells(self, grid_view_id: str):
grid_view = self.get_object(grid_view_id)
grid_view.SelectAll()
def select_column(self, grid_view_id: str, column_index: int):
grid_view = self.get_object(grid_view_id)
grid_view.SelectColumn(self.__get_column_name__(grid_view, column_index))
def select_context_menu_item(self, grid_view_id: str, function_code: str):
grid_view = self.get_object(grid_view_id)
grid_view.contextMenu()
grid_view.selectContextMenuItem(function_code)
def select_rows_by_cell_value(self, grid_view_id: str, cell_value: object):
grid_view = self.get_object(grid_view_id)
indexes = self.__get_cell_address_by_value__(grid_view, cell_value)
if len(indexes) == 0:
raise Exception('The GridView row not found for the value: %s' % cell_value)
for row_index, column_index in indexes:
column_name = self.__get_column_name__(grid_view, column_index)
grid_view.SetCurrentCell(row_index, column_name)
grid_view.currentCellRow = row_index
grid_view.selectedRows = ','.join([str(r) for r, c in indexes])
def set_current_cell_by_cell_value(self, grid_view_id: str, cell_value: object):
grid_view = self.get_object(grid_view_id)
indexes = self.__get_cell_address_by_value__(grid_view, cell_value)
if len(indexes) == 0:
raise Exception(f'The GridView row not found for the value: {cell_value}')
for row_index, column_index in indexes:
column_name = self.__get_column_name__(grid_view, column_index)
grid_view.SetCurrentCell(row_index, column_name)
def to_array(self, grid_view_id: str) -> list:
grid_view = self.get_object(grid_view_id)
return [self.__get_headers__(grid_view), *self.__get_body__(grid_view)]
def to_dict(self, grid_view_id: str) -> dict:
grid_view = self.get_object(grid_view_id)
return {'columns': self.__get_headers__(grid_view), 'data': self.__get_body__(grid_view)}
def to_dataframe(self, grid_view_id: str) -> DataFrame:
grid_view = self.get_object(grid_view_id)
return DataFrame(data=self.__get_body__(grid_view), columns=self.__get_headers__(grid_view))
def to_csv(self, grid_view_id: str, path_or_buf: str):
grid_view = self.get_object(grid_view_id)
self.to_dataframe(grid_view).to_csv(
path_or_buf=path_or_buf, index=False)
def to_xlsx(self, grid_view_id: str, file_path: str):
grid_view = self.get_object(grid_view_id)
self.to_dataframe(grid_view).to_excel(file_path, index=False)
# Magic methods - Grid View
def __get_column_index__(self, grid_view: win32com.client.dynamic.CDispatch, column_name: str):
for column_index in range(0, grid_view.ColumnOrder.Count):
return column_index if column_name == grid_view.ColumnOrder[column_index] else None
def __get_column_name__(self, grid_view: win32com.client.dynamic.CDispatch, column_index: int) -> str:
return grid_view.ColumnOrder[column_index]
def __get_cell_address_by_value__(self, grid_view: win32com.client.dynamic.CDispatch, cell_value: object):
results = []
for row_index in range(0, grid_view.RowCount):
for column_index in range(0, grid_view.ColumnOrder.Count):
if cell_value == grid_view.GetCellValue(row_index, grid_view.ColumnOrder(column_index)):
results.append(Cell_Address(row_index, column_index))
return results
def __get_headers__(self, grid_view: win32com.client.dynamic.CDispatch) -> list:
return [grid_view.GetColumnTitles(column_name)[0] for column_name in grid_view.ColumnOrder]
def __get_body__(self, grid_view: win32com.client.dynamic.CDispatch) -> list:
body = []
for row_index in range(0, grid_view.RowCount):
row = []
for column_index in range(0, grid_view.ColumnCount):
row.append(grid_view.GetCellValue(
row_index, self.__get_column_name__(grid_view, column_index)))
body.append(row)
return body | /rpa-sap-1.1.3.tar.gz/rpa-sap-1.1.3/rpa_sap/lib/GridView.py | 0.89977 | 0.45042 | GridView.py | pypi |
import signal
import re
import time
from typing import List
import robot
from robot.api import logger
from robot.libraries.BuiltIn import BuiltIn
from robot.libraries.Screenshot import Screenshot
from tos.settings import PLATFORM
from .exceptions import AbortException
from . import messages
def handle_dead_selenium():
"""
If selenium/chromedriver is killed on purpose or by error,
stop the robot execution to prevent unnecessary retrying.
"""
# TODO: find a way to use this automatically in a sensible way.
# Selenium existence should be enforced only in stages
# where selenium is used!
try:
selenium_lib = BuiltIn().get_library_instance("SeleniumLibrary")
except Exception:
logger.debug(
"Not checking webdriver existence as SeleniumLibrary was not found"
)
return
status = get_webdriver_status(selenium_lib)
if status == "dead": # alive means an open chrome window
raise RuntimeError(messages.WEBDRIVER_DEAD)
def get_webdriver_status(selenium_lib):
from selenium.webdriver.remote.command import Command
try:
selenium_lib.driver.execute(Command.STATUS)
except Exception:
return "dead"
return "alive"
def handle_signals():
"""Listen for TERM / INT signals and handle appropriately"""
# TODO: find a way to test catching SIGINT/KeyboardInterrupt
signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGINT, sigint_handler)
def sigint_handler(signum, frame):
"""Detect SIGINT or Keyboard interrupt signals.
Pass the information as exception message to ``action_on_fail``
later on to be handled.
"""
raise AbortException(messages.SIGINT_MESSAGE)
def sigterm_handler(signum, frame):
"""Detect SIGTERM signals.
Pass the information as exception message to ``action_on_fail``
later on to be handled.
"""
raise AbortException(messages.SIGTERM_MESSAGE)
def take_screenshot():
"""Take screenshot of all visible screens.
Use Robot Framework standard library with Scrot screenshotting utility.
"""
if PLATFORM == "Linux":
module = "Scrot" # NOTE: needs Scrot to be installed with apt-get or similar
elif PLATFORM == "Windows": # pragma: no cover
module = "Pil"
elif PLATFORM == "Darwin": # pragma: no cover
module = None # NOTE: OS X uses built-in screencapture tool
else: # pragma: no cover
logger.warn("Screenshotting is supported only on Windows, Linux and OS X")
return
try:
Screenshot(screenshot_module=module).take_screenshot()
except robot.libraries.BuiltIn.RobotNotRunningError as err:
logger.warn(
f"Robot needs to be running for screenshotting to work: {str(err)}")
except Exception: # pragma: no cover
logger.warn("You need to install Scrot on Linux and Pil on Windows")
def repeat_call_until(*args, **kwargs):
"""Repeat given function or method call until given condition is True.
:param kwargs:
- **callable** (func) - Callable method or function (required).
- **condition** (func) - Condition to wait for (required)
- **arguments** (tuple) - Tuple of arguments to pass for the callable.
- **kwarguments** (dict) - Dict of kw arguments to pass for the callable.
- **limit** (int) - limit for retries.
- **sleep** (int) - time to sleep between retries.
Usage:
.. code-block:: python
class RobotLibrary:
'''Example RF library with retry condition as a method.'''
def btn1_is_enabled(self):
return browser.find_element_by_name("btn1").is_enabled()
@keyword
def retry_clicking_until_success(self):
repeat_call_until(
callable=BuiltIn().run_keyword,
condition=self.btn1_is_enabled,
arguments=("SeleniumLibrary.Click Element", "btn2"),
limit=5
)
"""
required_kwargs = ("callable", "condition")
if not all(kwarg in kwargs for kwarg in required_kwargs):
raise TypeError(f"Missing required kwargs {required_kwargs}")
func = kwargs["callable"]
condition = kwargs["condition"]
limit = kwargs.get("limit", 3)
sleep = kwargs.get("sleep", 1)
counter = 0
while not condition():
if counter <= limit:
value = func(
*kwargs.get("arguments", ()),
**kwargs.get("kwarguments", {})
)
else:
raise RuntimeError(
f"Tried to retry action {str(func)} {limit} times without success."
)
counter += 1
time.sleep(sleep)
return value
def get_stage_from_tags(tags: List) -> int:
"""Get the stage number from the stage tag.
It is required that the stage tags include one tag of the form 'stage_0'.
Example:
>>> tags = ["stage_0", "repeat"]
>>> get_stage_from_tags(tags)
0
"""
try:
stage_tag = next(filter(lambda tag: tag.startswith("stage_"), tags))
return int(re.search(r"\d+", stage_tag).group())
except (StopIteration, ValueError):
raise ValueError | /rpadriver-1.3.0-py3-none-any.whl/RPALibrary/helpers.py | 0.433981 | 0.25311 | helpers.py | pypi |
import functools
import sys
import traceback
from typing import Tuple
from robot.api import logger
from tos.statuses import is_failure, is_business_failure, is_skip
from .exceptions import (
get_status_by_exception,
)
def log_number_of_created_task_objects(func):
"""
Decorator for logging the number of processed task objects.
Note that the function to decorate should return the
number of processed objects.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
counter = func(*args, **kwargs)
if counter == 0:
logger.warn("No task objects processed")
else:
logger.info(f"\n[ INFO ] {counter} task object(s) processed", also_console=True)
return counter
return wrapper
def handle_errors(error_msg="") -> Tuple[dict, str, str]:
"""
Decorator for handling all general exceptions.
Function to decorate ``func`` is the set of actions we are trying to do
(e.g., ``main_action`` method). That function can take arbitrary arguments.
All exceptions are caught when this function is called. When exception
occurs, full stacktrace is logged with Robot Framework logger and the status
of task object is set to 'fail'.
The task object should be passed as a keyword argument so it can
be accessed here inside the decorator, but really it is used only for logging.
Nothing breaks if it is omitted.
:returns: tuple of (value, status, error), where value is the return value of the
decorated function or ``None``, and the error is the text from the exception
encountered in this function call. Status is always either
"pass", "fail", "expected_fail", or "skip".
Usage example:
.. code-block:: python
class RobotLibrary:
def __init__(self):
self.error_msg = "Alternative error message"
@handle_errors("One is not one anymore")
def function_which_might_fail(self, to=None):
if to["one"] != 1:
raise ValueError
>>> RobotLibrary().function_which_might_fail(to={"one": 2})
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
custom_error_message = error_msg
if not error_msg:
# TODO: is this custom error message ever needed?
custom_error_message = getattr(self, "error_msg", "")
to = kwargs.get("to", {})
value = None
status = None
error_text = None
try:
value = func(*args, **kwargs)
except NotImplementedError:
raise
except Exception as err:
exc_name = err.__class__.__name__
stacktrace, _ = _get_stacktrace_string(sys.exc_info())
error_text = f"{exc_name}: {stacktrace}"
status = get_status_by_exception(err)
log_message_by_status(status, to, error_text, custom_error_message)
else:
status = "pass"
return (value, status, error_text)
return wrapper
return decorator
def log_message_by_status(status, to, error_text, custom_error_message):
def _get_log_function_and_verb_by_status(status):
if is_failure(status):
verb = "failed"
log_function = "warn" if is_business_failure(status) else "error"
elif is_skip(status):
verb = "skipped"
log_function = "info"
return log_function, verb
log_function, verb = _get_log_function_and_verb_by_status(status)
log_message = (
f"Task {to.get('_id', '<not created>')} {verb}: {custom_error_message}"
f"\n{error_text}"
)
getattr(logger, log_function)(log_message)
def error_name(error, critical=False):
"""Name error handlers with corresponding error messages.
:param error:
:type error: Enum
:param critical: if error is critical, shut down and don't try to
retry or continue. Default False.
:type critical: bool
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(args[0], message=error.value)
wrapper.name = error.name
wrapper.critical = critical
return wrapper
return decorator
def _get_stacktrace_string(exc_info):
exc_type, exc_value, exc_traceback = exc_info
exc_lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
try:
message = exc_value.message
except AttributeError:
message = str(exc_value)
return message, " ".join(exc_lines) | /rpadriver-1.3.0-py3-none-any.whl/RPALibrary/deco.py | 0.424889 | 0.240496 | deco.py | pypi |
from robot.api import logger
from robot.libraries.BuiltIn import BuiltIn
class BaseStage:
"""
RPA Library base class to be used for writing Robot Framework / Python
stage definitions using TOSLibrary.
This class is inherited by Consumer and Producer. These classes contain
error handling, logging, and TOS interaction,
so users don't have to write them manually every time they write
new stages.
"""
def __init__(self):
"""Remember to call this constructor when inheriting.
See the example in the :class:`~TOSLibrary.RPALibrary.RPALibrary`
class docstring above.
:ivar self.tags: Tags of the current Robot Framework task.
:ivar self.tos: TOSLibrary instance of the current RF suite.
:ivar self.error_msg: Library-wide general error message text.
"""
super(BaseStage, self).__init__()
self.tags = BuiltIn().get_variable_value("@{TEST TAGS}")
self.tos = BuiltIn().get_library_instance("TOSLibrary")
self.consecutive_failures = 0
self.error_msg = ""
def post_action(self, to, status, *args, **kwargs):
"""Teardown steps.
Action to do for every task object after
the main action has completed succesfully or failed.
You should make the implementation yourself, if needed.
:param to: task object
:type to: dict
:param status: status returned from running ``handle_errors`` decorated
``main_action``.
:type status: str
"""
return to
def _predefined_action_on_fail(self, to):
"""Call error handler plugins here automatically."""
logger.debug("Predefined action on fail not yet implemented")
# TODO: reimplemenet error handler plugin system
return to
def action_on_fail(self, to):
"""Custom action to do when an error is encountered.
This is always called after automatic error handlers
have done their job. You can define here some custom
action or some steps that should be always run after
every error handler.
E.g. fail the robot immediately with keyword "Fail".
Note that these actions are not error handled, all exceptions
will be propagated until Robot Framework stops execution with
failure.
"""
pass
def action_on_skip(self, to):
"""Custom action to do when special skip exception
is encountered.
Note that this functionality is identical to the
action_on_fail except that this handler will be called
instead when SkipProcessing exception is raised. Use
this method to differentiate handling if needed.
"""
pass
def _increment_fail_counter(self):
self.consecutive_failures += 1
def _reset_fail_counter(self):
"""Call this when the whole workflow has completed succesfully
for one task object.
This resets the consecutive failure counter.
"""
self.consecutive_failures = 0 | /rpadriver-1.3.0-py3-none-any.whl/RPALibrary/stages/BaseStage.py | 0.826081 | 0.332554 | BaseStage.py | pypi |
import warnings
from robot.api import logger
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn
from tos.statuses import is_failure, is_skip
from RPALibrary.deco import log_number_of_created_task_objects, handle_errors
from RPALibrary.helpers import (
get_stage_from_tags,
handle_dead_selenium,
handle_signals,
take_screenshot,
)
from .BaseStage import BaseStage
class Consumer(BaseStage):
"""
Consumer base definition. Inherit your own consumer stage from this.
Every inheriting library must have a method
``main_action`` which defines the steps to be done for every
task object in the current stage. To run the actions,
call ``main_loop`` defined here (override only when necessary).
Usage example:
.. code-block:: python
from RPALibrary.stages import Consumer
class PDFMerger(Consumer):
def __init__(self):
'''
Remember to call ``super`` in the constructor.
'''
super(PDFMerger, self).__init__()
self.merger = PdfFileMerger()
@keyword
def merge_all_pdfs(self, filename):
'''
Get every valid task object from the DB
and do the action defined in ``main_action``.
Exceptions are handled and logged appropriately.
'''
count = self.main_loop(current_stage=4)
if count:
write_merged_pdf_object(filename)
def main_action(self, to):
'''Append pdf as bytes to the pdf merger object.'''
pdf_bytes = io.BytesIO(to["payload"]["pdf_letter"])
self.merger.append(pdf_bytes)
And the corresponding Robot Framework script:
.. code-block:: python
*** Settings ***
Library PDFMerger
*** Tasks ***
Manipulate PDF files
Merge All PDFs combined.pdf
"""
def __init__(self):
"""Remember to super call this constructor if your stage as
its own ``__init__``: ``super(YourStage, self).__init__()``
:ivar self.tags: Tags of the current Robot Framework task.
:ivar self.tos: TOSLibrary instance of the current RF suite.
:ivar self.error_msg: Library-wide general error message text.
:ivar self.stop_after_limit: If set, looping will stop after this many task objects.
:ivar self.should_stop_reason: If set, looping will stop.
"""
super(Consumer, self).__init__()
self.stop_after_limit = None
self.should_stop_reason = None
def main_action(self, to):
"""
The main action by which each task object is "consumed".
You should make the implementation yourself.
This will be called in the ``main_loop`` and should
contain all the steps that should be done with the
data stored in one task object.
Don't call this from Robot Framework, call ``main_loop`` instead.
:param to: task object
:type to: dict
"""
raise NotImplementedError("Make your own implementation of this method")
def pre_action(self, to):
"""Setup steps.
Action to do for every task object before the error
handled main action.
You should make the implementation yourself, if needed.
:param to: task object
:type to: dict
"""
return to
@keyword
@log_number_of_created_task_objects
def main_loop(self, *args, **kwargs):
"""
The main loop for processing task objects on a given stage.
Get task objects ready for processing and do the actions
as defined in method :meth:`~main_action`. Continue doing this as
long as valid task objects are returned from the DB. The counter
value must be returned for logger decorator consumption.
Using this method/keyword gives you automatic logging and looping
over valid task objects. You can override this method to suit
your specific needs.
Remember to explicitly call this from Robot Framework.
:param kwargs:
- **stage** (`int` or `str`) - the current stage where this is called from.
If this is not given, the stage is inferred from the Robot Framework
task level tag.
- **status** (`str`) - the status of the task objects to process
(default is 'pass')
- **change_status** (`bool`) - decide if the status should be changed after
main_action or kept as the original (default is `True`).
- **error_msg** (`str`) - Custom error message if the action here fails
(optional).
- **getter** (`callable`) - the method which is used to get the data to process.
This might be a custom input data fetcher. By default it is
``find_one_task_object_by_status_and_stage``.
Note that using a custom getter is considered experimental. Custom getter could be, e.g.
``collection.find_one_and_update``. Very important to update the object
state in the same operation- otherwise ``main_loop`` will loop infinitely!
*This functionality will be deprecated in the future*.
- **getter_args** (`dict`)- arguments that should be passed to the custom
getter. By default the arguments are ``{"statuses": status, "stages": previous_stage}``.
Note that they must be given as a dict, where the keys are the argument names, eg.
``{"filter": {"payload.age": "older"}}`` when the getter signature is
``find_one_and_update(filter=None, update=None)``.
- **amend** (`dict`) - additional MongoDB query to be used
for filtering task objects (optional).
- **main_keyword** (`str`) - custom method name to use in place of `main_action`
(optional).
- **sort_condition** (`str`) - custom condition to be used in sorting
the task objects, e.g. `sort_condition=[("_id", pymongo.DESCENDING)]`
(optional).
:returns: number of task objects processed
:rtype: int
:ivar new_status: the new status returned from the :meth:`~RPALibrary.deco.handle_errors`
decorator.
:type new_status: str
"""
def _get_stages():
current_stage = kwargs.get("current_stage")
if current_stage is None:
current_stage = get_stage_from_tags(self.tags)
else: # 0 is a valid case
current_stage = int(current_stage)
previous_stage = current_stage - 1
return current_stage, previous_stage
def _get_target_status():
return kwargs.get("status", "pass")
def _get_getter_and_args(status, previous_stage):
"""
Be careful when using a custom getter.
* Its arguments must be passed in as a dict.
* The objects state should change, otherwise there will be infinite loop!
"""
default_getter_args = {
"statuses": status,
"stages": previous_stage,
"amend": kwargs.get("amend", ""),
"sort_condition": kwargs.get("sort_condition", "")
}
getter_args = kwargs.get("getter_args", default_getter_args)
if kwargs.get("getter"):
# IMPORTANT: make sure this changes the object state!
warnings.warn("Use a custom getter at your own risk", DeprecationWarning)
getter = kwargs.get("getter")
else:
getter = self.tos.find_one_task_object_by_status_and_stage # this changes status to processing
return getter, getter_args
self.error_msg = kwargs.get("error_msg", self.error_msg) # Used inside the decorator. Could we scrap this?
current_stage, previous_stage = _get_stages()
status = _get_target_status()
getter, getter_args = _get_getter_and_args(status, previous_stage)
# TODO: clean this mess of a loop
counter = 0
while True:
to = getter(**getter_args) # Be very careful when using a custom getter
if not to:
break
counter += 1
logger.info(f"\n[ INFO ] Handling task object {to['_id']}", also_console=True)
self.tos.update_stage_object(to["_id"], current_stage)
self.tos.save_retry_metadata_if_retry(to, current_stage)
_, new_status, error = self._error_handled_pre_and_main_action(to=to, *args, **kwargs)
if kwargs.get("change_status", True):
self.tos.update_status(to["_id"], current_stage, new_status)
else:
self.tos.update_status(to["_id"], current_stage, status)
if new_status != 'pass':
to["last_error"] = error
to["status"] = new_status
self.tos.update_exceptions(to["_id"], current_stage, error)
self._increment_fail_counter()
if not kwargs.get("no_screenshots"):
take_screenshot()
to = self._predefined_action_on_fail(to)
if is_failure(new_status):
self.action_on_fail(to) # the process might be killed here
elif is_skip(new_status):
self.action_on_skip(to)
else:
self._reset_fail_counter()
to = self.post_action(to, new_status)
self.tos.set_stage_end_time(to["_id"], current_stage)
if self.stop_after_limit and counter >= self.stop_after_limit:
self.should_stop_reason = f"Already processed {counter} task objects."
if self.should_stop_reason:
logger.warn(f"Process should stop: {self.should_stop_reason}")
break
return counter
@handle_errors()
def _error_handled_pre_and_main_action(self, to=None, **kwargs):
"""Wrap the user defined main action with error handling.
Firstly `pre_action` is called and so it is included in the
error handling.
It is important that the task object ``to`` is passed
as a keyword argument to this method. It allows the decorator
to consume the task object data.
:param to: task object
:type to: dict
:param kwargs:
- **main_keyword** (`str`) - Name of the keyword that should be
used as the ``main_action``
:returns: return value of ``main_action`` and status ("pass" or "fail")
as returned from the decorator ``handle_errors``.
:rtype: `tuple`
"""
handle_signals()
# handle_dead_selenium() # FIXME: this creates problems, investigate!
to = self.pre_action(to)
main_keyword = kwargs.get("main_keyword")
if main_keyword:
return BuiltIn().run_keyword(main_keyword, to)
return self.main_action(to) | /rpadriver-1.3.0-py3-none-any.whl/RPALibrary/stages/Consumer.py | 0.787196 | 0.232049 | Consumer.py | pypi |
import atexit
from logging import getLogger
from subprocess import Popen
from typing import Optional, Tuple
from typing_extensions import Literal
from flet import flet as ft
from flet_core.page import Connection
def _connect_internal_sync(
page_name,
view: Literal["flet_app"],
host,
port,
server,
auth_token,
session_handler,
assets_dir,
upload_dir,
web_renderer,
route_url_strategy,
) -> ft.SyncLocalSocketConnection:
# For some reason this is necessary to disable getting `flet.flet` linting errors
# pylint: disable=all
return ft.__connect_internal_sync( # pylint: disable=protected-access
page_name,
view,
host,
port,
server,
auth_token,
session_handler,
assets_dir,
upload_dir,
web_renderer,
route_url_strategy,
)
class BackgroundFlet:
"""Class that manages the graphical flet subrocess and related operations"""
def __init__(self):
atexit.register(self.close_flet_view)
self.logger = getLogger(__name__)
self._conn: Optional[Connection] = None
self._fvp: Optional[Popen] = None
self._pid_file: Optional[str] = None
def _app_sync(
self,
target,
name="",
host=None,
port=0,
view: ft.AppViewer = ft.FLET_APP,
assets_dir=None,
upload_dir=None,
web_renderer="canvaskit",
route_url_strategy="path",
auth_token=None,
) -> Tuple[Connection, Popen, str]:
# Based on https://github.com/flet-dev/flet/blob/035b00104f782498d084c2fd7ee96132a542ab7f/sdk/python/packages/flet/src/flet/flet.py#L96 # noqa: E501
# We access Flet internals because it is simplest way to control the specifics
# In the future we should migrate / ask for a stable API that fits our needs
# pylint: disable=protected-access
conn = _connect_internal_sync(
page_name=name,
view=ft.FLET_APP,
host=host,
port=port,
server=None,
auth_token=auth_token,
session_handler=target,
assets_dir=assets_dir,
upload_dir=upload_dir,
web_renderer=web_renderer,
route_url_strategy=route_url_strategy,
)
self.logger.info("Connected to Flet app and handling user sessions...")
fvp, pid_file = ft.open_flet_view(
conn.page_url, assets_dir, view == ft.FLET_APP_HIDDEN
)
return conn, fvp, pid_file
def start_flet_view(self, target) -> None:
"""Starts the flet process and places the connection, view process Popen and
flet python server PID file into self
"""
self._conn, self._fvp, self._pid_file = self._app_sync(target)
def close_flet_view(self) -> None:
"""Close the currently open flet view"""
if not all([self._conn, self._fvp, self._pid_file]):
# Library was not open
return
assert self._conn is not None
assert self._fvp is not None
assert self._pid_file is not None
self._conn.close()
ft.close_flet_view(self._pid_file)
self._fvp.terminate()
self._conn = None
self._fvp = None
self._pid_file = None
def poll(self):
return self._fvp.poll() | /rpaframework_assistant-3.0.0.tar.gz/rpaframework_assistant-3.0.0/src/RPA/Assistant/background_flet.py | 0.77081 | 0.154185 | background_flet.py | pypi |
from typing import Any, Dict, List, Optional, Tuple, Union
from typing_extensions import Literal
from RPA.core.types import is_list_like # type: ignore
from RPA.Assistant.types import Element, Location, Options
def to_options(
opts: Options, default: Optional[str] = None
) -> Tuple[List[str], Optional[str]]:
"""Convert keyword argument for multiple options into
a list of strings.
Also handles default option validation.
"""
if isinstance(opts, str):
opts = [opt.strip() for opt in opts.split(",")]
elif is_list_like(opts):
opts = [str(opt) for opt in opts]
else:
raise ValueError(f"Unsupported options type: {opts}")
if not opts:
return [], None
if default is None:
default = opts[0]
if default not in opts:
raise ValueError(f"Default '{default}' is not in available options")
return opts, default
def optional_str(val: Any) -> Optional[str]:
"""Convert value to string, but keep NoneType"""
return str(val) if val is not None else val
def optional_int(val: Any) -> Optional[int]:
"""Convert value to int, but keep NoneType"""
return int(val) if val is not None else val
def int_or_auto(val: Any) -> Union[int, str]:
"""Convert value to int or 'AUTO' literal"""
if isinstance(val, int):
return val
try:
return int(val)
except ValueError:
pass
height = str(val).strip().upper()
if height == "AUTO":
return height
raise ValueError("Value not integer or AUTO")
def is_input(element: Element) -> bool:
"""Check if an element is an input"""
return element["type"].startswith("input-")
def is_submit(element: Element) -> bool:
"""Check if an element is a submit button."""
return element["type"] == "submit"
def location_to_absolute(
location: Union[Location, Tuple[int, int], None],
parent_width: float,
parent_height: float,
element_width: Optional[float],
element_height: Optional[float],
) -> Dict[Literal["left", "top", "bottom", "right"], float]:
"""Calculates and returns absolute version of elements relative position as left or
right and bottom or top keys in dictionary.
"""
if isinstance(location, tuple):
return {"left": location[0], "top": location[1]}
if location in [
Location.TopCenter,
Location.BottomCenter,
Location.CenterLeft,
Location.CenterRight,
Location.Center,
]:
if element_height is None or element_width is None:
raise ValueError(
"Cannot determine centered position without static width and height"
)
half_height = (parent_height / 2) - (element_height / 2)
half_width = (parent_width / 2) - (element_width / 2)
else:
half_height, half_width = -1, -1
coordinates: Dict[
Location, Dict[Literal["left", "top", "bottom", "right"], float]
] = {
Location.TopLeft: {"left": 0, "top": 0},
Location.TopCenter: {"left": half_width, "top": 0},
Location.TopRight: {"right": 0, "top": 0},
Location.CenterLeft: {"left": 0, "top": half_height},
Location.Center: {"left": half_width, "top": half_height},
Location.CenterRight: {"right": 0, "top": half_width},
Location.BottomLeft: {"left": 0, "bottom": 0},
Location.BottomCenter: {"left": half_width, "bottom": 0},
Location.BottomRight: {"right": 0, "bottom": 0},
}
if isinstance(location, Location):
return coordinates[location]
else:
raise ValueError(f"Invalid location {location}") | /rpaframework_assistant-3.0.0.tar.gz/rpaframework_assistant-3.0.0/src/RPA/Assistant/utils.py | 0.908139 | 0.397821 | utils.py | pypi |
import logging
import types
from typing import Any, Callable, Dict, Optional, Union
from flet_core import ControlEvent
from robot.errors import RobotError
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
from robot.output.logger import LOGGER
class CallbackRunner:
"""provides helper functionality for running Robot and Python callbacks in
RPA.Assistant."""
def __init__(self, client) -> None:
self.logger = logging.getLogger(__name__)
self.validation_errors: Dict[str, Optional[str]] = {}
self._client = client
def _python_callback(
self, function: Callable[[Any], None], *args, **kwargs
) -> Callable[[], None]:
"""wrapper code that is used to add wrapping for user functions when binding
them to be run by buttons
"""
def func_wrapper() -> None:
return self._run_python_callback(function, *args, **kwargs)
return func_wrapper
def python_validation(
self, element_name: str, function: Callable[[Any], Optional[str]]
) -> Callable[[ControlEvent], None]:
"""wrapper code that is used to add wrapping for user functions when binding
them to be run on validations buttons
"""
def validate(e: ControlEvent) -> None:
error = self._run_python_callback(function, e.data)
casted_error = str(error) if error else None
e.control.error_text = casted_error
self._client.flet_update()
self.validation_errors[element_name] = casted_error
return validate
def _run_python_callback(self, function: Callable, *args, **kwargs):
try:
return function(*args, **kwargs)
# This can be anything since it comes from the user function, we don't
# want to let the user function crash the UI
except Exception as err: # pylint: disable=broad-except
self.logger.error(f"Error calling Python function {function.__name__}")
self.logger.error(err)
finally:
self._client.unlock_elements()
self._client.flet_update()
return None
def _robot_callback(self, kw_name: str, *args, **kwargs) -> Callable[[], None]:
"""wrapper code that is used to add wrapping for user functions when binding
them to be run by buttons
"""
def func_wrapper() -> None:
return self._run_robot_callback(kw_name, *args, **kwargs)
return func_wrapper
def robot_validation(
self, element_name: str, kw_name: str
) -> Callable[[ControlEvent], None]:
"""wrapper code that is used to add wrapping for user functions when binding
them to be run on validation
"""
def validate(e: ControlEvent) -> None:
def _nothing(*args, **kwargs): # pylint: disable=unused-argument
pass
logging_methods = (LOGGER.start_keyword, LOGGER.end_keyword)
try:
# Disable logging by monkey patching the robot logger
LOGGER.start_keyword = types.MethodType(_nothing, LOGGER)
LOGGER.end_keyword = types.MethodType(_nothing, LOGGER)
error = self._run_robot_callback(kw_name, e.control.value)
e.control.error_text = error
self._client.flet_update()
self.validation_errors[element_name] = error
finally:
LOGGER.start_keyword, LOGGER.end_keyword = logging_methods
return validate
def _run_robot_callback(self, kw_name: str, *args, **kwargs):
try:
return BuiltIn().run_keyword(kw_name, *args, **kwargs)
except RobotNotRunningError:
self.logger.error(
f"Robot Framework not running so cannot call keyword {kw_name}"
)
except RobotError as e:
self.logger.error(f"Error calling robot keyword {kw_name}")
self.logger.error(e)
# This can be anything since it comes from the user function, we don't
# want to let the user function crash the UI
except Exception as err: # pylint: disable=broad-except
self.logger.error(f"Unexpected error running robot keyword {kw_name}")
self.logger.error(err)
finally:
self._client.unlock_elements()
self._client.flet_update()
return None
def queue_fn_or_kw(self, function: Union[Callable, str], *args, **kwargs):
"""Check if function is a Python function or a Robot Keyword, and schedule it
for execution appropriately.
"""
if self._client.pending_operation:
self.logger.error("Can't have more than one pending operation.")
return
self._client.lock_elements()
self._client.flet_update()
if isinstance(function, Callable):
self._client.pending_operation = self._python_callback(
function, *args, **kwargs
)
else:
self._client.pending_operation = self._robot_callback(
function, *args, **kwargs
) | /rpaframework_assistant-3.0.0.tar.gz/rpaframework_assistant-3.0.0/src/RPA/Assistant/callback_runner.py | 0.850173 | 0.239572 | callback_runner.py | pypi |
class BoundingBox:
def __init__(self, width, height, left, top):
self._width = width
self._height = height
self._left = left
self._top = top
def __repr__(self):
return "width: {}, height: {}, left: {}, top: {}".format(
self._width, self._height, self._left, self._top
)
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@property
def left(self):
return self._left
@property
def top(self):
return self._top
class Polygon:
def __init__(self, x, y):
self._x = x
self._y = y
def __repr__(self):
return "x: {}, y: {}".format(self._x, self._y)
@property
def x(self):
return self._x
@property
def y(self):
return self._y
class Geometry:
def __init__(self, geometry):
boundingBox = geometry["BoundingBox"]
polygon = geometry["Polygon"]
bb = BoundingBox(
boundingBox["Width"],
boundingBox["Height"],
boundingBox["Left"],
boundingBox["Top"],
)
pgs = []
for pg in polygon:
pgs.append(Polygon(pg["X"], pg["Y"]))
self._boundingBox = bb
self._polygon = pgs
def __repr__(self):
s = "BoundingBox: {}".format(str(self._boundingBox))
return s
@property
def boundingBox(self):
return self._boundingBox
@property
def polygon(self):
return self._polygon
class Word:
def __init__(self, block, blockMap):
self._block = block
self._confidence = block["Confidence"]
self._geometry = Geometry(block["Geometry"])
self._id = block["Id"]
self._text = ""
if block["Text"]:
self._text = block["Text"]
def __repr__(self):
return self._text
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def text(self):
return self._text
@property
def block(self):
return self._block
class Line:
def __init__(self, block, blockMap):
self._block = block
self._confidence = block["Confidence"]
self._geometry = Geometry(block["Geometry"])
self._id = block["Id"]
self._text = ""
if block["Text"]:
self._text = block["Text"]
self._words = []
if "Relationships" in block and block["Relationships"]:
for rs in block["Relationships"]:
if rs["Type"] == "CHILD":
for cid in rs["Ids"]:
if blockMap[cid]["BlockType"] == "WORD":
self._words.append(Word(blockMap[cid], blockMap))
def __repr__(self):
return self._text
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def words(self):
return self._words
@property
def text(self):
return self._text
@property
def block(self):
return self._block
class SelectionElement:
def __init__(self, block, blockMap):
self._confidence = block["Confidence"]
self._geometry = Geometry(block["Geometry"])
self._id = block["Id"]
self._selectionStatus = block["SelectionStatus"]
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def selectionStatus(self):
return self._selectionStatus
class FieldKey:
def __init__(self, block, children, blockMap):
self._block = block
self._confidence = block["Confidence"]
self._geometry = Geometry(block["Geometry"])
self._id = block["Id"]
self._text = ""
self._content = []
t = []
for eid in children:
wb = blockMap[eid]
if wb["BlockType"] == "WORD":
w = Word(wb, blockMap)
self._content.append(w)
t.append(w.text)
if t:
self._text = " ".join(t)
def __repr__(self):
return self._text
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def content(self):
return self._content
@property
def text(self):
return self._text
@property
def block(self):
return self._block
class FieldValue:
def __init__(self, block, children, blockMap):
self._block = block
self._confidence = block["Confidence"]
self._geometry = Geometry(block["Geometry"])
self._id = block["Id"]
self._text = ""
self._content = []
t = []
for eid in children:
wb = blockMap[eid]
if wb["BlockType"] == "WORD":
w = Word(wb, blockMap)
self._content.append(w)
t.append(w.text)
elif wb["BlockType"] == "SELECTION_ELEMENT":
se = SelectionElement(wb, blockMap)
self._content.append(se)
self._text = se.selectionStatus
if t:
self._text = " ".join(t)
def __repr__(self):
return self._text
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def content(self):
return self._content
@property
def text(self):
return self._text
@property
def block(self):
return self._block
class Field:
def __init__(self, block, blockMap):
self._key = None
self._value = None
for item in block["Relationships"]:
if item["Type"] == "CHILD":
self._key = FieldKey(block, item["Ids"], blockMap)
elif item["Type"] == "VALUE":
for eid in item["Ids"]:
vkvs = blockMap[eid]
if "VALUE" in vkvs["EntityTypes"]:
if "Relationships" in vkvs:
for vitem in vkvs["Relationships"]:
if vitem["Type"] == "CHILD":
self._value = FieldValue(
vkvs, vitem["Ids"], blockMap
)
def __repr__(self):
return str({self._key: self._value})
@property
def key(self):
return self._key
@property
def value(self):
return self._value
class Form:
def __init__(self):
self._fields = []
self._fieldsMap = {}
def addField(self, field):
self._fields.append(field)
self._fieldsMap[field.key.text] = field
def __repr__(self):
return str(self._fields)
@property
def fields(self):
return self._fields
def getFieldByKey(self, key):
field = None
if key in self._fieldsMap:
field = self._fieldsMap[key]
return field
def searchFieldsByKey(self, key):
searchKey = key.lower()
results = []
for field in self._fields:
if field.key and searchKey in field.key.text.lower():
results.append(field)
return results
class Cell:
def __init__(self, block, blockMap):
self._block = block
self._confidence = block["Confidence"]
self._rowIndex = block["RowIndex"]
self._columnIndex = block["ColumnIndex"]
self._rowSpan = block["RowSpan"]
self._columnSpan = block["ColumnSpan"]
self._geometry = Geometry(block["Geometry"])
self._id = block["Id"]
self._content = []
self._text = ""
if "Relationships" in block and block["Relationships"]:
for rs in block["Relationships"]:
if rs["Type"] == "CHILD":
for cid in rs["Ids"]:
blockType = blockMap[cid]["BlockType"]
if blockType == "WORD":
w = Word(blockMap[cid], blockMap)
self._content.append(w)
self._text = self._text + w.text + " "
elif blockType == "SELECTION_ELEMENT":
se = SelectionElement(blockMap[cid], blockMap)
self._content.append(se)
self._text = self._text + se.selectionStatus + ", "
def __repr__(self):
return self._text
@property
def confidence(self):
return self._confidence
@property
def rowIndex(self):
return self._rowIndex
@property
def columnIndex(self):
return self._columnIndex
@property
def rowSpan(self):
return self._rowSpan
@property
def columnSpan(self):
return self._columnSpan
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def content(self):
return self._content
@property
def text(self):
return self._text
@property
def block(self):
return self._block
class Row:
def __init__(self):
self._cells = []
def __repr__(self):
return str(self._cells)
@property
def cells(self):
return self._cells
class Table:
def __init__(self, block, blockMap):
self._block = block
self._confidence = block["Confidence"]
self._geometry = Geometry(block["Geometry"])
self._id = block["Id"]
self._rows = []
ri = 1
row = Row()
cell = None
if "Relationships" in block and block["Relationships"]:
for rs in block["Relationships"]:
if rs["Type"] == "CHILD":
for cid in rs["Ids"]:
cell = Cell(blockMap[cid], blockMap)
if cell.rowIndex > ri:
self._rows.append(row)
row = Row()
ri = cell.rowIndex
row.cells.append(cell)
if row and row.cells:
self._rows.append(row)
def __repr__(self):
return str(self._rows)
@property
def confidence(self):
return self._confidence
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
@property
def rows(self):
return self._rows
@property
def block(self):
return self._block
class Page:
def __init__(self, blocks, blockMap):
self._blocks = blocks
self._text = ""
self._lines = []
self._form = Form()
self._tables = []
self._content = []
self._parse(blockMap)
def __repr__(self):
return str(self._content)
def _parse(self, blockMap):
for item in self._blocks:
if item["BlockType"] == "PAGE":
self._geometry = Geometry(item["Geometry"])
self._id = item["Id"]
elif item["BlockType"] == "LINE":
line = Line(item, blockMap)
self._lines.append(line)
self._content.append(line)
self._text = self._text + line.text + "\n"
elif item["BlockType"] == "TABLE":
t = Table(item, blockMap)
self._tables.append(t)
self._content.append(t)
elif item["BlockType"] == "KEY_VALUE_SET":
if "KEY" in item["EntityTypes"]:
f = Field(item, blockMap)
if f.key:
self._form.addField(f)
self._content.append(f)
# TODO. report error if key can't be found
# print(
# "WARNING: Detected K/V where key does not have content.
# Excluding key from output."
# )
# print(f)
# print(item)
def getLinesInReadingOrder(self):
columns = []
lines = []
for item in self._lines:
column_found = False
for index, column in enumerate(columns):
bbox_left = item.geometry.boundingBox.left
bbox_right = (
item.geometry.boundingBox.left + item.geometry.boundingBox.width
)
bbox_centre = (
item.geometry.boundingBox.left + item.geometry.boundingBox.width / 2
)
column_centre = column["left"] + column["right"] / 2
if (bbox_centre > column["left"] and bbox_centre < column["right"]) or (
column_centre > bbox_left and column_centre < bbox_right
):
# Bbox appears inside the column
lines.append([index, item.text])
column_found = True
break
if not column_found:
columns.append(
{
"left": item.geometry.boundingBox.left,
"right": item.geometry.boundingBox.left
+ item.geometry.boundingBox.width,
}
)
lines.append([len(columns) - 1, item.text])
lines.sort(key=lambda x: x[0])
return lines
def getTextInReadingOrder(self):
lines = self.getLinesInReadingOrder()
text = ""
for line in lines:
text = text + line[1] + "\n"
return text
@property
def blocks(self):
return self._blocks
@property
def text(self):
return self._text
@property
def lines(self):
return self._lines
@property
def form(self):
return self._form
@property
def tables(self):
return self._tables
@property
def content(self):
return self._content
@property
def geometry(self):
return self._geometry
@property
def id(self):
return self._id
class TextractDocument:
def __init__(self, responsePages):
if not isinstance(responsePages, list):
rps = []
rps.append(responsePages)
responsePages = rps
self._responsePages = responsePages
self._pages = []
self._parse()
def __repr__(self):
return str(self._pages)
def _parseDocumentPagesAndBlockMap(self):
blockMap = {}
documentPages = []
documentPage = None
for page in self._responsePages:
for block in page["Blocks"]:
if "BlockType" in block and "Id" in block:
blockMap[block["Id"]] = block
if block["BlockType"] == "PAGE":
if documentPage:
documentPages.append({"Blocks": documentPage})
documentPage = []
documentPage.append(block)
else:
documentPage.append(block)
if documentPage:
documentPages.append({"Blocks": documentPage})
return documentPages, blockMap
def _parse(self):
(
self._responseDocumentPages,
self._blockMap,
) = self._parseDocumentPagesAndBlockMap()
for documentPage in self._responseDocumentPages:
page = Page(documentPage["Blocks"], self._blockMap)
self._pages.append(page)
@property
def blocks(self):
return self._responsePages
@property
def pageBlocks(self):
return self._responseDocumentPages
@property
def pages(self):
return self._pages
def getBlockById(self, blockId):
block = None
if self._blockMap and blockId in self._blockMap:
block = self._blockMap[blockId]
return block | /rpaframework_aws-5.3.0.tar.gz/rpaframework_aws-5.3.0/src/RPA/Cloud/AWS/textract.py | 0.91695 | 0.317929 | textract.py | pypi |
from functools import wraps
from importlib import util
import inspect
import os
from typing import Any
IPYTHON_AVAILABLE = False
ipython_module = util.find_spec("IPython")
if ipython_module:
# pylint: disable=C0415
from IPython.display import ( # noqa
Audio,
display,
FileLink,
FileLinks,
Image,
JSON,
Markdown,
Video,
)
IPYTHON_AVAILABLE = True
def _get_caller_prefix(calframe):
keyword_name = (
calframe[1][3] if calframe[1][3] not in ["<module>", "<lambda>"] else None
)
if keyword_name:
keyword_name = keyword_name.replace("_", " ").title()
return f"Output from **{keyword_name}**"
return ""
def print_precheck(f):
@wraps(f)
def wrapper(*args, **kwargs):
if not IPYTHON_AVAILABLE:
return None
output_level = os.getenv("RPA_NOTEBOOK_OUTPUT_LEVEL", "1")
if output_level == "0":
return None
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
prefix = _get_caller_prefix(calframe)
if prefix != "":
display(Markdown(prefix))
return f(*args, **kwargs)
return wrapper
@print_precheck
def notebook_print(arg=None, **kwargs) -> Any:
"""Display IPython Markdown object in the notebook
Valid parameters are `text`, `image`, `link` or `table`.
:param text: string to output (can contain markdown)
:param image: path to the image file
:param link: path to the link
:param table: `RPA.Table` object to print
"""
if arg and "text" in kwargs.keys():
kwargs["text"] = f"{arg} {kwargs['text']}"
else:
kwargs["text"] = str(arg)
output = _get_markdown(**kwargs)
if output:
display(Markdown(output))
@print_precheck
def notebook_file(filepath):
"""Display IPython FileLink object in the notebook
:param filepath: location of the file
"""
if filepath:
display(FileLink(filepath))
@print_precheck
def notebook_dir(directory, recursive=False):
"""Display IPython FileLinks object in the notebook
:param directory: location of the directory
:param recursive: if all subdirectories should be shown also, defaults to False
"""
if directory:
display(FileLinks(directory, recursive=recursive))
@print_precheck
def notebook_table(table: Any, count: int = 20, columns=None):
"""Display RPA.Table or RPA.Table shaped data as IPython Markdown object in the notebook
:param table: `RPA.Table` object to print
:param count: How many rows of table to print
:param columns: Names / headers of the table columns
:param index: List of indices for table rows
"""
# pylint: disable=C0415,E0611
from RPA.Tables import Table, Tables # noqa
table = Table(table, columns)
if count:
table = Tables().table_head(table, count=count)
output = _get_table_output(table)
if output:
display(Markdown(output))
@print_precheck
def notebook_image(image):
"""Display IPython Image object in the notebook
:param image: path to the image file
"""
if image:
display(Image(image))
@print_precheck
def notebook_video(video):
"""Display IPython Video object in the notebook
:param video: path to the video file
"""
if video:
display(Video(video))
@print_precheck
def notebook_audio(audio):
"""Display IPython Audio object in the notebook
:param audio: path to the audio file
"""
if audio:
display(Audio(filename=audio))
@print_precheck
def notebook_json(json_object):
"""Display IPython JSON object in the notebook
:param json_object: item to show
"""
if json_object:
display(JSON(json_object))
def _get_table_output(table):
# pylint: disable=C0415,E0611
from RPA.Tables import Tables, Table # noqa
output = ""
try:
if isinstance(table, Table):
output = "<table class='rpafw-notebook-table'>"
header = Tables().table_head(table, count=1)
for row in header:
output += "<tr>"
for h, _ in row.items():
output += f"<th>{h}</th>"
output += "</tr>"
for row in table:
output += "<tr>"
for _, cell in row.items():
output += f"<td>{cell}</td>"
output += "</tr>"
output += "</table><br>"
except ImportError:
pass
return None if output == "" else output
def _get_markdown(**kwargs):
output = ""
for key, val in kwargs.items():
if key == "text":
output += f"<span class='rpafw-notebook-text'>{val}</span><br>"
if key == "image":
output += f"<img class='rpafw-notebook-image' src='{val}'><br>"
if key == "link":
link_text = (val[:75] + "..") if len(val) > 75 else val
output += f"<a class='rpafw-notebook-link' href='{val}'>{link_text}</a><br>"
if key == "table":
output += _get_table_output(val)
return None if output == "" else output | /rpaframework_core-11.0.6.tar.gz/rpaframework_core-11.0.6/src/RPA/core/notebook.py | 0.58948 | 0.173603 | notebook.py | pypi |
import importlib
import code
import logging
import os
import string
import sys
import time
import unicodedata
from typing import Any, Optional
# Sentinel value for undefined argument
UNDEFINED = object()
def delay(sleeptime: float = 0.0):
"""Delay execution for given amount of seconds.
:param sleeptime: seconds as float, defaults to 0
"""
if delay is None:
return
sleeptime = float(sleeptime)
if sleeptime > 0:
logging.debug("Sleeping for %f second(s)", sleeptime)
time.sleep(sleeptime)
def clean_filename(filename: str, replace: str = " ") -> str:
"""Clean filename to valid format which can be used file operations.
:param filename: name to be cleaned
:param replace: characters to replace with underscore, defaults to " "
:return: valid filename
"""
valid_characters = "-_.()" + string.ascii_letters + string.digits
for char in replace:
filename = filename.replace(char, "_")
clean = unicodedata.normalize("NFKD", filename)
clean = clean.encode("ASCII", "ignore").decode()
clean = "".join(char for char in filename if char in valid_characters)
return clean
def required_env(name: str, default: Any = UNDEFINED) -> str:
"""Load required environment variable.
:param name: Name of environment variable
:param default: Value to use if variable is undefined.
If not given and variable is undefined, raises KeyError.
"""
val = os.getenv(name, default)
if val is UNDEFINED:
raise KeyError(f"Missing required environment variable: {name}")
return val
def required_param(param_name: Any = None, method_name: str = None):
"""Check that required parameter is not None"""
if not isinstance(param_name, list):
param_name = [param_name]
if any(p is None for p in param_name):
raise KeyError("Required parameter(s) missing for kw: %s" % method_name)
def import_by_name(name: str, caller: str = None) -> Any:
"""Import module (or attribute) by name.
:param name: Import path, e.g. RPA.Robocorp.WorkItems.RobocorpAdapter
"""
name = str(name)
# Attempt import as path module
try:
return importlib.import_module(name)
except ImportError:
pass
# Attempt import from calling file
if caller is not None:
try:
module = importlib.import_module(caller)
return getattr(module, name)
except AttributeError:
pass
# Attempt import as path to attribute inside module
if "." in name:
try:
path, attr = name.rsplit(".", 1)
module = importlib.import_module(path)
return getattr(module, attr)
except (AttributeError, ImportError):
pass
raise ValueError(f"No module/attribute with name: {name}")
def interact(expression: Any = None, local: Optional[dict] = None):
"""Interrupts the execution with an interactive shell on `expression`."""
if expression is not None and not expression:
return
sys.stdin, bkp_stdin = sys.__stdin__, sys.stdin
sys.stdout, bkp_stdout = sys.__stdout__, sys.stdout
sys.stderr, bkp_stderr = sys.__stderr__, sys.stderr
try:
code.interact(local=local or {**globals(), **locals()})
finally:
sys.stdin = bkp_stdin
sys.stdout = bkp_stdout
sys.stderr = bkp_stderr | /rpaframework_core-11.0.6.tar.gz/rpaframework_core-11.0.6/src/RPA/core/helpers.py | 0.53777 | 0.21893 | helpers.py | pypi |
from dataclasses import dataclass, astuple
from typing import Any, Optional, Union, Sequence, Tuple
def to_point(obj: Any) -> Optional["Point"]:
"""Convert `obj` to instance of Point."""
if obj is None or isinstance(obj, Point):
return obj
if isinstance(obj, str):
obj = obj.split(",")
return Point(*(int(i) for i in obj))
def to_region(obj: Any) -> Optional["Region"]:
"""Convert `obj` to instance of Region."""
if obj is None or isinstance(obj, Region):
return obj
if isinstance(obj, str):
obj = obj.split(",")
return Region(*(int(i) for i in obj))
@dataclass
class Undefined:
"""Internal placeholder for generic geometry."""
def __str__(self):
return "undefined"
@dataclass(order=True)
class Point:
"""Container for a 2D point."""
x: int
y: int
def __post_init__(self):
self.x = int(self.x)
self.y = int(self.y)
def __str__(self):
return f"point:{self.x},{self.y}"
def __iter__(self):
return iter(self.as_tuple())
def as_tuple(self) -> Tuple:
return astuple(self)
def move(self, x: int, y: int) -> "Point":
"""Move the point relativce to the current position,
and return the resulting copy.
"""
return Point(self.x + int(x), self.y + int(y))
@dataclass(order=True)
class Region:
"""Container for a 2D rectangular region."""
left: int
top: int
right: int
bottom: int
def __post_init__(self):
self.left = int(self.left)
self.top = int(self.top)
self.right = int(self.right)
self.bottom = int(self.bottom)
if self.left >= self.right:
raise ValueError("Invalid width")
if self.top >= self.bottom:
raise ValueError("Invalid height")
def __str__(self):
return f"region:{self.left},{self.top},{self.right},{self.bottom}"
def __iter__(self):
return iter(self.as_tuple())
@classmethod
def from_size(cls, left: int, top: int, width: int, height: int) -> "Region":
return cls(left, top, left + width, top + height)
@classmethod
def merge(cls, regions: Sequence["Region"]) -> "Region":
left = min(region.left for region in regions)
top = min(region.top for region in regions)
right = max(region.right for region in regions)
bottom = max(region.bottom for region in regions)
return cls(left, top, right, bottom)
@property
def width(self) -> int:
return self.right - self.left
@width.setter
def width(self, value: int):
diff = int(value) - self.width
if self.width + diff <= 0:
raise ValueError("Invalid width")
self.left -= int(diff / 2)
self.right += int(diff / 2)
@property
def height(self) -> int:
return self.bottom - self.top
@height.setter
def height(self, value: int):
diff = int(value) - self.height
if self.height + diff <= 0:
raise ValueError("Invalid height")
self.top -= int(diff / 2)
self.bottom += int(diff / 2)
@property
def area(self) -> int:
return self.width * self.height
@property
def center(self) -> Point:
return Point(
x=int((self.left + self.right) / 2), y=int((self.top + self.bottom) / 2)
)
def as_tuple(self) -> Tuple:
return astuple(self)
def scale(self, scaling_factor: float) -> "Region":
"""Scale all coordinate values with a given factor.
Used for instance when regions are from a monitor with
different pixel scaling.
"""
left = int(self.left * scaling_factor)
top = int(self.top * scaling_factor)
right = int(self.right * scaling_factor)
bottom = int(self.bottom * scaling_factor)
return Region(left, top, right, bottom)
def resize(self, *sizes: int) -> "Region":
"""Grow or shrink the region a given amount of pixels,
and return the resulting copy.
The method supports different ways to resize:
resize(a): a = all edges
resize(a, b): a = left/right, b = top/bottom
resize(a, b, c): a = left, b = top/bottom, c = right
resize(a, b, c, d): a = left, b = top, c = right, d = bottom
"""
count = len(sizes)
if count == 1:
left = top = right = bottom = sizes[0]
elif count == 2:
left = right = sizes[0]
top = bottom = sizes[1]
elif count == 3:
left = sizes[0]
top = bottom = sizes[1]
right = sizes[2]
elif count == 4:
left, top, right, bottom = sizes
else:
raise ValueError(f"Too many resize arguments: {count}")
left = self.left - int(left)
top = self.top - int(top)
right = self.right + int(right)
bottom = self.bottom + int(bottom)
return Region(left, top, right, bottom)
def move(self, left: int, top: int) -> "Region":
"""Move the region relative to current position,
and return the resulting copy.
"""
left = self.left + int(left)
top = self.top + int(top)
right = left + self.width
bottom = top + self.height
return Region(left, top, right, bottom)
def contains(self, element: Union[Point, "Region"]) -> bool:
"""Check if a point or region is inside this region."""
if isinstance(element, Point):
return (self.left <= element.x <= self.right) and (
self.top <= element.y <= self.bottom
)
elif isinstance(element, Region):
return (
element.left >= self.left
and element.top >= self.top
and element.right <= self.right
and element.bottom <= self.bottom
)
else:
raise NotImplementedError("contains() only supports Points and Regions")
def clamp(self, container: "Region") -> "Region":
"""Limit the region to the maximum dimensions defined by the container,
and return the resulting copy.
"""
left = max(container.left, min(self.left, container.right))
top = max(container.top, min(self.top, container.bottom))
right = min(container.right, max(self.right, container.left))
bottom = min(container.bottom, max(self.bottom, container.top))
return Region(left, top, right, bottom) | /rpaframework_core-11.0.6.tar.gz/rpaframework_core-11.0.6/src/RPA/core/geometry.py | 0.973215 | 0.388299 | geometry.py | pypi |
from pathlib import Path
from typing import Dict, List, Optional
from RPA.core.vendor.deco import keyword as method
from RPA.core.windows.context import WindowsContext
from RPA.core.windows.helpers import IS_WINDOWS
from RPA.core.windows.locators import Locator, MatchObject, WindowsElement
if IS_WINDOWS:
import uiautomation as auto
from uiautomation.uiautomation import Control
StructureType = Dict[int, List[WindowsElement]]
class ElementMethods(WindowsContext):
"""Keywords for listing Windows GUI elements."""
@staticmethod
def _add_child_to_tree(
control: "Control",
structure: StructureType,
*,
locator: Optional[str],
depth: int,
path: str,
):
# Adds current control child as element in the flattened tree structure.
if locator and path:
control_locator = f"{locator} > path:{path}"
elif path:
control_locator = f"path:{path}"
else:
control_locator = locator
control.robocorp_click_offset = None
element = WindowsElement(control, control_locator)
structure.setdefault(depth, []).append(element)
@method
def print_tree(
self,
locator: Optional[Locator] = None,
max_depth: int = 8,
capture_image_folder: Optional[str] = None,
log_as_warnings: Optional[bool] = False,
return_structure: bool = False,
) -> Optional[StructureType]:
# Cache how many brothers are in total given a child. (to know child position)
brothers_count: Dict[int, int] = {}
# Current path in the tree as children positions. (to compute the path locator)
children_stack: List[int] = [-1] * (max_depth + 1)
# Flattened tree of elements by depth level (to return the object if wanted).
structure: StructureType = {}
def get_children(ctrl: Control) -> List[Control]:
children = ctrl.GetChildren()
children_count = len(children)
for child in children:
brothers_count[hash(child)] = children_count
return children
target_elem = self.ctx.get_element(locator)
locator: Optional[str] = WindowsElement.norm_locator(target_elem)
root_ctrl = target_elem.item
brothers_count[hash(root_ctrl)] = 1 # the root is always singular here
image_idx = 1
image_folder: Optional[Path] = None
if capture_image_folder:
image_folder = Path(capture_image_folder).expanduser().resolve()
image_folder.mkdir(parents=True, exist_ok=True)
control_log = {
None: self.logger.debug,
False: self.logger.info,
True: self.logger.warning,
}[log_as_warnings]
for control, depth, children_remaining in auto.WalkTree(
root_ctrl,
getChildren=get_children,
includeTop=True,
maxDepth=max_depth,
):
control_str = str(control)
if image_folder:
element = WindowsElement(control, locator)
capture_filename = f"{control.ControlType}_{image_idx}.png"
image_path = image_folder / capture_filename
try:
self.ctx.screenshot(element, image_path)
except Exception as exc: # pylint: disable=broad-except
self.logger.warning(
"Couldn't capture into %r due to: %s", image_path, exc
)
else:
control_str += f" Image: {capture_filename}"
image_idx += 1
space = " " * depth * 4
child_pos = brothers_count[hash(control)] - children_remaining
children_stack[depth] = child_pos
path = MatchObject.PATH_SEP.join(
str(pos) for pos in children_stack[1 : depth + 1]
)
control_log(f"{space}{depth}-{child_pos}. {control_str} Path: {path}")
if return_structure:
self._add_child_to_tree(
control,
structure,
locator=locator,
depth=depth,
path=path,
)
return structure if return_structure else None | /rpaframework_core-11.0.6.tar.gz/rpaframework_core-11.0.6/src/RPA/core/windows/elements.py | 0.882561 | 0.302687 | elements.py | pypi |
from pathlib import Path
from typing import Dict, List, Optional, Union
from RPA.core.windows import WindowsElements
from RPA.core.windows.helpers import IS_WINDOWS
from RPA.core.windows.locators import MatchObject, WindowsElement
from RPA.core.windows.window import WindowMethods
if IS_WINDOWS:
import uiautomation as auto
from uiautomation import Control # pylint: disable=unused-import
RecordElement = Dict[str, Optional[Union[float, str, "Control", List[str]]]]
NOT_AVAILABLE = "N/A"
class ElementInspector:
"""Element locator inspector"""
MATCH_PRIORITY = ["automation_id", "name"] # element matching priority
def __init__(self):
# Lazily loaded with verbose mode on for printing the tree and returning the
# structure.
self._windows_elements: Optional[WindowsElements] = None
@property
def windows_elements(self) -> WindowsElements:
"""The minimal core flavor of the Windows library."""
if not self._windows_elements:
self._windows_elements = WindowsElements()
return self._windows_elements
def inspect_element(
self,
recording: List[RecordElement],
verbose: bool = False,
) -> None:
"""Inspect Windows element under mouse pointer.
:param recording: Store the dict records under this list.
:param verbose: Show exhaustive locators if `True`, otherwise just simple ones.
Switching this on will make recording slower as it is refreshing the
element tree with each click in order to provide their path strategy as
well.
"""
# TODO(cmin764): Support Python syntax as well. (currently just RF keywords)
with auto.UIAutomationInitializerInThread(debug=False):
control = auto.ControlFromCursor()
parent_control = control.GetParentControl()
exec_path = ""
try:
top_level_control = control.GetTopLevelControl()
except AttributeError:
top_level_control = None
top_level_handle = NOT_AVAILABLE
else:
top_level_handle = top_level_control.NativeWindowHandle
try:
exec_path = WindowMethods.get_fullpath(top_level_control.ProcessId)
except Exception: # pylint: disable=broad-except
pass
top_properties = self._get_element_key_properties(
top_level_control, verbose=verbose
)
parent_properties = self._get_element_key_properties(
parent_control, verbose=verbose
)
child_properties = self._get_element_key_properties(
control, top_level_control=top_level_control, verbose=verbose
)
top_locator = " and ".join(top_properties) or NOT_AVAILABLE
parent_locator = " and ".join(parent_properties) or NOT_AVAILABLE
child_locator = " and ".join(child_properties) or NOT_AVAILABLE
control_locator = child_locator
if parent_locator != NOT_AVAILABLE and not (
"name:" in child_locator or "id:" in child_locator
):
control_locator = f"{parent_locator} > {child_locator}"
recording.append(
{
"type": "locator",
"exec_path": exec_path,
"exec": Path(exec_path).name,
"top": top_locator,
"top_handle": top_level_handle,
"x": top_level_control,
"locator": control_locator,
"top_props": top_properties,
"parent_props": parent_properties,
"props": child_properties,
"name": parent_control.Name if parent_control else None,
"control": parent_control,
}
)
@staticmethod
def _get_locators(*, regex_limit: int, **kwargs) -> List[str]:
locators = []
name = kwargs["name"]
if name:
name_property = "name:"
if len(name) > regex_limit:
name_property = "regex:"
name = name[:regex_limit].strip()
if " " in name:
q = MatchObject.QUOTE
name = f"{q}{name}{q}"
locators.append(f"{name_property}{name}")
automation_id, control_type, class_name = (
kwargs["automation_id"],
kwargs["control_type"],
kwargs["class_name"],
)
# NOTE(cmin764): Sometimes, the automation ID is a randomly generated number,
# different with each run. (therefore you can't rely on it in the locator)
if automation_id and not str(automation_id).isnumeric():
locators.append(f"id:{automation_id}")
if control_type:
locators.append(f"type:{control_type}")
if class_name:
locators.append(f"class:{class_name}")
return locators
@classmethod
def _filter_elements(
cls,
elements: List[WindowsElement],
*,
control_type: str,
class_name: str,
**kwargs,
) -> Dict[str, List[WindowsElement]]:
candidates: Dict[str, List[WindowsElement]] = {}
for element in elements:
not_good = (
control_type
and control_type != element.control_type
or class_name
and class_name != element.class_name
)
if not_good:
continue
for attr in cls.MATCH_PRIORITY:
value = kwargs[attr]
if value and value == getattr(element, attr):
candidates.setdefault(attr, []).append(element)
return candidates
def _match_element_for_path(
self, control: "Control", top_level_control: "Control", **kwargs
) -> Optional[str]:
# Compute how deep the search should go.
at_level = 0
cursor = control
while not cursor.IsTopLevel():
cursor = cursor.GetParentControl()
at_level += 1
if at_level == 0:
return None # the clicked element is the root of the tree (main window)
# Obtain a new element tree structure during every click, as the tree changes
# (expands/shrinks/rotates) with element actions producing UI display changes.
top_level_element = WindowsElement(top_level_control, None)
structure = self.windows_elements.print_tree(
top_level_element,
return_structure=True,
log_as_warnings=None,
max_depth=at_level,
)
elements_dict = self._filter_elements(structure[at_level], **kwargs)
for prio in self.MATCH_PRIORITY:
elements = elements_dict.get(prio, [])
for candidate in elements:
maybe_path = candidate.locator.rsplit(MatchObject.TREE_SEP, 1)[-1]
if "path:" in maybe_path:
return maybe_path
return None
def _get_element_key_properties(
self,
control: Optional["Control"],
*,
top_level_control: Optional["Control"] = None,
verbose: bool,
regex_limit: int = 300,
) -> List[str]:
if not control:
print("Got null control!")
return []
props = {
"name": control.Name,
"automation_id": control.AutomationId,
"control_type": control.ControlTypeName,
"class_name": control.ClassName,
}
locators = self._get_locators(regex_limit=regex_limit, **props)
# Add the `path:` strategy as well with verbose recordings. (useful when you
# can't rely on Automation IDs nor names)
if verbose and top_level_control:
path = self._match_element_for_path(
control,
top_level_control,
**props,
)
if path:
locators.append(path)
if locators:
if not verbose:
locators = locators[:1]
return locators
print("Was unable to construct locator for the control!")
return [] | /rpaframework_core-11.0.6.tar.gz/rpaframework_core-11.0.6/src/RPA/core/windows/inspect.py | 0.83602 | 0.182845 | inspect.py | pypi |
import functools
import logging
import re
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Set, Tuple, Union
from RPA.core.locators import LocatorsDatabase, WindowsLocator
from RPA.core.vendor.deco import keyword as method
from RPA.core.windows.context import (
ElementNotFound,
WindowControlError,
WindowsContext,
with_timeout,
)
from RPA.core.windows.helpers import IS_WINDOWS
if IS_WINDOWS:
import uiautomation as auto
from uiautomation.uiautomation import Control
Locator = Union["WindowsElement", str]
SearchType = Dict[str, Union[str, int, List[int]]]
@dataclass
class WindowsElement:
"""Represent Control as dataclass"""
item: "Control"
locator: Optional[Locator] = None
name: str = ""
automation_id: str = ""
control_type: str = ""
class_name: str = ""
left: int = -1
right: int = -1
top: int = -1
bottom: int = -1
width: int = -1
height: int = -1
xcenter: int = -1
ycenter: int = -1
def __init__(self, item: "Control", locator: Optional[Locator]):
self.item: "Control" = item
self.locator: Optional[Locator] = locator
self.name = item.Name
self.automation_id = item.AutomationId
self.control_type = item.ControlTypeName
self.class_name = item.ClassName
# If there's no rectangle, then all coords are defaulting to -1.
rect = item.BoundingRectangle
if rect:
self.left = rect.left
self.right = rect.right
self.top = rect.top
self.bottom = rect.bottom
self.width = rect.width()
self.height = rect.height()
self.xcenter = rect.xcenter()
self.ycenter = rect.ycenter()
self._sibling_element_compare = {
# <locator_strategy>: <element_attribute>
"id": "automation_id",
"automationid": "automation_id",
re.compile(r"(?<!sub)name:"): "name",
"subname": self._cmp_subname,
"regex": self._cmp_regex,
"class": "class_name",
"control": "control_type",
"type": "control_type",
}
@staticmethod
def _get_locator_value(locator: str, strategy: str) -> str:
# pylint: disable=not-an-iterable
for loc in MatchObject.parse_locator(locator).locators:
if loc[0] == strategy:
return loc[1]
raise ValueError(
f"couldn't find {strategy!r} in parsed final sub-locator: {locator}"
)
@classmethod
def _cmp_subname(cls, win_elem: "WindowsElement", *, locator: str) -> bool:
subname = cls._get_locator_value(locator, "SubName")
return subname in win_elem.name
@classmethod
def _cmp_regex(cls, win_elem: "WindowsElement", *, locator: str) -> bool:
pattern = cls._get_locator_value(locator, "RegexName")
return bool(re.match(pattern, win_elem.name))
@staticmethod
def norm_locator(locator: Optional[Locator]) -> Optional[str]:
while locator:
if isinstance(locator, WindowsElement):
locator = locator.locator
else: # finally, reached a string locator
break
return locator
def is_sibling(self, win_elem: "WindowsElement") -> bool:
"""Returns `True` if the provided window element is a sibling."""
locator: Optional[str] = self.norm_locator(win_elem)
if not locator:
return True # nothing to check here, can be considered sibling
last_locator_part = locator.split(MatchObject.TREE_SEP)[-1]
cmp_attrs = []
for strategy, attr_or_func in self._sibling_element_compare.items():
if isinstance(strategy, str):
strategy_regex = re.compile(rf"{strategy}:")
else:
strategy_regex = strategy
if strategy_regex.search(last_locator_part):
cmp_attrs.append(attr_or_func)
# Name comparison is assumed by default if no strategies are found at all.
cmp_attrs = cmp_attrs or ["name"]
for attr_or_func in cmp_attrs:
if isinstance(attr_or_func, str):
status = getattr(self, attr_or_func) == getattr(win_elem, attr_or_func)
else:
status = attr_or_func( # pylint: disable=not-callable
win_elem, locator=last_locator_part
)
if not status:
return False
return True
@dataclass
class MatchObject:
"""Represents all locator parts as object properties"""
_WINDOWS_LOCATOR_STRATEGIES = {
# RPA-strategy: UIA-strategy
"automationid": "AutomationId",
"id": "AutomationId",
"class": "ClassName",
"control": "ControlType",
"depth": "searchDepth",
"name": "Name",
"regex": "RegexName",
"subname": "SubName",
"type": "ControlType",
"index": "foundIndex",
"offset": "offset",
"desktop": "desktop",
"process": "process",
"handle": "handle",
"executable": "executable",
"path": "path",
}
TREE_SEP = " > "
PATH_SEP = "|" # path locator index separator
QUOTE = '"' # enclosing quote character
_LOCATOR_REGEX = re.compile(rf"\S*{QUOTE}[^{QUOTE}]+{QUOTE}|\S+", re.IGNORECASE)
_LOGGER = logging.getLogger(__name__)
locators: List[Tuple] = field(default_factory=list)
_classes: Set[str] = field(default_factory=set)
max_level: int = 0
@classmethod
def parse_locator(cls, locator: str) -> "MatchObject":
match_object = MatchObject()
locator_tree = [loc.strip() for loc in locator.split(cls.TREE_SEP)]
for level, branch in enumerate(locator_tree):
default_values = []
for part in cls._LOCATOR_REGEX.finditer(branch):
match_object.handle_locator_part(
level, part.group().strip(), default_values
)
if default_values:
match_object.add_locator("Name", " ".join(default_values), level=level)
if not match_object.locators:
match_object.add_locator("Name", locator)
return match_object
def handle_locator_part(
self, level: int, part_text: str, default_values: List[str]
) -> None:
if not part_text:
return
add_locator = functools.partial(self.add_locator, level=level)
if part_text in ("and", "or", "desktop"):
# NOTE(cmin764): Only "and" is supported at the moment. (match type is
# ignored and spaces are treated as "and"s by default)
if part_text == "desktop":
add_locator("desktop", "desktop")
return
try:
strategy, value = part_text.split(":", 1)
except ValueError:
self._LOGGER.debug("No locator strategy found. (assuming 'name')")
default_values.append(part_text)
return
control_strategy = self._WINDOWS_LOCATOR_STRATEGIES.get(strategy)
if control_strategy:
if default_values:
add_locator("Name", " ".join(default_values))
default_values.clear()
add_locator(control_strategy, value)
else:
self._LOGGER.warning(
"Invalid locator strategy %r! (assuming 'name')", strategy
)
default_values.append(part_text)
def add_locator(self, control_strategy: str, value: str, level: int = 0) -> None:
value = value.strip(f"{self.QUOTE} ")
if not value:
return
self.max_level = max(self.max_level, level)
if control_strategy in ("foundIndex", "searchDepth", "handle"):
value = int(value)
elif control_strategy == "ControlType":
value = value if value.endswith("Control") else f"{value}Control"
elif control_strategy == "ClassName":
self._classes.add(value.lower()) # pylint: disable=no-member
elif control_strategy == "path":
value = [
int(idx)
for idx in value.strip(f" {self.PATH_SEP}").split(self.PATH_SEP)
]
self.locators.append( # pylint: disable=no-member
(control_strategy, value, level)
)
@property
def classes(self) -> List[str]:
return list(self._classes)
class LocatorMethods(WindowsContext):
"""Keywords for finding Windows GUI elements"""
def __init__(self, ctx, locators_path: Optional[str] = None):
super().__init__(ctx)
self._locators_path = locators_path
@staticmethod
def _get_desktop_control() -> "Control":
root_control = auto.GetRootControl()
new_control = Control.CreateControlFromControl(root_control)
new_control.robocorp_click_offset = None
return new_control
@classmethod
def get_desktop_element(cls, locator: Optional[Locator] = None) -> WindowsElement:
desktop_control = cls._get_desktop_control()
return WindowsElement(desktop_control, locator)
@staticmethod
def _get_control_from_params(
search_params: SearchType, root_control: Optional["Control"] = None
) -> "Control":
search_params = search_params.copy() # to keep idempotent behaviour
offset = search_params.pop("offset", None)
control_type = search_params.pop("ControlType", "Control")
ElementControl = getattr(root_control, control_type, Control)
control = ElementControl(**search_params)
new_control = Control.CreateControlFromControl(control)
new_control.robocorp_click_offset = offset
return new_control
def _get_control_from_listed_windows(
self, search_params: SearchType, *, param_type: str, win_type: str
) -> "Control":
search_params = search_params.copy() # to keep idempotent behaviour
win_value = search_params.pop(param_type)
window_list = self.ctx.list_windows()
matches = [win for win in window_list if win[win_type] == win_value]
if not matches:
raise WindowControlError(
f"Could not locate window with {param_type} {win_value!r}"
)
elif len(matches) > 1:
raise WindowControlError(
f"Found more than one window with {param_type} {win_value!r}"
)
self.logger.info("Found process with window title: %r", matches[0]["title"])
search_params["Name"] = matches[0]["title"]
return self._get_control_from_params(search_params)
def _get_control_from_path(
self, search_params: SearchType, root_control: "Control"
) -> "Control":
# Follow a path in the tree of controls until reaching the final target.
search_params = search_params.copy() # to keep idempotent behaviour
path = search_params["path"]
current = root_control
to_path = lambda idx: ( # noqa: E731
MatchObject.PATH_SEP.join(str(pos) for pos in path[:idx])
)
for index, position in enumerate(path):
children = current.GetChildren()
if position > len(children):
raise ElementNotFound(
f"Unable to retrieve child on position {position!r} under a parent"
f" with partial path {to_path(index)!r}"
)
current = children[position - 1]
self.logger.debug(
"On child position %d found control: %s", position, current
)
offset = search_params.get("offset")
current.robocorp_click_offset = offset
return current
def _get_control_with_locator_part(
self, locator: str, search_depth: int, root_control: "Control"
) -> "Control":
# Prepare control search parameters.
match_object = MatchObject.parse_locator(locator)
self.logger.info("Locator %r produced matcher: %s", locator, match_object)
search_params = {}
for loc in match_object.locators: # pylint: disable=not-an-iterable
search_params[loc[0]] = loc[1]
if "searchDepth" not in search_params:
search_params["searchDepth"] = search_depth
elif {"desktop", "path"} & set(search_params):
self.logger.warning(
"Depth strategy has no effect on 'desktop:' or 'path:' ones!"
)
# Obtain an element with the search parameters.
if "desktop" in search_params:
return self._get_desktop_control()
if "executable" in search_params:
return self._get_control_from_listed_windows(
search_params, param_type="executable", win_type="name"
)
if "handle" in search_params:
return self._get_control_from_listed_windows(
search_params, param_type="handle", win_type="handle"
)
if "path" in search_params:
return self._get_control_from_path(search_params, root_control)
return self._get_control_from_params(search_params, root_control=root_control)
def _load_by_alias(self, criteria: str) -> str:
try:
locator = LocatorsDatabase.load_by_name(criteria, self._locators_path)
if isinstance(locator, WindowsLocator):
return locator.value
except ValueError:
pass
return criteria
def _resolve_root(self, root_element: Optional[WindowsElement]) -> WindowsElement:
# Explicit root element > set anchor > active window > Desktop.
root = (
self._window_or_none(root_element)
or self.anchor
or self.window
or self.get_desktop_element()
)
self.logger.info("Resulted root element: %s", root)
return root
def _get_element_by_locator_string(
self, locator: str, search_depth: int, root_element: Optional[WindowsElement]
) -> WindowsElement:
root_control = self._resolve_root(root_element).item
locator_parts = locator.split(MatchObject.TREE_SEP)
assert locator_parts, "empty locator"
try:
for locator_part in locator_parts:
self.logger.debug("Active root element: %r", root_control)
control = self._get_control_with_locator_part(
locator_part, search_depth, root_control
)
root_control = control
except LookupError as err:
raise ElementNotFound(
f"Element not found with locator {locator!r}"
) from err
# If we get here, a `control` item was found.
return WindowsElement(control, locator)
@method
@with_timeout
def get_element(
self,
locator: Optional[Locator] = None,
search_depth: int = 8,
root_element: Optional[WindowsElement] = None,
timeout: Optional[float] = None, # pylint: disable=unused-argument
) -> WindowsElement:
if isinstance(locator, str):
locator = self._load_by_alias(locator)
self.logger.info("Getting element with locator: %s", locator)
if not locator:
return self._resolve_root(root_element)
elif isinstance(locator, str):
element = self._get_element_by_locator_string(
locator, search_depth, root_element
)
else:
element = locator
if self._window_or_none(element) is None:
raise ElementNotFound(f"Unable to get element with {locator!r}")
self.logger.info("Returning element: %s", element)
return element | /rpaframework_core-11.0.6.tar.gz/rpaframework_core-11.0.6/src/RPA/core/windows/locators.py | 0.872198 | 0.153169 | locators.py | pypi |
from dataclasses import dataclass, asdict, fields, MISSING
from typing import Optional
@dataclass
class Locator:
"""Baseclass for a locator entry."""
def __str__(self):
values = []
for field in fields(self):
if field.default is not MISSING:
break
values.append(getattr(self, field.name))
typename = NAMES[type(self)]
return "{}:{}".format(typename, ",".join(str(value) for value in values))
@staticmethod
def from_dict(data):
"""Construct correct locator subclass from dictionary,
which should contain a 'type' field and at least all
required fields of that locator.
"""
type_ = data.pop("type", None)
if not type_:
raise ValueError("Missing locator type field")
class_ = TYPES.get(type_)
if not class_:
raise ValueError(f"Unknown locator type: {type_}")
# Check for missing parameters
required = set(
field.name for field in fields(class_) if field.default is MISSING
)
missing = set(required) - set(data)
if missing:
raise ValueError("Missing locator field(s): {}".format(", ".join(missing)))
# Ignore extra data
required_or_optional = [field.name for field in fields(class_)]
kwargs = {k: v for k, v in data.items() if k in required_or_optional}
return class_(**kwargs)
def to_dict(self):
"""Convert locator instance to a dictionary with type information."""
data = {"type": NAMES[type(self)]}
data.update(asdict(self))
return data
@dataclass
class PointLocator(Locator):
"""Locator for absolute coordinates."""
x: int
y: int
def __post_init__(self):
self.x = int(self.x)
self.y = int(self.y)
@dataclass
class OffsetLocator(Locator):
"""Locator for offset coordinates."""
x: int
y: int
def __post_init__(self):
self.x = int(self.x)
self.y = int(self.y)
@dataclass
class RegionLocator(Locator):
"""Locator for area defined by coordinates."""
left: int
top: int
right: int
bottom: int
def __post_init__(self):
self.left = int(self.left)
self.top = int(self.top)
self.right = int(self.right)
self.bottom = int(self.bottom)
@dataclass
class SizeLocator(Locator):
"""Locator for area defined by width/height."""
width: int
height: int
def __post_init__(self):
self.width = int(self.width)
self.height = int(self.height)
@dataclass
class ImageLocator(Locator):
"""Image-based locator for template matching."""
path: str
confidence: Optional[float] = None
source: Optional[str] = None # TODO: Remove when crop is implemented
def __post_init__(self):
if self.confidence is not None:
self.confidence = float(self.confidence)
@dataclass
class OcrLocator(Locator):
"""Locator for OCR-based text."""
text: str
confidence: Optional[float] = None
"""3-character ISO 639-2 language code. Passed to pytesseract lang parameter."""
language: Optional[str] = None
def __post_init__(self):
self.text = str(self.text)
if self.confidence is not None:
self.confidence = float(self.confidence)
@dataclass
class BrowserLocator(Locator):
"""Browser-based locator for DOM elements."""
strategy: str
value: str
source: Optional[str] = None
screenshot: Optional[str] = None
@dataclass
class WindowsLocator(Locator):
"""Windows-based locator for windows UI elements"""
window: str
value: str
version: float
screenshot: Optional[str] = None
# Aliases for backwards compatibility, just in case.
Offset = OffsetLocator
BrowserDOM = BrowserLocator
ImageTemplate = ImageLocator
Coordinates = PointLocator
# Mapping of supported locator typenames to classes.
# Used for parsing locator literals.
TYPES = {
"point": PointLocator,
"offset": OffsetLocator,
"region": RegionLocator,
"size": SizeLocator,
"image": ImageLocator,
"ocr": OcrLocator,
"browser": BrowserLocator,
"coordinates": PointLocator, # Backwards compatibility
"windows": WindowsLocator,
}
# Above mapping but in reverse direction.
NAMES = {
PointLocator: "point",
OffsetLocator: "offset",
RegionLocator: "region",
SizeLocator: "size",
ImageLocator: "image",
OcrLocator: "ocr",
BrowserLocator: "browser",
PointLocator: "point", # Backwards compatibility
WindowsLocator: "windows",
} | /rpaframework_core-11.0.6.tar.gz/rpaframework_core-11.0.6/src/RPA/core/locators/containers.py | 0.908833 | 0.267324 | containers.py | pypi |
import inspect
def not_keyword(func):
"""Decorator to disable exposing functions or methods as keywords.
Examples::
@not_keyword
def not_exposed_as_keyword():
# ...
def exposed_as_keyword():
# ...
Alternatively the automatic keyword discovery can be disabled with
the :func:`library` decorator or by setting the ``ROBOT_AUTO_KEYWORDS``
attribute to a false value.
New in Robot Framework 3.2.
"""
func.robot_not_keyword = True
return func
not_keyword.robot_not_keyword = True
@not_keyword
def keyword(name=None, tags=(), types=()):
"""Decorator to set custom name, tags and argument types to keywords.
This decorator creates ``robot_name``, ``robot_tags`` and ``robot_types``
attributes on the decorated keyword function or method based on the
provided arguments. Robot Framework checks them to determine the keyword's
name, tags, and argument types, respectively.
Name must be given as a string, tags as a list of strings, and types
either as a dictionary mapping argument names to types or as a list
of types mapped to arguments based on position. It is OK to specify types
only to some arguments, and setting ``types`` to ``None`` disables type
conversion altogether.
If the automatic keyword discovery has been disabled with the
:func:`library` decorator or by setting the ``ROBOT_AUTO_KEYWORDS``
attribute to a false value, this decorator is needed to mark functions
or methods keywords.
Examples::
@keyword
def example():
# ...
@keyword('Login as user "${user}" with password "${password}"',
tags=['custom name', 'embedded arguments', 'tags'])
def login(user, password):
# ...
@keyword(types={'length': int, 'case_insensitive': bool})
def types_as_dict(length, case_insensitive):
# ...
@keyword(types=[int, bool])
def types_as_list(length, case_insensitive):
# ...
@keyword(types=None])
def no_conversion(length, case_insensitive=False):
# ...
"""
if inspect.isroutine(name):
return keyword()(name)
def decorator(func):
func.robot_name = name
func.robot_tags = tags
func.robot_types = types
return func
return decorator
@not_keyword
def library(
scope=None, version=None, doc_format=None, listener=None, auto_keywords=False
):
"""Class decorator to control keyword discovery and other library settings.
By default disables automatic keyword detection by setting class attribute
``ROBOT_AUTO_KEYWORDS = False`` to the decorated library. In that mode
only methods decorated explicitly with the :func:`keyword` decorator become
keywords. If that is not desired, automatic keyword discovery can be
enabled by using ``auto_keywords=True``.
Arguments ``scope``, ``version``, ``doc_format`` and ``listener`` set the
library scope, version, documentation format and listener by using class
attributes ``ROBOT_LIBRARY_SCOPE``, ``ROBOT_LIBRARY_VERSION``,
``ROBOT_LIBRARY_DOC_FORMAT`` and ``ROBOT_LIBRARY_LISTENER``, respectively.
These attributes are only set if the related arguments are given and they
override possible existing attributes in the decorated class.
Examples::
@library
class KeywordDiscovery:
@keyword
def do_something(self):
# ...
def not_keyword(self):
# ...
@library(scope='GLOBAL', version='3.2')
class LibraryConfiguration:
# ...
The ``@library`` decorator is new in Robot Framework 3.2.
"""
if inspect.isclass(scope):
return library()(scope)
def decorator(cls):
if scope is not None:
cls.ROBOT_LIBRARY_SCOPE = scope
if version is not None:
cls.ROBOT_LIBRARY_VERSION = version
if doc_format is not None:
cls.ROBOT_LIBRARY_DOC_FORMAT = doc_format
if listener is not None:
cls.ROBOT_LIBRARY_LISTENER = listener
cls.ROBOT_AUTO_KEYWORDS = auto_keywords
return cls
return decorator | /rpaframework_core-11.0.6.tar.gz/rpaframework_core-11.0.6/src/RPA/core/vendor/deco.py | 0.801781 | 0.374962 | deco.py | pypi |
import atexit
import glob
import logging
import time
from datetime import date, datetime
from pathlib import Path
from typing import Dict, List, Optional, Union, Any, Generator
from robot.api.deco import library, keyword # type: ignore
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
from RPA.core.logger import deprecation
from .dialog import Dialog, TimeoutException
from .dialog_types import Elements, Result, Options, Size, Icon
from .utils import to_options, optional_str, optional_int, int_or_auto, is_input
@library(scope="GLOBAL", doc_format="REST", auto_keywords=False)
class Dialogs:
"""**NOTICE:** The `Dialogs` library is now marked for deprecation.
The library will be replaced by `Assistant`. In order to get more
information about the changes and the migration guide, please
check the release note: https://updates.robocorp.com/release/Gfko5-rpaframework-2200
The `Dialogs` library provides a way to display information to a user
and request input while a robot is running. It allows building processes
that require human interaction.
Some examples of use-cases could be the following:
- Displaying generated files after an execution is finished
- Displaying dynamic and user-friendly error messages
- Requesting passwords or other personal information
- Automating based on files created by the user
**Workflow**
The library is used to create dialogs, i.e. windows, that can be composed
on-the-fly based on the current state of the execution.
The content of the dialog is defined by calling relevant keywords
such as ``Add text`` or ``Add file input``. When the dialog is opened
the content is generated based on the previous keywords.
Depending on the way the dialog is started, the execution will either
block or continue while the dialog is open. During this time the user
can freely edit any possible input fields or handle other tasks.
After the user has successfully submitted the dialog, any possible
entered input will be returned as a result. The user also has the option
to abort by closing the dialog window forcefully.
**Results**
Each input field has a required ``name`` argument that controls what
the value will be called in the result object. Each input name should be
unique, and must not be called ``submit`` as that is reserved for the submit
button value.
A result object is a Robot Framework DotDict, where each key
is the name of the input field and the value is what the user entered.
The data type of each field depends on the input. For instance,
a text input will have a string, a checkbox will have a boolean, and
a file input will have a list of paths.
If the user closed the window before submitting or there was an internal
error, the library will raise an exception and the result values will
not be available.
**Examples**
.. code-block:: robotframework
Success dialog
Add icon Success
Add heading Your orders have been processed
Add files *.txt
Run dialog title=Success
Failure dialog
Add icon Failure
Add heading There was an error
Add text The assistant failed to login to the Enterprise portal
Add link https://robocorp.com/docs label=Troubleshooting guide
Run dialog title=Failure
Large dialog
Add heading A real chonker size=large
Add image fat-cat.jpeg
Run dialog title=Large height=1024 width=1024
Confirmation dialog
Add icon Warning
Add heading Delete user ${username}?
Add submit buttons buttons=No,Yes default=Yes
${result}= Run dialog
IF $result.submit == "Yes"
Delete user ${username}
END
Input form dialog
Add heading Send feedback
Add text input email label=E-mail address
Add text input message
... label=Feedback
... placeholder=Enter feedback here
... rows=5
${result}= Run dialog
Send feedback message ${result.email} ${result.message}
Dialog as progress indicator
Add heading Please wait while I open a browser
${dialog}= Show dialog title=Please wait on_top=${TRUE}
Open available browser https://robocorp.com
Close dialog ${dialog}
"""
def __init__(self) -> None:
deprecation(
"`RPA.Dialogs` got deprecated and will be no longer maintained, "
"please use `RPA.Assistant` instead and check the migration guide "
"and release notes that describe the differences "
"(https://updates.robocorp.com/release/Gfko5-rpaframework-2200)"
)
self.logger = logging.getLogger(__name__)
self.elements: Elements = []
self.dialogs: List[Dialog] = []
try:
# Prevent logging from keywords that return results
keywords = [
"Run dialog",
"Wait dialog",
"Wait all dialogs",
]
BuiltIn().import_library(
"RPA.core.logger.RobotLogListener", "WITH NAME", "RPA.RobotLogListener"
)
listener = BuiltIn().get_library_instance("RPA.RobotLogListener")
listener.register_protected_keywords(keywords)
except RobotNotRunningError:
pass
def add_element(self, element: Dict[str, Any]) -> None:
if is_input(element):
name = element["name"]
names = [
el["name"] for el in self.elements if el["type"].startswith("input-")
]
if name in names:
raise ValueError(f"Input with name '{name}' already exists")
if name == "submit":
raise ValueError("Input name 'submit' is not allowed")
self.elements.append(element)
@keyword("Clear elements")
def clear_elements(self) -> None:
"""Remove all previously defined elements and start from a clean state
By default this is done automatically when a dialog is created.
Example:
.. code-block:: robotframework
Add heading Please input user information
FOR ${user} IN @{users}
Run dialog clear=False
Process page
END
Clear elements
"""
self.elements = []
@keyword("Add heading")
def add_heading(
self,
heading: str,
size: Size = Size.Medium,
) -> None:
"""Add a centered heading text element
:param heading: The text content for the heading
:param size: The size of the heading
Supported ``size`` values are Small, Medium, and Large. By default uses
the value Medium.
Example:
.. code-block:: robotframework
Add heading User information size=Large
Add heading Location size=Small
Add text input address label=User address
Run dialog
"""
if not isinstance(size, Size):
size = Size(size)
element = {
"type": "heading",
"value": str(heading),
"size": size.value,
}
self.add_element(element)
@keyword("Add text")
def add_text(
self,
text: str,
size: Size = Size.Medium,
) -> None:
"""Add a text paragraph element, for larger bodies of text
:param text: The text content for the paragraph
:param size: The size of the text
Supported ``size`` values are Small, Medium, and Large. By default uses
the value Medium.
Example:
.. code-block:: robotframework
Add heading An error occurred
Add text There was an error while requesting user information
Add text ${error} size=Small
Run dialog
"""
if not isinstance(size, Size):
size = Size(size)
element = {
"type": "text",
"value": str(text),
"size": size.value,
}
self.add_element(element)
@keyword("Add link")
def add_link(
self,
url: str,
label: Optional[str] = None,
) -> None:
"""Add an external URL link element
:param url: The URL for the link
:param label: A custom label text for the link
Adds a clickable link element, which opens the user's default
browser to the given ``url``. Optionally a ``label`` can be given
which is shown as the link text, instead of the raw URL.
Example:
.. code-block:: robotframework
Add heading An error occurred
Add text See link for documentation
Add link https://robocorp.com/docs label=Troubleshooting
Run dialog
"""
element = {
"type": "link",
"value": str(url),
"label": optional_str(label),
}
self.add_element(element)
@keyword("Add image")
def add_image(
self,
url_or_path: str,
width: Optional[int] = None,
height: Optional[int] = None,
) -> None:
"""Add an image element, from a local file or remote URL
:param url_or_path: The location of the image
:param width: The static width of the image, in pixels
:param height: The static height of the image, in pixels
Adds an inline image to the dialog, which can either
point to a local file path on the executing machine or to
a remote URL.
By default the image is resized to fit the width of the dialog
window, but the width and/or height can be explicitly defined
to a custom value. If only one of the dimensions is given,
the other is automatically changed to maintain the correct aspect ratio.
Example:
.. code-block:: robotframework
Add image company-logo.png
Add heading To start, please press the Continue button size=Small
Add submit buttons Continue
Run dialog
"""
element = {
"type": "image",
"value": str(url_or_path),
"width": optional_int(width),
"height": optional_int(height),
}
self.add_element(element)
@keyword("Add file")
def add_file(
self,
path: str,
label: Optional[str] = None,
) -> None:
"""Add a file element, which links to a local file
:param path: The path to the file
:param label: A custom label text for the file
Adds a button which opens a local file with the corresponding
default application. Can be used for instance to display generated
files from the robot to the end-user.
Optionally a custom ``label`` can be given for the button text.
By default uses the filename of the linked file.
Example:
.. code-block:: robotframework
${path}= Generate order files
Add heading Current orders
Add file ${path} label=Current
Run dialog
"""
resolved = Path(path).resolve()
self.logger.info("Adding file: %s", resolved)
if not resolved.exists():
self.logger.warning("File does not exist: %s", resolved)
element = {
"type": "file",
"value": str(resolved),
"label": optional_str(label),
}
self.add_element(element)
@keyword("Add files")
def add_files(
self,
pattern: str,
) -> None:
"""Add multiple file elements according to the given file pattern
:param pattern: File matching pattern
See the keyword ``Add file`` for information about the inserted
element itself.
The keyword uses Unix-style glob patterns for finding matching files,
and the supported pattern expressions are as follow:
========== ================================================
Pattern Meaning
========== ================================================
``*`` Match everything
``?`` Match any single character
``[seq]`` Match any character in seq
``[!seq]`` Match any character not in seq
``**`` Match all files, directories, and subdirectories
========== ================================================
If a filename has any of these special characters, they
can be escaped by wrapping them with square brackets.
Example:
.. code-block:: robotframework
# Add all excel files
Add files *.xlsx
# Add all log files in any subdirectory
Add files **/*.log
# Add all PDFs between order0 and order9
Add files order[0-9].pdf
"""
matches = glob.glob(pattern, recursive=True)
for match in sorted(matches):
self.add_file(match)
@keyword("Add icon")
def add_icon(self, variant: Icon, size: int = 48) -> None:
"""Add an icon element
:param variant: The icon type
:param size: The size of the icon
Adds an icon which can be used to indicate status
or the type of dialog being presented.
The currently supported icon types are:
======= ==========================
Name Description
======= ==========================
Success A green check mark
Warning An orange warning triangle
Failure A red cross or X mark
======= ==========================
The ``size`` of the icon can also be changed,
to a given height/width of pixels.
Example:
.. code-block:: robotframework
Add icon Warning size=64
Add heading Do you want to delete this order?
Add submit buttons buttons=No,Yes
${result}= Run dialog
"""
if not isinstance(variant, Icon):
variant = Icon(variant)
element = {
"type": "icon",
"variant": variant.value,
"size": int(size),
}
self.add_element(element)
@keyword("Add text input", tags=["input"])
def add_text_input(
self,
name: str,
label: Optional[str] = None,
placeholder: Optional[str] = None,
rows: Optional[int] = None,
) -> None:
"""Add a text input element
:param name: Name of result field
:param label: Label for field
:param placeholder: Placeholder text in input field
:param rows: Number of input rows
Adds a text field that can be filled by the user. The entered
content will be available in the ``name`` field of the result.
For customizing the look of the input, the ``label`` text can be given
to add a descriptive label and the ``placholder`` text can be given
to act as an example of the input value.
If the ``rows`` argument is given as a number, the input is converted
into a larger text area input with the given amount of rows by default.
Example:
.. code-block:: robotframework
Add heading Send feedback
Add text input email label=E-mail address
Add text input message
... label=Feedback
... placeholder=Enter feedback here
... rows=5
${result}= Run dialog
Send feedback message ${result.email} ${result.message}
"""
element = {
"type": "input-text",
"name": str(name),
"label": optional_str(label),
"placeholder": optional_str(placeholder),
"rows": optional_int(rows),
}
self.add_element(element)
@keyword("Add password input", tags=["input"])
def add_password_input(
self,
name: str,
label: Optional[str] = None,
placeholder: Optional[str] = None,
) -> None:
"""Add a password input element
:param name: Name of result field
:param label: Label for field
:param placeholder: Placeholder text in input field
Adds a text field that hides the user's input. The entered
content will be available in the ``name`` field of the result.
For customizing the look of the input, the ``label`` text can be given
to add a descriptive label and the ``placholder`` text can be given
to act as an example of the input value.
Example:
.. code-block:: robotframework
Add heading Change password
Add text input username label=Current username
Add password input password label=New password
${result}= Run dialog
Change user password ${result.username} ${result.password}
"""
element = {
"type": "input-password",
"name": str(name),
"label": optional_str(label),
"placeholder": optional_str(placeholder),
}
self.add_element(element)
@keyword("Add hidden input", tags=["input"])
def add_hidden_input(
self,
name: str,
value: str,
) -> None:
"""Add a hidden input element
:param name: Name of result feild
:param value: Value for input
Adds a special hidden result field that is not visible
to the user and always contains the given static value.
Can be used to keep user input together with already known
values such as user IDs, or to ensure that dialogs with differing
elements all have the same fields in results.
Example:
.. code-block:: robotframework
Add hidden input user_id ${USER_ID}
Add text input username
${result}= Run dialog
Enter user information ${result.user_id} ${result.username}
"""
element = {
"type": "input-hidden",
"name": str(name),
"value": str(value),
}
self.add_element(element)
@keyword("Add file input", tags=["input"])
def add_file_input(
self,
name: str,
label: Optional[str] = None,
source: Optional[str] = None,
destination: Optional[str] = None,
file_type: Optional[str] = None,
multiple: bool = False,
) -> None:
"""Add a file input element
:param name: Name of result field
:param label: Label for input field
:param source: Default source directory
:param destination: Target directory for selected files
:param file_type: Accepted file types
:param multiple: Allow selecting multiple files
Adds a native file selection dialog for inputting one or more files.
The list of selected files will be available in the ``name`` field
of the result.
By default opens up in the user's home directory, but it can be
set to a custom path with the ``source`` argument.
If the ``destination`` argument is not set, it returns the original
paths to the selected files. If the ``destination`` directory
is set, the files are copied there first and the new paths are
returned.
The argument ``file_type`` restricts the possible file extensions
that the user can select. The format of the argument is as follows:
``Description text (*.ext1;*.ext2;...)``. For instance, an argument
to limit options to Excel files could be: ``Excel files (*.xls;*.xlsx)``.
To allow selecting more than one file, the ``multiple`` argument
can be enabled.
Example:
.. code-block:: robotframework
# This can be any one file
Add file input name=anyting
# This can be multiple files
Add file input name=multiple multiple=True
# This opens the select dialog to a custom folder
Add file input name=src source=C:\\Temp\\Output\\
# This copies selected files to a custom folder
Add file input name=dest destination=%{ROBOT_ROOT}
# This restricts files to certain types
Add file input name=types file_type=PDF files (*.pdf)
# Every file input result is a list of paths
${result}= Run dialog
FOR ${path} IN @{result.multiple}
Log Selected file: ${path}
END
"""
element = {
"type": "input-file",
"name": str(name),
"label": optional_str(label),
"source": optional_str(source),
"destination": optional_str(destination),
"file_type": optional_str(file_type),
"multiple": bool(multiple),
}
self.add_element(element)
@keyword("Add drop-down", tags=["input"])
def add_drop_down(
self,
name: str,
options: Options,
default: Optional[str] = None,
label: Optional[str] = None,
) -> None:
"""Add a drop-down element
:param name: Name of result field
:param options: List of drop-down options
:param default: The default selection
:param label: Label for input field
Creates a drop-down menu with the given ``options``. The selection
the user makes will be available in the ``name`` field of the result.
The ``default`` argument can be one of the defined options,
and the dialog automatically selects that option for the input.
A custom ``label`` text can also be added.
Example:
.. code-block:: robotframework
Add heading Select user type
Add drop-down
... name=user_type
... options=Admin,Maintainer,Operator
... default=Operator
... label=User type
${result}= Run dialog
Log User type should be: ${result.user_type}
"""
options, default = to_options(options, default)
element = {
"type": "input-dropdown",
"name": str(name),
"options": options,
"default": default,
"label": optional_str(label),
}
self.add_element(element)
@keyword("Add Date Input", tags=["input"])
def add_date_input(
self,
name: str,
default: Optional[Union[date, str]] = None,
label: Optional[str] = None,
) -> None:
"""Add a date input element
:param name: Name of the result field
:param default: The default set date
:param label: Label for the date input field
Displays a date input widget. The selection the user makes will be available
as a ``date`` object in the ``name`` field of the result.
The ``default`` argument can be a pre-set date as object or string in
"YYYY-MM-DD" format, otherwise the current date is used.
Example:
.. code-block:: robotframework
Add heading Enter your birthdate
Add Date Input birthdate default=1993-04-26
${result} = Run dialog
Log To Console User birthdate year should be: ${result.birthdate.year}
"""
# TODO(cmin764): Be flexible on date formats. (provide it as parameter)
py_date_format = "%Y-%m-%d"
js_date_format = "yyyy-MM-dd"
default = default or datetime.utcnow().date()
if isinstance(default, date): # recognizes both `date` and `datetime`
default = default.strftime(py_date_format)
else:
try:
datetime.strptime(default, py_date_format)
except Exception as exc:
raise ValueError(
f"Invalid default date with value {default!r}"
) from exc
element = {
"type": "input-datepicker",
"name": str(name),
"_format": py_date_format,
"format": js_date_format,
"default": optional_str(default),
"label": optional_str(label),
}
self.add_element(element)
@keyword("Add radio buttons", tags=["input"])
def add_radio_buttons(
self,
name: str,
options: Options,
default: Optional[str] = None,
label: Optional[str] = None,
) -> None:
"""Add radio button elements
:param name: Name of result field
:param options: List of drop-down options
:param default: The default selection
:param label: Label for input field
Creates a set of radio buttons with the given ``options``. The selection
the user makes will be available in the ``name`` field of the result.
The ``default`` argument can be one of the defined options,
and the dialog automatically selects that option for the input.
A custom ``label`` text can also be added.
Example:
.. code-block:: robotframework
Add heading Select user type
Add radio buttons
... name=user_type
... options=Admin,Maintainer,Operator
... default=Operator
... label=User type
${result}= Run dialog
Log User type should be: ${result.user_type}
"""
options, default = to_options(options, default)
element = {
"type": "input-radio",
"name": str(name),
"options": options,
"default": default,
"label": optional_str(label),
}
self.add_element(element)
@keyword("Add checkbox", tags=["input"])
def add_checkbox(
self,
name: str,
label: str,
default: bool = False,
) -> None:
"""Add a checkbox element
:param name: Name of result field
:param label: Label text for checkbox
:param default: Default checked state
Adds a checkbox that indicates a true or false value.
The selection will be available in the ``name`` field of the result,
and the ``label`` text will be shown next to the checkbox.
The boolean ``default`` value will define the initial checked
state of the element.
Example:
.. code-block:: robotframework
Add heading Enable features
Add checkbox name=vault label=Enable vault default=True
Add checkbox name=triggers label=Enable triggers default=False
Add checkbox name=assistants label=Enable assistants default=True
${result}= Run dialog
IF $result.vault
Enable vault
END
"""
element = {
"type": "input-checkbox",
"name": str(name),
"label": str(label),
"default": bool(default),
}
self.add_element(element)
@keyword
def add_dialog_next_page_button(
self,
label: str,
) -> None:
"""Add a next page button
:param label: The text displayed on the button
The next page button will delimit the next elements of
the dialog in a separate view, so that they will only be displayed after
pressing the button, creating a wizard experience in the dialog.
Example:
.. code-block:: robotframework
Add heading Send feedback
Add text input email label=E-mail address
Add dialog next page button label=next
Add text input name label=Name
Add dialog next page button label=next
Add checkbox name=contact
... label=Do you want us to contact you?
... default=True
Add dialog next page button label=next
Add text input message
... label=Feedback
... placeholder=Enter feedback here
... rows=5
Add submit buttons buttons=submit
${result}= Run dialog
Send feedback message ${result.email} ${result.message}
Run dialog
"""
element = {
"type": "next",
"label": str(label),
}
self.add_element(element)
@keyword("Add submit buttons", tags=["input"])
def add_submit_buttons(
self,
buttons: Options,
default: Optional[str] = None,
) -> None:
"""Add custom submit buttons
:param buttons: Submit button options
:param default: The primary button
The dialog automatically creates a button for closing itself.
If there are no input fields, the button will say "Close".
If there are one or more input fields, the button will say "Submit".
If the submit button should have a custom label or there should be
multiple options to choose from when submitting, this keyword can
be used to replace the automatically generated ones.
The result field will always be called ``submit`` and will contain
the pressed button text as a value.
If one of the custom ``options`` should be the preferred option,
the ``default`` argument controls which one is highlighted with
an accent color.
Example:
.. code-block:: robotframework
Add icon Warning
Add heading Delete user ${username}?
Add submit buttons buttons=No,Yes default=Yes
${result}= Run dialog
IF $result.submit == "Yes"
Delete user ${username}
END
"""
buttons, _ = to_options(buttons, default)
element = {
"type": "submit",
"buttons": buttons,
"default": default,
}
self.add_element(element)
@keyword("Run dialog", tags=["dialog"])
def run_dialog(self, timeout: int = 180, **options: Any) -> Result:
"""Create a dialog from all the defined elements and block
until the user has handled it.
:param timeout: Time to wait for dialog to complete, in seconds
:param options: Options for the dialog
Returns a result object with all input values.
This keyword is a shorthand for the following expression:
.. code-block:: robotframework
Run dialog
[Arguments] ${timeout}=180 &{options}
${dialog}= Show dialog &{options}
${result}= Wait dialog ${dialog} timeout=${timeout}
[Return] ${result}
For more information about possible options for opening the dialog,
see the documentation for the keyword ``Show dialog``.
Example:
.. code-block:: robotframework
Add heading Please enter your username
Add text input name=username
${result}= Run dialog
Log The username is: ${result.username}
"""
dialog = self.show_dialog(**options)
return self.wait_dialog(dialog, timeout)
@keyword("Show dialog", tags=["dialog"])
def show_dialog(
self,
title: str = "Dialog",
height: Union[int, str] = "AUTO",
width: int = 480,
on_top: bool = False,
clear: bool = True,
debug: bool = False,
) -> Dialog:
"""Create a new dialog with all the defined elements, and show
it to the user. Does not block, but instead immediately returns
a new ``Dialog`` instance.
The return value can later be used to wait for
the user to close the dialog and inspect the results.
:param title: Title of dialog
:param height: Height of dialog (in pixels or 'AUTO')
:param width: Width of dialog (in pixels)
:param on_top: Show dialog always on top of other windows
:param clear: Remove all defined elements
:param debug: Allow opening developer tools in Dialog window
By default the window has the title ``Dialog``, but it can be changed
with the argument ``title`` to any string.
The ``height`` argument accepts a static number in pixels, but
defaults to the string value ``AUTO``. In this mode the Dialog window
tries to automatically resize itself to fit the defined content.
In comparison, the ``width`` argument only accepts pixel values, as all
element types by default resize to fit the given window width.
With the ``clear`` argument it's possible to control if defined elements
should be cleared after the dialog has been created. It can be set
to ``False`` if the same content should be shown multiple times.
In certain applications it's useful to have the dialog always be
on top of already opened applications. This can be set with the
argument ``on_top``, which is disabled by default.
For development purposes the ``debug`` agument can be enabled to
allow opening browser developer tools.
If the dialog is still open when the execution ends, it's closed
automatically.
Example:
.. code-block:: robotframework
Add text input name=username label=Username
Add text input name=address label=Address
${dialog}= Show dialog title=Input form
Open browser to form page
${result}= Wait dialog ${dialog}
Insert user information ${result.username} ${result.address}
"""
height = int_or_auto(height)
dialog = Dialog(
self.elements,
title=title,
height=height,
width=width,
on_top=on_top,
debug=debug,
)
if clear:
self.clear_elements()
dialog.start()
self.dialogs.append(dialog)
atexit.register(dialog.stop)
return dialog
@keyword("Wait dialog", tags=["dialog"])
def wait_dialog(self, dialog: Dialog, timeout: int = 300) -> Result:
"""Wait for a dialog to complete that has been created with the
keyword ``Show dialog``.
:param dialog: An instance of a Dialog
:param timeout: Time to wait for dialog to complete, in seconds
Blocks until a user has closed the dialog or until ``timeout``
amount of seconds has been reached.
If the user submitted the dialog, returns a result object.
If the user closed the dialog window or ``timeout`` was reached,
raises an exception.
Example:
.. code-block:: robotframework
Add text input name=username label=Username
Add text input name=address label=Address
${dialog}= Show dialog title=Input form
Open browser to form page
${result}= Wait dialog ${dialog}
Insert user information ${result.username} ${result.address}
"""
dialog.wait(timeout)
return dialog.result()
@keyword("Wait all dialogs", tags=["dialog"])
def wait_all_dialogs(self, timeout: int = 300) -> List[Result]:
"""Wait for all opened dialogs to be handled by the user.
:param timeout: Time to wait for dialogs to complete, in seconds
Returns a list of results from all dialogs that have not been handled
before calling this keyword, in the order the dialogs
were originally created.
If any dialog fails, this keyword throws the corresponding exception
immediately and doesn't keep waiting for further results.
Example:
.. code-block:: robotframework
# Create multiple dialogs
Show dialog title=One
Show dialog title=Two
Show dialog title=Three
# Wait for all of them to complete
@{results}= Wait all dialogs
# Loop through results
FOR ${result} IN @{results}
Log many &{result}
END
"""
# Filter dialogs that have been handled already
pending = [dialog for dialog in self.dialogs if dialog.is_pending]
results = []
for dialog in self.wait_dialogs_as_completed(*pending, timeout=timeout):
results.append((dialog, dialog.result()))
# Sort by dialog creation timestamp
results.sort(key=lambda t: t[0].timestamp)
return [result for _, result in results]
@keyword("Close dialog", tags=["dialog"])
def close_dialog(self, dialog: Dialog) -> None:
"""Close a dialog that has been created with the keyword
``Show dialog``.
:param dialog: An instance of a Dialog
Calling this keyword is not required if the user correctly
submits a dialog or closes it manually. However, it can be used
to forcefully hide a dialog if the result is no longer relevant.
If a forcefully closed dialog is waited, it will throw
an exception to indicate that it was closed before receiving
a valid result.
Example:
.. code-block:: robotframework
# Display notification dialog while operation runs
${dialog}= Show dialog title=Please wait
Run process that takes a while
Close dialog ${dialog}
"""
dialog.stop()
@keyword("Close all dialogs", tags=["dialog"])
def close_all_dialogs(self) -> None:
"""Close all dialogs opened by this library.
See the keyword ``Close dialog`` for further information
about usage and implications.
Example:
.. code-block:: robotframework
${dialog1}= Show dialog
A keyword which runs during the dialog
${dialog2}= Show dialog
A keyword that fails during the dialog
# Close all dialogs without knowing which have been created
[Teardown] Close all dialogs
"""
for dialog in self.dialogs:
dialog.stop()
def wait_dialogs_as_completed(
self, *dialogs: Dialog, timeout: int = 300
) -> Generator[Dialog, None, None]:
"""Create a generator that yields dialogs as they complete.
:param dialogs: Dialogs to wait
:param timeout: Time in seconds to wait for all dialogs
"""
if not dialogs:
return
index = list(range(len(dialogs)))
end = time.time() + timeout
while time.time() <= end:
if not index:
return
for idx in list(index):
dialog = dialogs[idx]
if dialog.poll():
self.logger.info(
"Dialog completed (%s/%s)",
len(dialogs) - len(index) + 1,
len(dialogs),
)
yield dialog
index.remove(idx)
time.sleep(0.1)
raise TimeoutException("Reached timeout while waiting for dialogs") | /rpaframework_dialogs-4.0.4-py3-none-any.whl/RPA/Dialogs/library.py | 0.794664 | 0.360461 | library.py | pypi |
import json
import logging
import subprocess
import time
from datetime import datetime
from typing import Any, Union, Optional
import robocorp_dialog # type: ignore
from robot.utils import DotDict # type: ignore
from .dialog_types import Element, Elements, Result
from .utils import is_input, is_submit
class TimeoutException(RuntimeError):
"""Timeout while waiting for dialog to finish."""
class Dialog:
"""Container for a dialog running in a separate subprocess."""
# Post-process received result's values.
POST_PROCESS_MAP = {
"input-datepicker": lambda value, *, _format, **__: datetime.strptime(
value, _format # converts date strings to objects
).date(),
}
def __init__(
self,
elements: Elements,
title: str,
width: int,
height: Union[int, str],
on_top: bool,
debug: bool = False,
):
self.logger = logging.getLogger(__name__)
self.timestamp = time.time()
auto_height = height == "AUTO"
if auto_height:
height = 100
self._elements = self._to_elements(elements)
self._options = {
"title": str(title),
"width": int(width),
"height": int(height),
}
self._flags = {
"auto_height": bool(auto_height),
"on_top": bool(on_top),
"debug": bool(debug),
}
# Flag to indicate if someone has handled the result
self._is_pending = True
self._result: Optional[Result] = None
self._process: Optional[subprocess.Popen] = None
@property
def is_pending(self):
return self._is_pending
def start(self) -> None:
if self._process is not None:
raise RuntimeError("Process already started")
cmd = [
robocorp_dialog.executable(),
json.dumps(self._elements),
]
for option, value in self._options.items():
cmd.append(f"--{option}")
cmd.append(str(value))
for flag, value in self._flags.items():
if value:
cmd.append(f"--{flag}")
# pylint: disable=consider-using-with
self._process = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
def stop(self, timeout: int = 15) -> None:
if self._process is None:
raise RuntimeError("Process not started")
if self.poll():
self.logger.debug("Process already finished")
return
self._result = {"error": "Stopped by execution"}
self._process.terminate()
try:
self._process.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
self._process.kill()
self._process.communicate()
def poll(self) -> bool:
if self._process is None:
raise RuntimeError("Process not started")
if self._result is not None:
return True
try:
stdout, stderr = self._process.communicate(timeout=0.2)
except subprocess.TimeoutExpired:
return False
self._to_result(stdout, stderr)
return True
def wait(self, timeout: int = 180) -> None:
if self._process is None:
raise RuntimeError("Process not started")
if self._result is not None:
return
try:
stdout, stderr = self._process.communicate(timeout=timeout)
except subprocess.TimeoutExpired as err:
raise TimeoutException("Reached timeout while waiting for dialog") from err
self._to_result(stdout, stderr)
def result(self) -> Result:
if self._process is None:
raise RuntimeError("Process not started")
if self._result is None:
raise RuntimeError("No result set, call poll() or wait() first")
self._is_pending = False
if "error" in self._result:
raise RuntimeError(self._result["error"])
result = DotDict()
fields = self._result["value"]
for element in self._elements:
if is_input(element):
key = element["name"]
assert key in fields, f"Missing input value for '{key}'"
result[key] = self._post_process_value(fields[key], element=element)
elif is_submit(element):
result["submit"] = fields["submit"]
assert "submit" in result, "Missing submit value"
return result
def _to_elements(self, elements: Elements) -> Elements:
has_submit = any(is_submit(element) for element in elements)
has_input = any(is_input(element) for element in elements)
if not has_submit:
element = {
"type": "submit",
"buttons": ["Submit"] if has_input else ["Close"],
"default": None,
}
elements.append(element)
return elements
def _to_result(self, stdout: bytes, stderr: bytes) -> None:
if self._process is None:
raise RuntimeError("Process not started")
out = stdout.decode().strip()
err = stderr.decode().strip()
if self._process.returncode != 0:
self._result = {"error": str(err)}
return
if not out:
# Process didn't have non-zero exit code, but also didn't
# print JSON output. Possibly flushing issue,
# unhandled code path, or killed by OS.
self._result = {"error": "Closed abruptly"}
return
try:
self._result = json.loads(out)
except ValueError:
self._result = {"error": f"Malformed response:\n{out}"}
@classmethod
def _post_process_value(cls, value: Any, *, element: Element) -> Any:
func = cls.POST_PROCESS_MAP.get(element["type"])
if func:
value = func(value, **element)
return value | /rpaframework_dialogs-4.0.4-py3-none-any.whl/RPA/Dialogs/dialog.py | 0.764804 | 0.175432 | dialog.py | pypi |
from typing import Dict, Optional
from google.cloud import vision
from . import (
LibraryContext,
keyword,
)
class VisionKeywords(LibraryContext):
"""Keywords for Google Vision operations"""
def __init__(self, ctx):
super().__init__(ctx)
self.service = None
@keyword(tags=["init", "vision"])
def init_vision(
self,
service_account: str = None,
use_robocorp_vault: Optional[bool] = None,
token_file: str = None,
) -> None:
"""Initialize Google Cloud Vision client
:param service_account: file path to service account file
:param use_robocorp_vault: use credentials in `Robocorp Vault`
:param token_file: file path to token file
"""
self.service = self.init_service_with_object(
vision.ImageAnnotatorClient,
service_account,
use_robocorp_vault,
token_file,
)
def set_image_type(self, image_file: str = None, image_uri: str = None):
if image_file:
with open(image_file, "rb") as f:
content = f.read()
return {"image": {"content": content}}
elif image_uri:
return {"image": {"source": {"image_uri": image_uri}}}
else:
raise KeyError("'image_file' or 'image_uri' is required")
@keyword(tags=["vision"])
def detect_labels(
self, image_file: str = None, image_uri: str = None, json_file: str = None
) -> Dict:
"""Detect labels in the image
:param image_file: source image file path
:param image_uri: source image uri
:param json_file: json target to save result
:return: detection response
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Detect Labels image_file=${CURDIR}${/}test.png
... json_file=${CURDIR}${/}result.json
"""
parameters = self.set_image_type(image_file, image_uri)
response = self.service.label_detection(**parameters)
self.write_json(json_file, response)
return response
@keyword(tags=["vision"])
def detect_text(
self, image_file: str = None, image_uri: str = None, json_file: str = None
) -> Dict:
"""Detect text in the image
:param image_file: source image file path
:param image_uri: Google Cloud Storage URI
:param json_file: json target to save result
:return: detection response
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Detect Text image_file=${CURDIR}${/}test.png
... json_file=${CURDIR}${/}result.json
"""
parameters = self.set_image_type(image_file, image_uri)
response = self.service.text_detection(**parameters)
self.write_json(json_file, response)
return response
@keyword(tags=["vision"])
def detect_document(
self, image_file: str = None, image_uri: str = None, json_file: str = None
) -> Dict:
"""Detect document
:param image_file: source image file path
:param image_uri: Google Cloud Storage URI
:param json_file: json target to save result
:return: detection response
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Detect Document image_file=${CURDIR}${/}test.png
... json_file=${CURDIR}${/}result.json
"""
parameters = self.set_image_type(image_file, image_uri)
response = self.service.document_text_detection(**parameters)
self.write_json(json_file, response)
return response
@keyword(tags=["vision"])
def annotate_image(
self, image_file: str, image_uri: str, json_file: str = None
) -> Dict:
"""Annotate image
:param image_file: source image file path
:param image_uri: Google Cloud Storage URI
:param json_file: json target to save result
:return: detection response
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Annotate Image image_file=${CURDIR}${/}test.png
... json_file=${CURDIR}${/}result.json
"""
parameters = self.set_image_type(image_file, image_uri)
response = self.service.annotate_image(**parameters)
self.write_json(json_file, response)
return response
@keyword(tags=["vision"])
def face_detection(
self, image_file: str = None, image_uri: str = None, json_file: str = None
) -> Dict:
"""Detect faces
:param image_file: source image file path
:param image_uri: Google Cloud Storage URI
:param json_file: json target to save result
:return: detection response
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Face Detection image_uri=gs://vision/faces.png
... json_file=${CURDIR}${/}result.json
"""
parameters = self.set_image_type(image_file, image_uri)
response = self.service.face_detection(**parameters)
self.write_json(json_file, response)
return response | /rpaframework_google-7.1.2.tar.gz/rpaframework_google-7.1.2/src/RPA/Cloud/Google/keywords/vision.py | 0.926366 | 0.267465 | vision.py | pypi |
from typing import Dict, List, Optional
from . import (
LibraryContext,
keyword,
)
class SheetsKeywords(LibraryContext):
"""Keywords for Google Sheets operations"""
def __init__(self, ctx):
super().__init__(ctx)
self.service = None
@keyword(tags=["init", "sheets"])
def init_sheets(
self,
service_account: str = None,
credentials: str = None,
use_robocorp_vault: Optional[bool] = None,
scopes: list = None,
token_file: str = None,
) -> None:
"""Initialize Google Sheets client
:param service_account: file path to service account file
:param credentials: file path to credentials file
:param use_robocorp_vault: use credentials in `Robocorp Vault`
:param scopes: list of extra authentication scopes
:param token_file: file path to token file
"""
sheets_scopes = ["drive", "drive.file", "spreadsheets"]
if scopes:
sheets_scopes += scopes
self.service = self.init_service(
service_name="sheets",
api_version="v4",
scopes=sheets_scopes,
service_account_file=service_account,
credentials_file=credentials,
use_robocorp_vault=use_robocorp_vault,
token_file=token_file,
)
@keyword(tags=["sheets"])
def create_sheet(self, title: str) -> str:
"""Create empty sheet with a title
:param title: name as string
:return: created `sheet_id`
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Create Sheet Example Sheet
"""
if not title:
raise KeyError("title is required for kw: create_sheet")
data = {"properties": {"title": title}}
spreadsheet = (
self.service.spreadsheets()
.create(body=data, fields="spreadsheetId")
.execute()
)
return spreadsheet.get("spreadsheetId")
@keyword(tags=["sheets"])
def insert_sheet_values(
self,
sheet_id: str,
sheet_range: str,
values: list,
major_dimension: str = "COLUMNS",
value_input_option: str = "USER_ENTERED",
) -> Dict:
"""Insert values into sheet cells
:param sheet_id: target sheet
:param sheet_range: target sheet range
:param values: list of values to insert into sheet
:param major_dimension: major dimension of the values, default `COLUMNS`
:param value_input_option: controls whether input strings are parsed or not,
default `USER_ENTERED`
:return: operation result
**Examples**
**Robot Framework**
.. code-block:: robotframework
${values} Evaluate [[11, 12, 13], ['aa', 'bb', 'cc']]
${result}= Insert Sheet Values ${SHEET_ID} A:B ${values}
${result}= Insert Sheet Values ${SHEET_ID} A:B ${values} ROWS
"""
resource = {"majorDimension": major_dimension, "values": values}
return (
self.service.spreadsheets()
.values()
.append(
spreadsheetId=sheet_id,
range=sheet_range,
body=resource,
valueInputOption=value_input_option,
)
.execute()
)
@keyword(tags=["sheets"])
def update_sheet_values(
self,
sheet_id: str,
sheet_range: str,
values: list,
major_dimension: str = "COLUMNS",
value_input_option: str = "USER_ENTERED",
) -> Dict:
"""Insert values into sheet cells
:param sheet_id: target sheet
:param sheet_range: target sheet range
:param values: list of values to insert into sheet
:param major_dimension: major dimension of the values, default `COLUMNS`
:param value_input_option: controls whether input strings are parsed or not,
default `USER_ENTERED`
:return: operation result
**Examples**
**Robot Framework**
.. code-block:: robotframework
${row} Evaluate [[22, 33 ,44]]
${result}= Update Sheet Values ${SHEET_ID} A6:C6 ${row} ROWS
"""
resource = {"majorDimension": major_dimension, "values": values}
return (
self.service.spreadsheets()
.values()
.update(
spreadsheetId=sheet_id,
range=sheet_range,
body=resource,
valueInputOption=value_input_option,
)
.execute()
)
@keyword(tags=["sheets"])
def get_sheet_values(
self,
sheet_id: str,
sheet_range: str,
value_render_option: str = "UNFORMATTED_VALUE",
datetime_render_option: str = "FORMATTED_STRING",
) -> List:
"""Get values from the range in the sheet
:param sheet_id: target sheet
:param sheet_range: target sheet range
:param value_render_option: how values should be represented
in the output defaults to "UNFORMATTED_VALUE"
:param datetime_render_option: how dates, times, and durations should be
represented in the output, defaults to "FORMATTED_STRING"
:return: operation result
**Examples**
**Robot Framework**
.. code-block:: robotframework
${values}= Get Sheet Values ${SHEET_ID} A1:C1
""" # noqa: E501
return (
self.service.spreadsheets()
.values()
.get(
spreadsheetId=sheet_id,
range=sheet_range,
valueRenderOption=value_render_option,
dateTimeRenderOption=datetime_render_option,
)
.execute()
)
@keyword(tags=["sheets"])
def clear_sheet_values(self, sheet_id: str, sheet_range: str) -> Dict:
"""Clear cell values for range of cells within a sheet
:param sheet_id: target sheet
:param sheet_range: target sheet range
:return: operation result
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Clear Sheet Values ${SHEET_ID} A1:C1
"""
return (
self.service.spreadsheets()
.values()
.clear(
spreadsheetId=sheet_id,
range=sheet_range,
)
.execute()
)
@keyword(tags=["sheets"])
def copy_sheet(self, sheet_id: str, target_sheet_id: str) -> Dict:
"""Copy spreadsheet to target spreadsheet
*NOTE:* service account user must have access to
target sheet also
:param sheet_id: ID of the sheet to copy
:param target_sheet_id: ID of the target sheet
:return: operation result
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Copy Sheet ${SHEET_ID} ${NEW_SHEET}
"""
body = {
"destination_spreadsheet_id": target_sheet_id,
}
return (
self.service.spreadsheets()
.sheets()
.copyTo(
spreadsheetId=sheet_id,
sheetId=0,
body=body,
)
.execute()
) | /rpaframework_google-7.1.2.tar.gz/rpaframework_google-7.1.2/src/RPA/Cloud/Google/keywords/sheets.py | 0.923691 | 0.323567 | sheets.py | pypi |
import mimetypes
import pickle
from typing import List, Optional
from google.api_core.client_options import ClientOptions
from google.cloud import documentai_v1 as documentai
from . import LibraryContext, keyword
class DocumentAIKeywords(LibraryContext):
"""Keywords for Google Cloud Document AI service.
Added on **rpaframework-google** version: 6.1.1
Google Document AI provides processors for intelligent
document processing (IDP).
To take Document AI into use:
- Create Google Cloud project
- Enable Google Cloud Document AI API for the project
- For Document AI product page, activate desired processors
for the project
"""
def __init__(self, ctx):
super().__init__(ctx)
self.service = None
@keyword(name="Init Document AI", tags=["init", "document ai"])
def init_document_ai(
self,
service_account: Optional[str] = None,
region: Optional[str] = "us",
use_robocorp_vault: Optional[bool] = None,
token_file: Optional[str] = None,
) -> None:
"""Initialize Google Cloud Document AI client
:param service_account: file path to service account file
:param region: region of the service
:param use_robocorp_vault: use credentials in `Robocorp Vault`
:param token_file: file path to token file
Robot Framework example:
.. code-block:: robotframework
# Init using Service Account from a file
Init Document AI ${CURDIR}${/}service_account.json region=eu
# Init using OAuth token from a file and default "us" region
Init Document AI ${CURDIR}${/}token.json
# Init using service account file from the Robocorp Vault
Set Robocorp Vault
... vault_name=DocumentAI
... vault_secret_key=google-sa
Init Document AI region=eu use_robocorp_vault=True
Python example:
.. code-block:: python
GOOGLE = Google()
GOOGLE.set_robocorp_vault("DocumentAI", "google-sa")
GOOGLE.init_document_ai(region="eu", use_robocorp_vault=True)
"""
kwargs = {}
if not region:
raise ValueError("Parameter 'region' needs to point to a service region")
if region.lower() != "us":
opts = ClientOptions(
api_endpoint=f"{region.lower()}-documentai.googleapis.com"
)
kwargs["client_options"] = opts
self.logger.info(f"Using Document AI from '{region.upper()}' region")
self.service = self.init_service_with_object(
documentai.DocumentProcessorServiceClient,
service_account,
use_robocorp_vault,
token_file,
**kwargs,
)
@keyword(tags=["document ai"])
def process_document(
self,
project_id: str,
region: str,
processor_id: str,
file_path: str,
mime_type: Optional[str] = None,
) -> documentai.Document:
"""Process document in the Google Cloud platform
using given document processor ID within given project and
region.
For a full list of Document response object attributes, please reference this
`page <https://cloud.google.com/python/docs/reference/documentai/latest/google.cloud.documentai_v1.types.Document/>`_.
:param project_id: Google Cloud project ID
:param region: Google Cloud region of the processor
:param processor_id: ID of the document processor
:param file_path: filepath of the document to process
:param mime_type: given mime type of document (optional),
if not given it is auto detected
:return: processed document response object
Robot Framework example:
.. code-block:: robotframework
${document}= Process Document
... project_id=${GOOGLE_PROJECT_ID}
... region=eu
... processor_id=${RECEIPT_PROCESSOR_ID}
... file_path=${CURDIR}${/}mydocument.pdf
${entities}= Get Document Entities ${document}
FOR ${ent} IN @{entities}
Log To Console Entity: ${ent}
END
${languages}= Get Document Languages ${document}
Log To Console Languages: ${languages}
Python example:
.. code-block:: python
document = GOOGLE.process_document(
project_id=PROJECT_ID,
region="eu",
processor_id=PROCESSOR_ID,
file_path="./files/mydocument.pdf",
)
entities = GOOGLE.get_document_entities(document)
for ent in entities:
print(ent)
languages = GOOGLE.get_document_languages(document)
for lang in languages:
print(lang)
""" # noqa: E501
name = self.service.processor_path(project_id, region, processor_id)
# Read the file into memory
with open(file_path, "rb") as binary:
binary_content = binary.read()
mime = mime_type or mimetypes.guess_type(file_path)[0]
self.logger.info(f"Processing document '{file_path}' with mimetype '{mime}'")
# Load Binary Data into Document AI RawDocument Object
raw_document = documentai.RawDocument(content=binary_content, mime_type=mime)
# Configure the process request
request = documentai.ProcessRequest(name=name, raw_document=raw_document)
result = self.service.process_document(request=request)
document = result.document
return document
@keyword(tags=["document ai"])
def save_document_response(
self, document: documentai.Document, filepath: str
) -> None:
"""Save ``Process Document`` response into a binary file.
:param document: response document object
:param filepath: target file to save binary object into
Robot Framework example:
.. code-block:: robotframework
${document}= Process Document
... project_id=101134120147
... region=eu
... processor_id=${RECEIPT_PROCESSOR}
... file_path=${file_in}
# save response for later
Save Document Response ${CURDIR}${/}google_processed.response
Python example:
.. code-block:: python
document = GOOGLE.process_document(
project_id=PROJECT_ID,
region="eu",
processor_id=PROCESSOR_ID,
file_path="./files/receipt1.jpg",
)
GOOGLE.save_document_response(document, "receipt.response")
"""
with open(filepath, "wb") as response_file:
pickle.dump(document, response_file)
@keyword(tags=["document ai"])
def load_document_response(self, filepath: str) -> documentai.Document:
"""Loads the binary object saved by ``Save Document Response`` into
``documentai.Document`` format which is accessible by helper keywords.
:param filepath: source file to read binary document object from
:return: processed document response object
Robot Framework example:
.. code-block:: robotframework
# load previously saved response
${document}= Load Document Response ${CURDIR}${/}google_processed.response
${entities}= Get Document Entities ${document}
Python example:
.. code-block:: python
document = GOOGLE.load_document_response("google_doc.response")
entities = GOOGLE.get_document_entities(document)
for ent in entities:
print(ent)
"""
document = None
with open(filepath, "rb") as response_file:
try:
document = pickle.load(response_file)
except pickle.UnpicklingError as err:
raise ValueError(
f"The file {filepath!r} is not 'documentai.Document' type"
) from err
if not isinstance(document, documentai.Document):
raise ValueError(
"The file '%s' is not 'documentai.Document' type" % filepath
)
return document
@keyword(tags=["document ai", "get"])
def get_document_entities(self, document: documentai.Document) -> List:
"""Helper keyword for getting document `entities` from a ``Process Document``
response object.
For examples. see ``Process Document`` keyword
:param document: the document response object
:return: detected entities in the document response as a list
"""
entities = []
for ent in document.entities:
entities.append(
{
"id": ent.id,
"confidence": ent.confidence,
"page": int(ent.page_anchor.page_refs[0].page) + 1,
"type": ent.type_,
"normalized": ent.normalized_value.text,
"text": ent.text_anchor.content,
}
)
return entities
@keyword(tags=["document ai", "get"])
def get_document_languages(self, document: documentai.Document) -> List:
"""Helper keyword for getting detected `languages` from a ``Process Document``
response object.
For examples. see ``Process Document`` keyword
:param document: the document response object
:return: detected languages in the document response as a list
"""
languages = []
for page in document.pages:
for lang in page.detected_languages:
languages.append(
{
"page": page.page_number,
"code": lang.language_code,
"confidence": lang.confidence,
}
)
return languages
@keyword(tags=["document ai"])
def list_processors(self, project_id: str, region: str) -> List:
"""List existing document AI processors from given project and region.
Requires `documentai.processors.list` permission.
:param project_id: Google Cloud project ID
:param region: Google Cloud region of the processor
:return: list of available processors as a list
Robot Framework example:
.. code-block:: robotframework
@{processors}= List Processors ${PROJECT_ID} eu
FOR ${p} IN @{processors}
# name: projects/PROJECT_ID/locations/REGION/processors/PROCESSOR_ID
Log To Console Processor name: ${p.name}
Log To Console Processor type: ${p.type_}
Log To Console Processor display name: ${p.display_name}
END
Python example:
.. code-block:: python
processors = GOOGLE.list_processors(PROJECT_ID, "eu")
for p in processors:
print(f"Processor name: {p.name}")
print(f"Processor type: {p.type_}")
print(f"Processor name: {p.display_name}")
"""
parent_value = self.service.common_location_path(project_id, region)
# Initialize request argument(s)
request = documentai.ListProcessorsRequest(
parent=parent_value,
)
processor_list = self.service.list_processors(request=request)
return processor_list | /rpaframework_google-7.1.2.tar.gz/rpaframework_google-7.1.2/src/RPA/Cloud/Google/keywords/document_ai.py | 0.784526 | 0.262307 | document_ai.py | pypi |
from typing import List, Optional
from google.cloud import texttospeech_v1
from google.cloud.texttospeech_v1.types import (
AudioConfig,
VoiceSelectionParams,
SynthesisInput,
)
from . import (
LibraryContext,
keyword,
)
class TextToSpeechKeywords(LibraryContext):
"""Class for Google Cloud Text-to-Speech API
Link to `Text To Speech PyPI`_ page.
.. _Text To Speech PyPI: https://pypi.org/project/google-cloud-texttospeech/
"""
def __init__(self, ctx):
super().__init__(ctx)
self.service = None
@keyword(tags=["init", "text to speech"])
def init_text_to_speech(
self,
service_account: str = None,
use_robocorp_vault: Optional[bool] = None,
token_file: str = None,
) -> None:
"""Initialize Google Cloud Text to Speech client
:param service_account: file path to service account file
:param use_robocorp_vault: use credentials in `Robocorp Vault`
:param token_file: file path to token file
"""
self.service = self.init_service_with_object(
texttospeech_v1.TextToSpeechClient,
service_account,
use_robocorp_vault,
token_file,
)
@keyword(tags=["text to speech"])
def list_supported_voices(self, language_code: str = None) -> List:
"""List supported voices for the speech
:param language_code: voice languages to list, defaults to None (all)
:return: list of supported voices
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= List Supported Voices en-US
"""
if language_code:
voices = self.service.list_voices(language_code)
else:
voices = self.service.list_voices()
return voices.voices
@keyword(tags=["text to speech"])
def synthesize_speech(
self,
text: str,
language: str = "en-US",
name: str = "en-US-Standard-B",
gender: str = "MALE",
encoding: str = "MP3",
target_file: str = "synthesized.mp3",
) -> List:
"""Synthesize speech synchronously
:param text: input text to synthesize
:param language: voice language, defaults to "en-US"
:param name: voice name, defaults to "en-US-Standard-B"
:param gender: voice gender, defaults to "MALE"
:param encoding: result encoding type, defaults to "MP3"
:param target_file: save synthesized output to file,
defaults to "synthesized.mp3"
:return: synthesized output in bytes
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Synthesize Speech ${text}
"""
synth_input = SynthesisInput(text=text)
voice_selection = VoiceSelectionParams(
language_code=language, name=name, ssml_gender=gender
)
audio_config = AudioConfig(audio_encoding=encoding)
response = self.service.synthesize_speech(
request={
"input": synth_input,
"voice": voice_selection,
"audio_config": audio_config,
}
)
if target_file:
with open(target_file, "wb") as f:
f.write(response.audio_content)
return response.audio_content | /rpaframework_google-7.1.2.tar.gz/rpaframework_google-7.1.2/src/RPA/Cloud/Google/keywords/text_to_speech.py | 0.85341 | 0.16455 | text_to_speech.py | pypi |
from enum import Enum
from google.cloud import language_v1, videointelligence
class TextType(Enum):
"""Possible text types."""
TEXT = language_v1.Document.Type.PLAIN_TEXT
HTML = language_v1.Document.Type.HTML
class UpdateAction(Enum):
"""Possible file update actions."""
trash = 1
untrash = 2
star = 3
unstar = 4
def to_texttype(value):
"""Convert value to TextType enum."""
if isinstance(value, TextType):
return int(value.value)
sanitized = str(value).upper().strip().replace(" ", "_")
try:
return int(TextType[sanitized].value)
except KeyError as err:
raise ValueError(f"Unknown text type: {value}") from err
class VideoFeature(Enum):
"""Possible video features."""
FEATURE_UNSPECIFIED = videointelligence.Feature.FEATURE_UNSPECIFIED
LABEL_DETECTION = videointelligence.Feature.LABEL_DETECTION
SHOT_CHANGE_DETECTION = videointelligence.Feature.SHOT_CHANGE_DETECTION
EXPLICIT_CONTENT_DETECTION = videointelligence.Feature.EXPLICIT_CONTENT_DETECTION
SPEECH_TRANSCRIPTION = videointelligence.Feature.SPEECH_TRANSCRIPTION
TEXT_DETECTION = videointelligence.Feature.TEXT_DETECTION
OBJECT_TRACKING = videointelligence.Feature.OBJECT_TRACKING
LOGO_RECOGNITION = videointelligence.Feature.LOGO_RECOGNITION
def to_feature(value):
"""Convert value to VideoFeature enum."""
if isinstance(value, VideoFeature):
return int(value.value)
sanitized = str(value).upper().strip().replace(" ", "_")
try:
return int(VideoFeature[sanitized].value)
except KeyError as err:
raise ValueError(f"Unknown video feature: {value}") from err
class DriveRole(Enum):
"""Possible Drive user roles"""
OWNER = "owner"
ORGANIZER = "organizer"
FILE_ORGANIZER = "fileOrganizer"
WRITER = "writer"
COMMENTER = "commenter"
READER = "reader"
def to_drive_role(value):
"""Convert value to DriveRole enum."""
if isinstance(value, DriveRole):
return value.value
sanitized = str(value).upper().strip().replace(" ", "_")
try:
return DriveRole[sanitized].value
except KeyError as err:
raise ValueError(f"Unknown drive role: {value}") from err
class DriveType(Enum):
"""Possible Drive Share types"""
USER = "user"
GROUP = "group"
DOMAIN = "domain"
ANY = "anyone"
def to_drive_type(value):
"""Convert value to DriveType enum."""
if isinstance(value, DriveType):
return value.value
sanitized = str(value).upper().strip().replace(" ", "_")
try:
return DriveType[sanitized].value
except KeyError as err:
raise ValueError(f"Unknown drive type: {value}") from err | /rpaframework_google-7.1.2.tar.gz/rpaframework_google-7.1.2/src/RPA/Cloud/Google/keywords/enums.py | 0.606615 | 0.284393 | enums.py | pypi |
from typing import Any, Dict, List, Optional
from google.cloud import storage
from . import (
LibraryContext,
keyword,
)
class StorageKeywords(LibraryContext):
"""Class for Google Cloud Storage API
and Google Cloud Storage JSON API
Link to `Google Storage PyPI`_ page.
.. _Google Storage PyPI: https://pypi.org/project/google-cloud-storage/
"""
def __init__(self, ctx):
super().__init__(ctx)
self.service = None
@keyword(tags=["init", "storage"])
def init_storage(
self,
service_account: str = None,
use_robocorp_vault: Optional[bool] = None,
token_file: str = None,
) -> None:
"""Initialize Google Cloud Storage client
:param service_account: file path to service account file
:param use_robocorp_vault: use credentials in `Robocorp Vault`
:param token_file: file path to token file
"""
self.service = self.init_service_with_object(
storage.Client, service_account, use_robocorp_vault, token_file
)
@keyword(tags=["storage"])
def create_storage_bucket(self, bucket_name: str) -> Dict:
"""Create Google Cloud Storage bucket
:param bucket_name: name as string
:return: bucket
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Create Storage Bucket visionfolder
"""
bucket = self.service.create_bucket(bucket_name)
return bucket
@keyword(tags=["storage"])
def delete_storage_bucket(self, bucket_name: str):
"""Delete Google Cloud Storage bucket
Bucket needs to be empty before it can be deleted.
:param bucket_name: name as string
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Delete Storage Bucket visionfolder
"""
bucket = self.get_storage_bucket(bucket_name)
try:
bucket.delete()
except Exception as e:
raise ValueError("The bucket you tried to delete was not empty") from e
@keyword(tags=["storage"])
def get_storage_bucket(self, bucket_name: str) -> Dict:
"""Get Google Cloud Storage bucket
:param bucket_name: name as string
:return: bucket
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Get Bucket visionfolder
"""
bucket = self.service.get_bucket(bucket_name)
return bucket
@keyword(tags=["storage"])
def list_storage_buckets(self) -> List:
"""List Google Cloud Storage buckets
:return: list of buckets
**Examples**
**Robot Framework**
.. code-block:: robotframework
${buckets}= List Storage Buckets
FOR ${bucket} IN @{buckets}
Log ${bucket}
END
"""
return list(self.service.list_buckets())
@keyword(tags=["storage"])
def delete_storage_files(self, bucket_name: str, files: Any) -> List:
"""Delete files in the bucket
Files need to be object name in the bucket.
:param bucket_name: name as string
:param files: single file, list of files or comma separated list of files
:return: list of files which could not be deleted
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Delete Storage Files ${BUCKET_NAME} file1,file2
"""
if not isinstance(files, list):
files = files.split(",")
bucket = self.get_storage_bucket(bucket_name)
notfound = []
for filename in files:
filename = filename.strip()
blob = bucket.get_blob(filename)
if blob:
blob.delete()
else:
notfound.append(filename)
return notfound if len(notfound) > 0 else True
@keyword(tags=["storage"])
def list_storage_files(self, bucket_name: str) -> List:
"""List files in the bucket
:param bucket_name: name as string
:return: list of object names in the bucket
**Examples**
**Robot Framework**
.. code-block:: robotframework
${files}= List Storage Files ${BUCKET_NAME}
FOR ${bucket} IN @{files}
Log ${file}
END
"""
bucket = self.get_storage_bucket(bucket_name)
all_blobs = bucket.list_blobs()
sorted_blobs = sorted(blob.name for blob in all_blobs)
return [
{"name": name, "uri": f"gs://{bucket_name}/{name}"} for name in sorted_blobs
]
@keyword(tags=["storage"])
def upload_storage_file(
self, bucket_name: str, filename: str, target_name: str
) -> None:
"""Upload a file into a bucket
:param bucket_name: name as string
:param filename: filepath to upload file
:param target_name: target object name
**Examples**
**Robot Framework**
.. code-block:: robotframework
Upload Storage File ${BUCKET_NAME}
... ${CURDIR}${/}test.txt test.txt
"""
bucket = self.get_storage_bucket(bucket_name)
blob = bucket.blob(target_name)
with open(filename, "rb") as f:
blob.upload_from_file(f)
@keyword(tags=["storage"])
def upload_storage_files(self, bucket_name: str, files: dict) -> None:
"""Upload files into a bucket
Example `files`:
files = {"mytestimg": "image1.png", "mydoc": "google.pdf"}
:param bucket_name: name as string
:param files: dictionary of object names and filepaths
**Examples**
**Robot Framework**
.. code-block:: robotframework
${files}= Create Dictionary
... test1.txt ${CURDIR}${/}test1.txt
... test2.txt ${CURDIR}${/}test2.txt
Upload Storage Files ${BUCKET_NAME} ${files}
"""
if not isinstance(files, dict):
raise ValueError("files needs to be an dictionary")
bucket = self.get_storage_bucket(bucket_name)
for target_name, filename in files.items():
blob = bucket.blob(target_name)
blob.upload_from_filename(filename)
@keyword(tags=["storage"])
def download_storage_files(self, bucket_name: str, files: Any) -> List:
"""Download files from a bucket
Example `files`:
files = {"mytestimg": "image1.png", "mydoc": "google.pdf"}
:param bucket_name: name as string
:param files: list of object names or dictionary of
object names and target files
:return: list of files which could not be downloaded
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Download Storage Files ${BUCKET_NAME} test1.txt,test2.txt
"""
if isinstance(files, str):
files = files.split(",")
bucket = self.get_storage_bucket(bucket_name)
notfound = []
if isinstance(files, dict):
for object_name, filename in files.items():
blob = bucket.get_blob(object_name)
if blob:
with open(filename, "wb") as f:
blob.download_to_file(f)
self.logger.info(
"Downloaded object %s from Google to filepath %s",
object_name,
filename,
)
else:
notfound.append(object_name)
else:
for filename in files:
filename = filename.strip()
blob = bucket.get_blob(filename)
if blob:
with open(filename, "wb") as f:
blob.download_to_file(f)
self.logger.info(
"Downloaded object %s from Google to filepath %s",
filename,
filename,
)
else:
notfound.append(filename)
return notfound | /rpaframework_google-7.1.2.tar.gz/rpaframework_google-7.1.2/src/RPA/Cloud/Google/keywords/storage.py | 0.888002 | 0.319267 | storage.py | pypi |
import base64
import mimetypes
import os
from pathlib import Path
from typing import Optional
from email.mime.application import MIMEApplication
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from googleapiclient import errors
from . import LibraryContext, keyword
def get_size_format(b, factor=1024, suffix="B"):
"""
Scale bytes to its proper byte format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if b < factor:
return f"{b:.2f}{unit}{suffix}"
b /= factor
return f"{b:.2f}Y{suffix}"
def clean(text):
# clean text for creating a folder
return "".join(c if c.isalnum() else "_" for c in text)
class GmailKeywords(LibraryContext):
"""Class for Google Gmail API
**Note:** The Gmail API does not work with _service accounts_
For more information about Google Gmail API link_.
.. _link: https://developers.google.com/gmail/api
"""
def __init__(self, ctx):
super().__init__(ctx)
self.service = None
@keyword(tags=["init", "gmail"])
def init_gmail(
self,
service_account: str = None,
credentials: str = None,
use_robocorp_vault: Optional[bool] = None,
scopes: list = None,
token_file: str = None,
) -> None:
"""Initialize Google Gmail client
:param service_account: file path to service account file
:param credentials: file path to credentials file
:param use_robocorp_vault: use credentials in `Robocorp Vault`
:param scopes: list of extra authentication scopes
:param token_file: file path to token file
"""
gmail_scopes = ["gmail.send", "gmail.compose", "gmail.modify", "gmail.labels"]
if scopes:
gmail_scopes = scopes
self.service = self.init_service(
service_name="gmail",
api_version="v1",
scopes=gmail_scopes,
service_account_file=service_account,
credentials_file=credentials,
use_robocorp_vault=use_robocorp_vault,
token_file=token_file,
)
def create_message(
self,
to: str,
subject: str,
message_text: str,
attachments: list = None,
):
"""Create a message for an email.
:param to: message recipient
:param subject: message subject
:param message_text: message body text
:param attachment: list of files to add as message attachments
:return: An object containing a base64url encoded email object
"""
mimeMessage = MIMEMultipart()
mimeMessage["to"] = to
mimeMessage["subject"] = subject
mimeMessage.attach(MIMEText(message_text, "plain"))
for at in attachments:
self.add_attachment_to_message(mimeMessage, at)
return {"raw": base64.urlsafe_b64encode(mimeMessage.as_bytes()).decode()}
def add_attachment_to_message(self, mimeMessage, attachment):
content_type, encoding = mimetypes.guess_type(attachment)
if content_type is None or encoding is not None:
content_type = "application/octet-stream"
main_type, sub_type = content_type.split("/", 1)
self.logger.debug(
f"Adding attachment of main_type: {main_type} and sub_type: {sub_type}"
)
mime_type_mapping = {
"text": MIMEText,
"image": MIMEImage,
"audio": MIMEAudio,
"application": MIMEApplication,
}
read_mode = "r" if main_type == "text" else "rb"
with open(attachment, read_mode) as fp: # pylint: disable=unspecified-encoding
mime_class = mime_type_mapping.get(main_type, MIMEBase)
msg = mime_class(fp.read(), _subtype=sub_type)
filename = os.path.basename(attachment)
msg.add_header("Content-Disposition", "attachment", filename=filename)
mimeMessage.attach(msg)
@keyword(tags=["gmail"])
def send_message(
self,
sender: str,
to: str,
subject: str,
message_text: str,
attachments: list = None,
):
"""Send an email message.
:param sender: message sender
:param to: message recipient
:param subject: message subject
:param message_text: message body text
:param attachment: list of files to add as message attachments
:return: sent message
Example:
.. code-block:: robotframework
${attachments}= Create List
... ${CURDIR}${/}random.txt
... ${CURDIR}${/}source.png
Send Message me
... mika@robocorp.com
... message subject
... body of the message
... ${attachments}
"""
if not self.service:
raise AssertionError("Gmail service has not been initialized")
attachments = attachments or []
message = self.create_message(to, subject, message_text, attachments)
try:
response = (
self.service.users()
.messages()
.send(userId=sender, body=message)
.execute()
)
self.logger.debug("Message Id: %s" % response["id"])
except errors.HttpError as he:
self.logger.warning(str(he))
raise he
return response
def set_list_parameters(self, user_id, query, label_ids, max_results, include_spam):
parameters = {"userId": user_id, "q": query}
if label_ids:
parameters["labelIds"] = ",".join(label_ids)
if max_results:
parameters["maxResults"] = max_results
if include_spam:
parameters["includeSpamTrash"] = include_spam
return parameters
def set_headers_to_message_dict(self, payload, message_id, response):
headers = payload.get("headers")
message_dict = {"id": message_id, "label_ids": response["labelIds"]}
for header in headers:
name = header.get("name")
value = header.get("value")
if name.lower() == "from":
message_dict["from"] = value
if name.lower() == "to":
message_dict["to"] = value
if name.lower() == "subject":
message_dict["subject"] = value
if name.lower() == "date":
message_dict["date"] = value
return message_dict
def handle_mimetypes(self, parsed_parts, part, msg, folder_name):
filename = part.get("filename")
mimetype = part.get("mimeType")
body = part.get("body")
data = body.get("data")
filesize = body.get("size")
part_headers = part.get("headers")
if mimetype == "text/plain":
if data:
text = base64.urlsafe_b64decode(data).decode()
parsed_parts.append({"text/plain": text})
elif mimetype == "text/html":
if not filename:
filename = "message.html"
filepath = os.path.join(folder_name, filename)
with open(filepath, "wb") as f:
data = base64.urlsafe_b64decode(data)
parsed_parts.append({"text/html": data, "path": filepath})
f.write(data)
else:
for part_header in part_headers:
part_header_name = part_header.get("name")
part_header_value = part_header.get("value")
if part_header_name == "Content-Disposition":
if "attachment" in part_header_value:
# we get the attachment ID
# and make another request to get the attachment itself
self.logger.info(
"Saving the file: %s, size:%s"
% (filename, get_size_format(filesize))
)
attachment_id = body.get("attachmentId")
attachment = (
self.service.users()
.messages()
.attachments()
.get(
id=attachment_id,
userId="me",
messageId=msg["id"],
)
.execute()
)
data = attachment.get("data")
filepath = os.path.join(folder_name, filename)
if data:
parsed_parts.append(
{"attachment": filepath, "id": attachment_id}
)
with open(filepath, "wb") as f:
f.write(base64.urlsafe_b64decode(data))
@keyword(tags=["gmail"])
def list_messages(
self,
user_id: str,
query: str,
folder_name: str = None,
label_ids: list = None,
max_results: int = None,
include_json: bool = False,
include_spam: bool = False,
):
"""List messages
:param user_id: user's email address. The special value me can
be used to indicate the authenticated user.
:param query: message query
:param folder_name: path where attachments are saved, default current
directory
:param label_ids: message label ids
:param max_results: maximum number of message to return
:param include_json: include original response json
:param include_spam: include messages from SPAM and TRASH
:return: messages
Example:
.. code-block:: robotframework
${messages}= List Messages me
... from:mika@robocorp.com
... folder_name=${CURDIR}${/}target
... include_json=True
FOR ${msg} IN @{messages}
Log Many ${msg}
END
"""
parameters = self.set_list_parameters(
user_id, query, label_ids, max_results, include_spam
)
folder_name = Path(folder_name) if folder_name else Path().absolute()
messages = []
try:
response = self.service.users().messages().list(**parameters).execute()
message_ids = [
m["id"] for m in response["messages"] if "messages" in response.keys()
]
for message_id in message_ids:
response = (
self.service.users()
.messages()
.get(userId=user_id, id=message_id)
.execute()
)
payload = response["payload"]
message_dict = self.set_headers_to_message_dict(
payload, message_id, response
)
if include_json:
message_dict["json"] = response
parts = payload.get("parts")
parsed_parts = self.parse_parts(
message_id, response, parts, folder_name
)
message_dict["parts"] = parsed_parts
messages.append(message_dict)
except errors.HttpError as he:
self.logger.warning(str(he))
raise he
return messages
def parse_parts(self, msg_id, msg, parts, folder_name):
"""
Utility function that parses the content of an email partition
"""
if msg_id and msg_id not in str(folder_name):
try:
folder_name = folder_name / msg_id
folder_name.mkdir(parents=True, exist_ok=True)
except FileExistsError:
pass
parsed_parts = []
if parts:
for part in parts:
if part.get("parts"):
# recursively call this function when we see that a part
# has parts inside
self.parse_parts(None, msg, part.get("parts"), folder_name)
self.handle_mimetypes(parsed_parts, part, msg, folder_name)
return parsed_parts | /rpaframework_google-7.1.2.tar.gz/rpaframework_google-7.1.2/src/RPA/Cloud/Google/keywords/gmail.py | 0.741206 | 0.164483 | gmail.py | pypi |
from typing import Dict, Optional
from google.cloud import language_v1
from . import LibraryContext, keyword, TextType, to_texttype
class NaturalLanguageKeywords(LibraryContext):
"""Keywords for Google Cloud Natural Language API"""
def __init__(self, ctx):
super().__init__(ctx)
self.service = None
@keyword(tags=["init", "natural language"])
def init_natural_language(
self,
service_account: str = None,
use_robocorp_vault: Optional[bool] = None,
token_file: str = None,
) -> None:
"""Initialize Google Cloud Natural Language client
:param service_account: file path to service account file
:param use_robocorp_vault: use credentials in `Robocorp Vault`
:param token_file: file path to token file
"""
self.service = self.init_service_with_object(
language_v1.LanguageServiceClient,
service_account,
use_robocorp_vault,
token_file,
)
@keyword(tags=["natural language"])
def analyze_sentiment(
self,
text: str = None,
text_file: str = None,
file_type: TextType = TextType.TEXT,
json_file: str = None,
lang: str = None,
) -> Dict:
"""Analyze sentiment in a text file
:param text: source text
:param text_file: source text file
:param file_type: type of text, PLAIN_TEXT (default) or HTML
:param json_file: json target to save result, defaults to None
:param lang: language code of the source, defaults to None
:return: analysis response
# For list of supported languages:
# https://cloud.google.com/natural-language/docs/languages
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Analyze Sentiment ${text}
${result}= Analyze Sentiment text_file=${CURDIR}${/}test.txt
"""
return self._analyze_handler(
text, text_file, file_type, json_file, lang, "sentiment"
)
@keyword(tags=["natural language"])
def classify_text(
self,
text: str = None,
text_file: str = None,
file_type: TextType = TextType.TEXT,
json_file: str = None,
lang: str = None,
) -> Dict:
"""Classify text
:param text: source text
:param text_file: source text file
:param file_type: type of text, PLAIN_TEXT (default) or HTML
:param json_file: json target to save result, defaults to None
:param lang: language code of the source, defaults to None
:return: classify response
# For list of supported languages:
# https://cloud.google.com/natural-language/docs/languages
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Classify Text ${text}
${result}= Classify Text text_file=${CURDIR}${/}test.txt
"""
return self._analyze_handler(
text, text_file, file_type, json_file, lang, "classify"
)
def _analyze_handler(
self, text, text_file, file_type, json_file, lang, analyze_method
):
file_type = to_texttype(file_type)
parameters = {"type_": file_type}
if text:
parameters["content"] = text
elif text_file:
with open(text_file, "r") as f: # pylint: disable=unspecified-encoding
parameters["content"] = f.read()
else:
raise AttributeError("Either 'text' or 'text_file' must be given")
if lang is not None:
parameters["language"] = lang
document = language_v1.Document(**parameters)
if analyze_method == "classify":
response = self.service.classify_text(document=document)
elif analyze_method == "sentiment":
# Available values: NONE, UTF8, UTF16, UTF32
# encoding_type = enums.EncodingType.UTF8
response = self.service.analyze_sentiment(
document=document, encoding_type="UTF8"
)
self.write_json(json_file, response)
return response | /rpaframework_google-7.1.2.tar.gz/rpaframework_google-7.1.2/src/RPA/Cloud/Google/keywords/natural_language.py | 0.873458 | 0.194444 | natural_language.py | pypi |
from typing import Optional
from . import (
LibraryContext,
keyword,
)
class AppsScriptKeywords(LibraryContext):
"""Class for Google Apps Script API
For more information about Google Apps Script API link_.
.. _link: https://developers.google.com/apps-script/api
"""
def __init__(self, ctx):
super().__init__(ctx)
self.service = None
@keyword(tags=["init", "apps script"])
def init_apps_script(
self,
service_account: str = None,
credentials: str = None,
use_robocorp_vault: Optional[bool] = None,
scopes: list = None,
token_file: str = None,
) -> None:
"""Initialize Google Apps Script client
:param service_account: file path to service account file
:param credentials: file path to credentials file
:param use_robocorp_vault: use credentials in `Robocorp Vault`
:param scopes: list of extra authentication scopes
:param token_file: file path to token file
"""
apps_scopes = ["script.projects", "drive.scripts", "script.external_request"]
if scopes:
apps_scopes += scopes
self.service = self.init_service(
service_name="script",
api_version="v1",
scopes=apps_scopes,
service_account_file=service_account,
credentials_file=credentials,
use_robocorp_vault=use_robocorp_vault,
token_file=token_file,
)
@keyword(tags=["apps script"])
def run_script(
self, script_id: str, function_name: str, parameters: dict = None
) -> None:
"""Run the Google Apps Script function
:param script_id: Google Script identifier
:param function_name: name of the script function
:param parameters: script function parameters as a dictionary
:raises AssertionError: thrown when Google Script returns errors
Example:
.. code-block:: robotframework
&{params}= Create Dictionary formid=aaad4232 formvalues=1,2,3
${response}= Run Script abc21397283712da submit_form ${params}
Log Many ${response}
"""
request = {
"function": function_name,
}
if parameters:
request["parameters"] = [parameters]
response = (
self.service.scripts()
.run(
body=request,
scriptId=script_id,
)
.execute()
)
if "error" in response.keys():
raise AssertionError(response["error"])
return response | /rpaframework_google-7.1.2.tar.gz/rpaframework_google-7.1.2/src/RPA/Cloud/Google/keywords/apps_script.py | 0.914668 | 0.159414 | apps_script.py | pypi |
from typing import Dict, Optional
from google.cloud import videointelligence
from . import LibraryContext, keyword, to_feature
class VideoIntelligenceKeywords(LibraryContext):
"""Keywords for Google Video Intelligence API"""
def __init__(self, ctx):
super().__init__(ctx)
self.service = None
@keyword(tags=["init", "video intelligence"])
def init_video_intelligence(
self,
service_account: str = None,
use_robocorp_vault: Optional[bool] = None,
token_file: str = None,
) -> None:
"""Initialize Google Cloud Video Intelligence client
:param service_account: file path to service account file
:param use_robocorp_vault: use credentials in `Robocorp Vault`
:param token_file: file path to token file
"""
self.service = self.init_service_with_object(
videointelligence.VideoIntelligenceServiceClient,
service_account,
use_robocorp_vault,
token_file,
)
@keyword(tags=["video intelligence"])
def annotate_video(
self,
video_file: str = None,
video_uri: str = None,
features: str = None,
output_uri: str = None,
json_file: str = None,
timeout: int = 300,
) -> Dict:
"""Annotate video
Possible values for features:
- FEATURE_UNSPECIFIED, Unspecified.
- LABEL_DETECTION, Label detection. Detect objects, such as dog or flower.
- SHOT_CHANGE_DETECTION, Shot change detection.
- EXPLICIT_CONTENT_DETECTION, Explicit content detection.
- SPEECH_TRANSCRIPTION, Speech transcription.
- TEXT_DETECTION, OCR text detection and tracking.
- OBJECT_TRACKING, Object detection and tracking.
- LOGO_RECOGNITION, Logo detection, tracking, and recognition.
If `video_uri` is given then that is used even if `video_file` is given.
:param video_file: local file path to input video
:param video_uri: Google Cloud Storage URI to input video
:param features: list of annotation features to detect,
defaults to LABEL_DETECTION,SHOT_CHANGE_DETECTION
:param output_uri: Google Cloud Storage URI to store response json
:param json_file: json target to save result
:param timeout: timeout for operation in seconds
:return: annotate result
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Annotate Video video_uri=gs://videointelligence/movie.mp4
... features=TEXT_DETECTION,LABEL_DETECTION
... output_uri=gs://videointelligence/movie_annotations.json
... json_file=${CURDIR}${/}videoannotations.json
"""
if features is None:
features_in = [
videointelligence.Feature.LABEL_DETECTION,
videointelligence.Feature.SHOT_CHANGE_DETECTION,
]
else:
features_in = [to_feature(feature) for feature in features.split(",")]
parameters = {"features": features_in}
if video_uri:
parameters["input_uri"] = video_uri
elif video_file:
video_context = videointelligence.VideoContext()
with open(video_file, "rb") as file:
input_content = file.read()
parameters["input_content"] = input_content
parameters["video_context"] = video_context
if output_uri:
parameters["output_uri"] = output_uri
operation = self.service.annotate_video(request=parameters)
result = operation.result(timeout=timeout)
self.write_json(json_file, result)
return result | /rpaframework_google-7.1.2.tar.gz/rpaframework_google-7.1.2/src/RPA/Cloud/Google/keywords/video_intelligence.py | 0.886746 | 0.219045 | video_intelligence.py | pypi |
from typing import Dict, Optional
from google.cloud import speech
from google.cloud.speech_v1.types import RecognitionConfig, RecognitionAudio
from . import (
LibraryContext,
keyword,
)
ENCODING = {
"AMR": RecognitionConfig.AudioEncoding.AMR,
"AMR_WB": RecognitionConfig.AudioEncoding.AMR_WB,
"FLAC": RecognitionConfig.AudioEncoding.FLAC,
"LINEAR16": RecognitionConfig.AudioEncoding.LINEAR16,
"MULAW": RecognitionConfig.AudioEncoding.MULAW,
"OGG": RecognitionConfig.AudioEncoding.OGG_OPUS,
"SPEEX": RecognitionConfig.AudioEncoding.SPEEX_WITH_HEADER_BYTE, # noqa: E501 # pylint: disable=C0301
"UNSPECIFIED": RecognitionConfig.AudioEncoding.ENCODING_UNSPECIFIED, # noqa: E501 # pylint: disable=C0301
}
class SpeechToTextKeywords(LibraryContext):
"""Class for Google Cloud Speech-To-Text API
Possible input audio encodings:
- 'AMR'
- 'AMR_WB'
- 'ENCODING_UNSPECIFIED'
- 'FLAC'
- 'LINEAR16'
- 'MULAW'
- 'OGG_OPUS'
- 'SPEEX_WITH_HEADER_BYTE'
Link to `Speech To Text PyPI`_ page.
.. _Speech To Text PyPI: https://pypi.org/project/google-cloud-speech/
"""
def __init__(self, ctx):
super().__init__(ctx)
self.service = None
@keyword(tags=["init", "speech to text"])
def init_speech_to_text(
self,
service_account: str = None,
use_robocorp_vault: Optional[bool] = None,
token_file: str = None,
) -> None:
"""Initialize Google Cloud Speech to Text client
:param service_account: file path to service account file
:param use_robocorp_vault: use credentials in `Robocorp Vault`
:param token_file: file path to token file
"""
self.service = self.init_service_with_object(
speech.SpeechClient, service_account, use_robocorp_vault, token_file
)
@keyword(tags=["speech to text"])
def recognize_text_from_audio(
self,
audio_file: str = None,
audio_uri: str = None,
encoding: str = None,
language_code: str = "en_US",
audio_channel_count: int = 2,
sample_rate: int = None,
) -> Dict:
"""Recognize text in the audio file
:param audio_file: local audio file path
:param audio_uri: Google Cloud Storage URI
:param encoding: audio file encoding
:param language_code: language in the audio
:param audio_channel_count: number of audio channel
:param sample_rate: rate in hertz, for example 16000
:return: recognized texts
**Examples**
**Robot Framework**
.. code-block:: robotframework
${result}= Recognize Text From Audio audio_file=${CURDIR}${/}test.mp3
"""
audio = self.set_audio_type(audio_file, audio_uri)
parameters = {"use_enhanced": True}
# audio_encoding = ENCODING["UNSPECIFIED"]
if encoding and encoding.upper() in ENCODING.keys():
parameters["encoding"] = ENCODING[encoding.upper()]
if sample_rate:
parameters["sample_rate_hertz"] = sample_rate
if language_code:
parameters["language_code"] = language_code
if audio_channel_count:
parameters["audio_channel_count"] = audio_channel_count
config = RecognitionConfig(**parameters) # pylint: disable=E1101
rec = self.service.recognize(config=config, audio=audio)
return rec.results
def set_audio_type(self, audio_file, audio_uri):
# flac or wav, does not require encoding type
if audio_file:
with open(audio_file, "rb") as f:
content = f.read()
return RecognitionAudio(content=content) # pylint: disable=E1101
elif audio_uri:
return RecognitionAudio(uri=audio_uri) # pylint: disable=E1101
else:
raise KeyError("'audio_file' or 'audio_uri' is required") | /rpaframework_google-7.1.2.tar.gz/rpaframework_google-7.1.2/src/RPA/Cloud/Google/keywords/speech_to_text.py | 0.869452 | 0.217712 | speech_to_text.py | pypi |
import logging
from typing import Optional, List
import openai
class OpenAI:
"""Library to support `OpenAI <https://openai.com>`_ and `Azure OpenAI <https://learn.microsoft.com/en-us/azure/cognitive-services/openai/overview>`_ services.
Library is **not** included in the `rpaframework` package, so in order to use it
you have to add `rpaframework-openai` with the desired version in your
*conda.yaml* file.
**Robot Framework example usage**
.. code-block:: robotframework
*** Settings ***
Library RPA.Robocorp.Vault
Library RPA.OpenAI
*** Tasks ***
Create a text completion
${secrets} Get Secret secret_name=OpenAI
Authorize To OpenAI api_key=${secrets}[key]
${completion} Completion Create
... Write a tagline for an ice cream shop
... temperature=0.6
Log ${completion}
**Python example usage**
.. code-block:: python
from RPA.Robocorp.Vault import Vault
from RPA.OpenAI import OpenAI
secrets = Vault().get_secret("OpenAI")
baselib = OpenAI()
baselib.authorize_to_openai(secrets["key"])
result = baselib.completion_create(
Create a tagline for icecream shop',
temperature=0.6,
)
print(result)
""" # noqa: E501
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self) -> None:
self.logger = logging.getLogger(__name__)
self.service_type = "OpenAI"
def authorize_to_azure_openai(
self,
api_key: str,
api_base: str,
api_type: Optional[str] = "azure",
api_version: Optional[str] = "2023-05-15",
) -> None:
"""Keyword for authorize to Azure OpenAI.
:param api_key: Your Azure OpenAI API key
:param api_base: Your Endpoint URL. Example: https://docs-test-001.openai.azure.com/
:param api_type: "azure"
:param api_version: "2023-05-15"
Robot Framework example:
.. code-block:: robotframework
${secrets} Get Secret secret_name=AzureOpenAI
Authorize To Azure Openai
... api_key=${secrets}[api_key]
... api_base=${secrets}[api_base]
... api_type=azure
... api_version=2023-05-15
Python example:
.. code-block:: python
secrets = Vault().get_secret("AzureOpenAI")
baselib = OpenAI()
baselib.authorize_to_azure_openai(
secrets["api_key"],
secrets["api_base"],
"azure",
"2023-05-15"
)
""" # noqa: E501
openai.api_key = api_key
openai.api_base = api_base
openai.api_type = api_type
openai.api_version = api_version
self.service_type = "Azure"
def authorize_to_openai(self, api_key: str) -> None:
"""Keyword for authorize to OpenAI with your API key obtained from your account.
:param api_key: Your OpenAI API key
Robot Framework example:
.. code-block:: robotframework
${secrets} Get Secret secret_name=OpenAI
Authorize To OpenAI api_key=${secrets}[key]
Python example:
.. code-block:: python
secrets = Vault().get_secret("OpenAI")
baselib = OpenAI()
baselib.authorize_to_openai(secrets["key"])
"""
openai.api_key = api_key
def completion_create(
self,
prompt: str,
model: Optional[str] = "text-davinci-003",
temperature: Optional[int] = 0.7,
max_tokens: Optional[int] = 256,
top_probability: Optional[int] = 1,
frequency_penalty: Optional[int] = 0,
presence_penalty: Optional[int] = 0,
result_format: Optional[str] = "string",
) -> None:
"""Keyword for creating text completions in OpenAI and Azure OpenAI.
Keyword returns a text string.
**Note**. When using ``Azure OpenAI`` you must provide the ``deployment_name``
as the ``model`` parameter instead of the model ID used with ``OpenAI``.
:param prompt: Text submitted to OpenAI for creating natural language.
:param model: For ``OpenAI`` the ID of the model to use, e.g. ``text-davinci-003``.
For ``Azure OpenAI`` the Deployment name, e.g. ``myDavinci3deployment``.
:param temperature: What sampling temperature to use.
Higher values means the model will take more risks..
:param max_tokens: The maximum number of tokens to generate in the completion..
:param top_probability: Controls diversity via nucleus sampling. 0.5 means half
of all likelihood-weighted options are considered.
:param frequency_penalty: Number between -2.0 and 2.0. Positive values penalize
new tokens based on their existing frequency in the text so far.
:param presence_penalty: Number between -2.0 and 2.0. Positive values penalize
new tokens based on whether they appear in the text so far.
:param result_format: Result format (string / json). Return just a string or
the default JSON response.
Robot Framework example:
.. code-block:: robotframework
${response} Completion Create
... Write a tagline for an icecream shop.
... temperature=0.6
Log ${response}
Python example:
.. code-block:: python
result = baselib.completion_create(
'Create a tagline for icecream shop',
temperature=0.6,
)
print(result)
""" # noqa: E501
parameters = {
"prompt": prompt,
"temperature": temperature,
"max_tokens": max_tokens,
"top_p": top_probability,
"frequency_penalty": frequency_penalty,
"presence_penalty": presence_penalty,
}
if self.service_type == "Azure":
parameters["engine"] = model
else:
parameters["model"] = model
response = openai.Completion.create(**parameters)
self.logger.info(response)
if result_format == "string":
text = response["choices"][0]["text"].strip()
return text
if result_format == "json":
return response
else:
return None
def chat_completion_create(
self,
user_content: str = None,
conversation: Optional[List] = None,
model: Optional[str] = "gpt-3.5-turbo",
system_content: Optional[str] = None,
temperature: Optional[int] = 1,
top_probability: Optional[int] = 1,
frequency_penalty: Optional[int] = 0,
presence_penalty: Optional[int] = 0,
) -> None:
"""Keyword for creating ChatGPT text completions using OpenAI or Azure OpenAI.
Keyword returns the response as a string and the message history as a list.
**Note**. When using ``Azure OpenAI`` you must provide the ``deployment_name``
as the ``model`` parameter instead of the model ID used with ``OpenAI``.
:param user_content: Text submitted to ChatGPT to generate completions.
:param conversation: List containing the conversation to be continued. Leave
empty for a new conversation.
:param model: For ``OpenAI`` the ID of the model to use, e.g. ``gpt-4``
or ``gpt-3.5-turbo``. For ``Azure OpenAI`` the Deployment name,
e.g. ``myGPT4deployment``.
:param system_content: The system message helps set the behavior of
the assistant.
:param temperature: What sampling temperature to use between 0 to 2. Higher
values means the model will take more risks.
:param top_probability: An alternative to sampling with temperature, called
nucleus sampling, where the model considers the results of the tokens with
top_p probability mass.
:param frequency_penalty: Number between -2.0 and 2.0. Positive values penalize
new tokens based on their existing frequency in the text so far.
:param presence_penalty: Number between -2.0 and 2.0. Positive values penalize
new tokens based on whether they appear in the text so far.
Robot Framework example:
.. code-block:: robotframework
# Get response without conversation history.
${response} @{chatgpt_conversation}= Chat Completion Create
... user_content=What is the biggest mammal?
Log ${response}
# Continue the conversation by using the "conversation" argument.
${response} @{chatgpt_conversation}= Chat Completion Create
... conversation=${chatgpt_conversation}
... user_content=How old can it live?
Log ${response}
"""
if conversation is not None:
conversation = conversation[0]
else:
conversation = []
if system_content is not None:
conversation.append(
{"role": "system", "content": system_content},
)
conversation.append(
{"role": "user", "content": user_content},
)
parameters = {
"messages": conversation,
"temperature": temperature,
"top_p": top_probability,
"frequency_penalty": frequency_penalty,
"presence_penalty": presence_penalty,
}
if self.service_type == "Azure":
parameters["engine"] = model
else:
parameters["model"] = model
response = openai.ChatCompletion.create(**parameters)
self.logger.info(response)
text = response["choices"][0]["message"]["content"]
conversation.append(
{"role": "assistant", "content": text},
)
return_list = [text, conversation]
self.logger.info(return_list)
return return_list
def image_create(
self,
prompt: str,
size: Optional[str] = "512x512",
num_images: Optional[int] = 1,
result_format: Optional[str] = "list",
) -> None:
"""Keyword for creating one or more images using OpenAI.
Keyword returns a list of urls for the images created.
**Note**. Keyword not supported in the ``Azure OpenAI`` service.
:param prompt: A text description of the desired image(s).
The maximum length is 1000 characters.
:param size: Size of the files to be created. 256x256, 512x512, 1024x1024
:param num_images: The number of images to generate. Must be between 1 and 10.
:param result_format: Result format (list / json).
Robot Framework example:
.. code-block:: robotframework
${images} Image Create
... Cartoon style picture of a cute monkey skateboarding.
... size=256x256
... num_images=2
FOR ${url} IN @{images}
Log ${url}
END
Python example:
.. code-block:: python
images = baselib.image_create(
'Cartoon style picture of a cute monkey skateboarding',
size='256x256',
num_images=2,
)
for url in images:
print(url)
"""
if self.service_type == "Azure":
raise NotImplementedError(
"Keyword 'Image Create' is not supported by Azure service"
)
response = openai.Image.create(prompt=prompt, size=size, n=num_images)
self.logger.info(response)
urls = []
if result_format == "list":
for _url in response["data"]:
urls.append(_url["url"])
self.logger.info(_url)
return urls
if result_format == "json":
return response
else:
return None
def image_create_variation(
self,
src_image: str,
size: Optional[str] = "512x512",
num_images: Optional[int] = 1,
result_format: Optional[str] = "list",
) -> None:
"""Keyword for creating one or more variations of a image. Keyword
returns a list of urls for the images created.
Source file must be a valid PNG file, less than 4MB, and square.
**Note**. Keyword not supported in the ``Azure OpenAI`` service.
:param src_image: The image to use as the basis for the variation(s).
Must be a valid PNG file, less than 4MB, and square.
:param size: The size of the generated images.
Must be one of 256x256, 512x512, or 1024x1024.
:param num_images: The number of images to generate. Must be between 1 and 10
:param result_format: Result format (list / json).
Robot Framework example:
.. code-block:: robotframework
${variations} Image Create Variation
... source_image.png
... size=256x256
... num_images=2
FOR ${url} IN @{variations}
Log ${url}
END
Python example:
.. code-block:: python
variations = baselib.image_create_variation(
'source_image.png',
size='256x256',
num_images=2,
)
for url in variations:
print(url)
"""
if self.service_type == "Azure":
raise NotImplementedError(
"Keyword 'Image Create Variation' is not supported by Azure service"
)
with open(src_image, "rb") as image_file:
response = openai.Image.create_variation(
image=image_file, n=num_images, size=size
)
self.logger.info(response)
urls = []
if result_format == "list":
for _url in response["data"]:
urls.append(_url["url"])
self.logger.info(_url)
return urls
if result_format == "json":
return response
else:
return None | /rpaframework_openai-1.3.0.tar.gz/rpaframework_openai-1.3.0/src/RPA/OpenAI.py | 0.917907 | 0.455017 | OpenAI.py | pypi |
import logging
from typing import Dict
from robotlibcore import DynamicCore
from RPA.core.logger import RobotLogListener
from RPA.PDF.keywords import DocumentKeywords, FinderKeywords, ModelKeywords
from RPA.PDF.keywords.model import Document
class PDF(DynamicCore):
"""`PDF` is a library for managing PDF documents.
It can be used to extract text from PDFs, add watermarks to pages, and
decrypt/encrypt documents.
Merging and splitting PDFs is supported by ``Add Files To PDF`` keyword. Read
the keyword documentation for examples.
There is also limited support for updating form field values. (check
``Set Field Value`` and ``Save Field Values`` for more info)
The input PDF file can be passed as an argument to the keywords, or it can be
omitted if you first call ``Open PDF``. A reference to the current active PDF will
be stored in the library instance and can be changed by using the ``Switch To PDF``
keyword with another PDF file path, therefore you can asynchronously work with
multiple PDFs.
.. Attention::
Keep in mind that this library works with text-based PDFs, and it **can't
extract information from an image-based (scan)** PDF file. For accurate
results, you have to use specialized external services wrapped by the
``RPA.DocumentAI`` library.
Portal example with video recording demo for parsing PDF invoices:
https://github.com/robocorp/example-parse-pdf-invoice
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.PDF
Library String
*** Tasks ***
Extract Data From First Page
${text} = Get Text From PDF report.pdf
${lines} = Get Lines Matching Regexp ${text}[${1}] .+pain.+
Log ${lines}
Get Invoice Number
Open Pdf invoice.pdf
${matches} = Find Text Invoice Number
Log List ${matches}
Fill Form Fields
Switch To Pdf form.pdf
${fields} = Get Input Fields encoding=utf-16
Log Dictionary ${fields}
Set Field Value Given Name Text Box Mark
Save Field Values output_path=${OUTPUT_DIR}${/}completed-form.pdf
... use_appearances_writer=${True}
.. code-block:: python
from RPA.PDF import PDF
from robot.libraries.String import String
pdf = PDF()
string = String()
def extract_data_from_first_page():
text = pdf.get_text_from_pdf("report.pdf")
lines = string.get_lines_matching_regexp(text[1], ".+pain.+")
print(lines)
def get_invoice_number():
pdf.open_pdf("invoice.pdf")
matches = pdf.find_text("Invoice Number")
for match in matches:
print(match)
def fill_form_fields():
pdf.switch_to_pdf("form.pdf")
fields = pdf.get_input_fields(encoding="utf-16")
for key, value in fields.items():
print(f"{key}: {value}")
pdf.set_field_value("Given Name Text Box", "Mark")
pdf.save_field_values(
output_path="completed-form.pdf",
use_appearances_writer=True
)
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self):
self.logger = logging.getLogger(__name__)
self.documents: Dict[str, Document] = {}
self.active_pdf_document = None
self.convert_settings = {}
# Register keyword libraries to LibCore
libraries = [
DocumentKeywords(self),
FinderKeywords(self),
ModelKeywords(self),
]
super().__init__(libraries)
listener = RobotLogListener()
listener.register_protected_keywords(["RPA.PDF.Decrypt PDF"])
logging.getLogger("pdfminer").setLevel(logging.WARNING) | /rpaframework_pdf-7.2.0.tar.gz/rpaframework_pdf-7.2.0/src/RPA/PDF/__init__.py | 0.822937 | 0.324035 | __init__.py | pypi |
import imghdr
import io
import os
import tempfile
from pathlib import Path
from typing import List, Optional, Tuple, Union
import pdfminer
import pypdf
from fpdf import FPDF, HTMLMixin
from pdfminer.image import ImageWriter
from pdfminer.layout import LTImage
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfparser import PDFParser
from PIL import Image
from robot.libraries.BuiltIn import BuiltIn
from RPA.PDF.keywords import LibraryContext, keyword
from RPA.PDF.keywords.model import Document, Figure
FilePath = Union[str, Path]
PagesType = Union[int, str, List[int], List[str], None]
ASSETS_DIR = Path(__file__).resolve().parent.parent / "assets"
def get_output_dir() -> Path:
try:
# A `None` may come from here too.
output_dir = BuiltIn().get_variable_value("${OUTPUT_DIR}")
except Exception: # pylint: disable=broad-except
output_dir = None
# Keep empty string as current working directory path.
if output_dir is None:
output_dir = "output"
output_dir = Path(output_dir).expanduser().resolve()
output_dir.mkdir(parents=True, exist_ok=True)
return output_dir
class PDF(FPDF, HTMLMixin):
"""
FDPF helper class.
Note that we are using FDPF2, which is a maintained fork of FPDF
https://github.com/PyFPDF/fpdf2
"""
FONT_PATHS = {
"": ASSETS_DIR / "Inter-Regular.ttf",
"B": ASSETS_DIR / "Inter-Bold.ttf",
"I": ASSETS_DIR / "Inter-Italic.ttf",
"BI": ASSETS_DIR / "Inter-BoldItalic.ttf",
}
def add_unicode_fonts(self):
for style, path in self.FONT_PATHS.items():
self.add_font("Inter", style=style, fname=str(path))
self.set_font("Inter")
class DocumentKeywords(LibraryContext):
"""Keywords for basic PDF operations"""
ENCODING = "utf-8"
@staticmethod
def resolve_input(path: FilePath) -> str:
"""Normalizes input path and returns as string."""
inp = Path(path)
inp = inp.expanduser().resolve()
return str(inp)
@staticmethod
def resolve_output(path: Optional[FilePath] = None) -> str:
"""Normalizes output path and returns as string."""
if path is None:
output = get_output_dir() / "output.pdf"
else:
output = Path(path)
output = output.expanduser().resolve()
output.parent.mkdir(parents=True, exist_ok=True)
return str(output)
@keyword
def close_all_pdfs(self) -> None:
"""Close all opened PDF file descriptors.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Close Multiple PDFs
Close all pdfs
"""
file_paths = list(self.ctx.documents.keys())
for filename in file_paths:
self.close_pdf(filename)
@keyword
def close_pdf(self, source_pdf: str = None) -> None:
"""Close PDF file descriptor for a certain file.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Close just one pdf
Close pdf path/to/the/pdf/file.pdf
:param source_pdf: filepath to the source pdf.
:raises ValueError: if file descriptor for the file is not found.
"""
if not source_pdf:
if self.active_pdf_document:
source_pdf = self.active_pdf_document.path
else:
raise ValueError("No active PDF document open")
source_pdf = str(source_pdf)
if source_pdf not in self.ctx.documents:
raise ValueError(f"PDF {source_pdf!r} is not open")
self.logger.info("Closing PDF document: %s", source_pdf)
self.ctx.documents[source_pdf].close()
del self.ctx.documents[source_pdf]
self.active_pdf_document = None
@keyword
def open_pdf(self, source_path: FilePath) -> None:
"""Open a PDF document for reading.
This is called automatically in the other PDF keywords
when a path to the PDF file is given as an argument.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Open my pdf file
Open PDF /tmp/sample.pdf
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def example_keyword():
metadata = pdf.open_pdf("/tmp/sample.pdf")
:param source_path: filepath to the source pdf.
:raises ValueError: if PDF is already open.
"""
if not source_path:
raise ValueError("Source PDF is missing")
source_path = self.resolve_input(source_path)
if source_path in self.ctx.documents:
raise ValueError(
"PDF file is already open, please close it before opening it again"
)
self.logger.debug("Opening new document: %s", source_path)
# pylint: disable=consider-using-with
self.active_pdf_document = self.ctx.documents[source_path] = Document(
source_path, fileobject=open(source_path, "rb")
)
@keyword
def template_html_to_pdf(
self,
template: str,
output_path: str,
variables: dict = None,
encoding: str = ENCODING,
) -> None:
"""Use HTML template file to generate PDF file.
It provides an easy method of generating a PDF document from an HTML formatted
template file.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Create PDF from HTML template
${TEMPLATE}= Set Variable order.template
${PDF}= Set Variable result.pdf
&{DATA}= Create Dictionary
... name=Robot Generated
... email=robot@domain.com
... zip=00100
... items=Item 1, Item 2
Template HTML to PDF
... template=${TEMPLATE}
... output_path=${PDF}
... variables=${DATA}
**Python**
.. code-block:: python
from RPA.PDF import PDF
p = PDF()
orders = ["item 1", "item 2", "item 3"]
data = {
"name": "Robot Process",
"email": "robot@domain.com",
"zip": "00100",
"items": "<br/>".join(orders),
}
p.template_html_to_pdf("order.template", "order.pdf", data)
:param template: Filepath to the HTML template.
:param output_path: Filepath where to save PDF document.
:param variables: Dictionary of variables to fill into template, defaults to {}.
:param encoding: Codec used for text I/O.
"""
variables = variables or {}
with open(template, "r", encoding=encoding or self.ENCODING) as templatefile:
html = templatefile.read()
for key, value in variables.items():
html = html.replace("{{" + key + "}}", str(value))
self.html_to_pdf(html, output_path, encoding=encoding)
@keyword
def html_to_pdf(
self,
content: str,
output_path: str,
encoding: str = ENCODING,
) -> None:
"""Generate a PDF file from HTML content.
Note that input must be well-formed and valid HTML.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Create PDF from HTML
HTML to PDF ${html_content_as_string} /tmp/output.pdf
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def create_pdf_from_html():
pdf.html_to_pdf(html_content_as_string, "/tmp/output.pdf")
:param content: HTML content.
:param output_path: Filepath where to save the PDF document.
:param encoding: Codec used for text I/O.
"""
output_path = self.resolve_output(output_path)
self.logger.info("Writing output to file %s", output_path)
fpdf = PDF()
# Support unicode content with a font capable of rendering it.
fpdf.core_fonts_encoding = encoding
fpdf.add_unicode_fonts()
fpdf.set_margin(0)
fpdf.add_page()
fpdf.write_html(content)
fpdf.output(name=output_path)
@keyword
def get_pdf_info(self, source_path: str = None) -> dict:
"""Get metadata from a PDF document.
If no source path given, assumes a PDF is already opened.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Get PDF metadata
${metadata}= Get PDF Info /tmp/sample.pdf
*** Keywords ***
Get metadata from an already opened PDF
${metadata}= Get PDF Info
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def get_pdf_metadata():
metadata = pdf.get_pdf_info("/tmp/sample.pdf")
:param source_path: filepath to the source PDF.
:return: dictionary of PDF information.
"""
self.switch_to_pdf(source_path)
reader = self.active_pdf_document.reader
docinfo = reader.metadata
num_pages = self.pages_count
parser = PDFParser(self.active_pdf_document.fileobject)
document = PDFDocument(parser)
try:
fields = pdfminer.pdftypes.resolve1(document.catalog["AcroForm"])["Fields"]
except KeyError:
fields = None
optional = (
lambda attr: getattr(docinfo, attr) if docinfo is not None else None
) # noqa
return {
"Author": optional("author"),
"Creator": optional("creator"),
"Producer": optional("producer"),
"Subject": optional("subject"),
"Title": optional("title"),
"Pages": num_pages,
"Encrypted": self.is_pdf_encrypted(source_path),
"Fields": bool(fields),
}
@keyword
def is_pdf_encrypted(self, source_path: str = None) -> bool:
"""Check if PDF is encrypted.
If no source path given, assumes a PDF is already opened.
:param source_path: filepath to the source pdf.
:return: True if file is encrypted.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Is PDF encrypted
${is_encrypted}= Is PDF Encrypted /tmp/sample.pdf
*** Keywords ***
Is open PDF encrypted
${is_encrypted}= Is PDF Encrypted
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def example_keyword():
is_encrypted = pdf.is_pdf_encrypted("/tmp/sample.pdf")
"""
self.switch_to_pdf(source_path)
reader = self.active_pdf_document.reader
return reader.is_encrypted
@keyword
def get_number_of_pages(self, source_path: str = None) -> int:
"""Get number of pages in the document.
If no source path given, assumes a PDF is already opened.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Number of pages in PDF
${page_count}= Get Number Of Pages /tmp/sample.pdf
Number of pages in opened PDF
${page_count}= Get Number Of Pages
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def number_of_pages_in_pdf():
page_count = pdf.get_number_of_pages("/tmp/sample.pdf")
:param source_path: filepath to the source pdf
:raises PdfReadError: if file is encrypted or other restrictions are in place
"""
self.switch_to_pdf(source_path)
reader = self.active_pdf_document.reader
return len(reader.pages)
@keyword
def switch_to_pdf(self, source_path: Optional[FilePath] = None) -> None:
"""Switch library's current fileobject to already opened file
or open a new file if not opened.
This is done automatically in the PDF library keywords.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Jump to another PDF
Switch to PDF /tmp/another.pdf
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def jump_to_another_pdf():
pdf.switch_to_pdf("/tmp/sample.pdf")
:param source_path: filepath to the source pdf.
:raises ValueError: if PDF filepath is not given and there are no active
file to activate.
"""
if not source_path:
if not self.active_pdf_document:
raise ValueError("No PDF is open")
self.logger.debug(
"Using already set document: %s", self.active_pdf_document.path
)
return
source_path = self.resolve_input(source_path)
if source_path not in self.ctx.documents:
self.open_pdf(source_path)
elif self.ctx.documents[source_path] != self.active_pdf_document:
self.logger.debug("Switching to already opened document: %s", source_path)
self.active_pdf_document = self.ctx.documents[source_path]
else:
self.logger.debug("Using already set document: %s", source_path)
@keyword
def get_text_from_pdf(
self,
source_path: str = None,
pages: PagesType = None,
details: bool = False,
trim: bool = True,
) -> dict:
"""Get text from set of pages in source PDF document.
If no source path given, assumes a PDF is already opened.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Text extraction from PDF
${text}= Get Text From PDF /tmp/sample.pdf
Text extraction from open PDF
${text}= Get Text From PDF
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def text_extraction_from_pdf():
text = pdf.get_text_from_pdf("/tmp/sample.pdf")
:param source_path: filepath to the source pdf.
:param pages: page numbers to get text (numbers start from 1).
:param details: set to `True` to return textboxes, default `False`.
:param trim: set to `False` to return raw texts, default `True`
means whitespace is trimmed from the text
:return: dictionary of pages and their texts.
"""
self.switch_to_pdf(source_path)
self.ctx.convert(trim=trim)
reader = self.active_pdf_document.reader
pages = self._get_page_numbers(pages, reader)
pdf_text = {}
for idx, page in self.active_pdf_document.get_pages().items():
if page.pageid not in pages:
continue
pdf_text[idx] = [] if details else ""
for _, item in page.textboxes.items():
if details:
pdf_text[idx].append(item)
else:
pdf_text[idx] += item.text
return pdf_text
@keyword
def extract_pages_from_pdf(
self,
source_path: str = None,
output_path: str = None,
pages: PagesType = None,
) -> None:
"""Extract pages from source PDF and save to a new PDF document.
Page numbers start from 1.
If no source path given, assumes a PDF is already opened.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Save PDF pages to a new document
${pages}= Extract Pages From PDF
... source_path=/tmp/sample.pdf
... output_path=/tmp/output.pdf
... pages=5
Save PDF pages from open PDF to a new document
${pages}= Extract Pages From PDF
... output_path=/tmp/output.pdf
... pages=5
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def save_pdf_pages_to_a_new_document():
pages = pdf.extract_pages_from_pdf(
source_path="/tmp/sample.pdf",
output_path="/tmp/output.pdf",
pages=5
)
:param source_path: filepath to the source pdf.
:param output_path: filepath to the target pdf, stored by default
in the robot output directory as ``output.pdf``
:param pages: page numbers to extract from PDF (numbers start from 1)
if None then extracts all pages.
"""
self.switch_to_pdf(source_path)
reader = self.active_pdf_document.reader
writer = pypdf.PdfWriter()
output_path = self.resolve_output(output_path)
pages: List[int] = self._get_page_numbers(pages, reader) # 1-indexed
for page_nr in pages:
writer.add_page(reader.pages[page_nr - 1])
with open(output_path, "wb") as stream:
writer.write(stream)
@keyword
def rotate_page(
self,
pages: PagesType,
source_path: Optional[str] = None,
output_path: Optional[str] = None,
clockwise: bool = True,
angle: int = 90,
) -> None:
"""Rotate pages in source PDF document and save to target PDF document.
If no source path given, assumes a PDF is already opened.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
PDF page rotation
Rotate Page
... source_path=/tmp/sample.pdf
... output_path=/tmp/output.pdf
... pages=5
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def pdf_page_rotation():
pages = pdf.rotate_page(
source_path="/tmp/sample.pdf",
output_path="/tmp/output.pdf",
pages=5
)
:param pages: page numbers to extract from PDF (numbers start from 1).
:param source_path: filepath to the source pdf.
:param output_path: filepath to the target pdf, stored by default
in the robot output directory as ``output.pdf``
:param clockwise: directorion that page will be rotated to, default True.
:param angle: number of degrees to rotate, default 90.
"""
# TODO: don't save to a new file every time
self.switch_to_pdf(source_path)
reader = self.active_pdf_document.reader
writer = pypdf.PdfWriter()
output_path = self.resolve_output(output_path)
angle = int(angle) * (1 if clockwise else -1)
pages = self._get_page_numbers(pages, reader)
for page, source_page in enumerate(reader.pages):
if page + 1 in pages:
source_page.rotate(angle)
writer.add_page(source_page)
with open(output_path, "wb") as stream:
writer.write(stream)
@keyword
def encrypt_pdf(
self,
source_path: str = None,
output_path: str = None,
user_pwd: str = "",
owner_pwd: str = None,
use_128bit: bool = True,
) -> None:
"""Encrypt a PDF document.
If no source path given, assumes a PDF is already opened.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Secure this PDF
Encrypt PDF /tmp/sample.pdf
Secure this PDF and set passwords
Encrypt PDF
... source_path=/tmp/sample.pdf
... output_path=/tmp/new/sample_encrypted.pdf
... user_pwd=complex_password_here
... owner_pwd=different_complex_password_here
... use_128bit=${TRUE}
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def secure_this_pdf():
pdf.encrypt_pdf("/tmp/sample.pdf")
:param source_path: filepath to the source pdf.
:param output_path: filepath to the target pdf, stored by default
in the robot output directory as ``output.pdf``
:param user_pwd: allows opening and reading PDF with restrictions.
:param owner_pwd: allows opening PDF without any restrictions, by
default same `user_pwd`.
:param use_128bit: whether to 128bit encryption, when false 40bit
encryption is used, default True.
"""
# TODO: don't save to a new file every time
self.switch_to_pdf(source_path)
reader = self.active_pdf_document.reader
output_path = self.resolve_output(output_path)
if owner_pwd is None:
owner_pwd = user_pwd
writer = pypdf.PdfWriter()
writer.append_pages_from_reader(reader)
writer.encrypt(user_pwd, owner_pwd, use_128bit)
with open(output_path, "wb") as f:
writer.write(f)
@keyword
def decrypt_pdf(self, source_path: str, output_path: str, password: str) -> bool:
"""Decrypt PDF with password.
If no source path given, assumes a PDF is already opened.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Make PDF human readable
${success}= Decrypt PDF /tmp/sample.pdf
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def make_pdf_human_readable():
success = pdf.decrypt_pdf("/tmp/sample.pdf")
:param source_path: filepath to the source pdf.
:param output_path: filepath to the decrypted pdf.
:param password: password as a string.
:return: True if decrypt was successful, else False or Exception.
:raises ValueError: on decryption errors.
"""
self.switch_to_pdf(source_path)
reader = self.active_pdf_document.reader
try:
match_result = reader.decrypt(password)
if match_result == 0:
raise ValueError("PDF decrypt failed.")
elif match_result == 1:
self.logger.info("PDF was decrypted with user password.")
elif match_result == 2:
self.logger.info("PDF was decrypted with owner password.")
else:
return False
output_path = self.resolve_output(output_path)
self.save_pdf(output_path, reader)
return True
except NotImplementedError as e:
raise ValueError(
f"Document {source_path!r} uses an unsupported encryption method"
) from e
except KeyError:
self.logger.info("PDF is not encrypted")
return False
@keyword
def get_all_figures(self, source_path: str = None) -> dict:
"""Return all figures in the PDF document.
If no source path given, assumes a PDF is already opened.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Image fetch
&{figures}= Get All Figures /tmp/sample.pdf
Image fetch from open PDF
&{figures}= Get All Figures
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def image_fetch():
figures = pdf.get_all_figures("/tmp/sample.pdf")
:param source_path: filepath to the source pdf.
:return: dictionary of figures divided into pages.
"""
self.switch_to_pdf(source_path)
self.ctx.convert()
pages = {}
for pagenum, page in self.active_pdf_document.get_pages().items():
pages[pagenum] = page.figures
return pages
@keyword
def add_watermark_image_to_pdf(
self,
image_path: FilePath,
output_path: FilePath,
source_path: Optional[FilePath] = None,
coverage: float = 0.2,
) -> None:
"""Add an image into an existing or new PDF.
If no source path is given, assume a PDF is already opened.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keyword ***
Indicate approved with watermark
Add Watermark Image To PDF
... image_path=approved.png
... source_path=/tmp/sample.pdf
... output_path=output/output.pdf
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def indicate_approved_with_watermark():
pdf.add_watermark_image_to_pdf(
image_path="approved.png"
source_path="/tmp/sample.pdf"
output_path="output/output.pdf"
)
:param image_path: filepath to image file to add into PDF
:param source: filepath to source, if not given add image to currently
active PDF
:param output_path: filepath of target PDF
:param coverage: how the watermark image should be scaled on page,
defaults to 0.2
"""
# Ensure an active input PDF.
self.switch_to_pdf(source_path)
input_reader = self.active_pdf_document.reader
# Set image boundaries.
mediabox = input_reader.pages[0].mediabox
img_obj = Image.open(image_path)
max_width = int(float(mediabox.width) * coverage)
max_height = int(float(mediabox.height) * coverage)
img_width, img_height = self.fit_dimensions_to_box(
*img_obj.size, max_width, max_height
)
# Put the image on the first page of a temporary PDF file, so we can merge this
# PDF formatted image page with every single page of the targeted PDF.
# NOTE(cmin764): Keep the watermark image PDF reader open along the entire
# process, so the final PDF gets rendered correctly)
with tempfile.TemporaryFile(suffix=".pdf") as temp_img_pdf:
# Save image in temporary PDF using FPDF.
pdf = FPDF()
pdf.add_page()
pdf.image(name=image_path, x=40, y=60, w=img_width, h=img_height)
pdf.output(name=temp_img_pdf)
# Get image page from temporary PDF using pypdf. (compatible with the
# writer)
img_pdf_reader = pypdf.PdfReader(temp_img_pdf)
watermark_page = img_pdf_reader.pages[0]
# Write the merged pages of source PDF into the destination one.
output_writer = pypdf.PdfWriter()
for page in input_reader.pages:
page.merge_page(watermark_page)
output_writer.add_page(page)
# Since the input PDF can be the same with the output, make sure we close
# the input stream after writing into an auxiliary buffer. (if the input
# stream is closed before writing, then the writing is incomplete; and we
# can't read and write at the same time into the same file, that's why we
# use an auxiliary buffer)
output_buffer = io.BytesIO()
output_writer.write(output_buffer)
self.active_pdf_document.close()
output_path = self.resolve_output(output_path)
with open(output_path, "wb") as output_stream:
output_stream.write(output_buffer.getvalue())
@staticmethod
def fit_dimensions_to_box(
width: int, height: int, max_width: int, max_height: int
) -> Tuple[int, int]:
"""
Fit dimensions of width and height to a given box.
"""
ratio = width / height
if width > max_width:
width = max_width
height = int(width / ratio)
if height > max_height:
height = max_height
width = int(ratio * height)
if width == 0 or height == 0:
raise ValueError("Image has invalid dimensions.")
return width, height
@keyword
def save_pdf(
self,
output_path: str,
reader: Optional[pypdf.PdfReader] = None,
):
"""Save the contents of a pypdf reader to a new file.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keyword ***
Save changes to PDF
Save PDF /tmp/output.pdf
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def save_changes_to_pdf():
pdf.save_pdf(output_path="output/output.pdf")
:param output_path: filepath to target PDF
:param reader: a pypdf reader (defaults to currently active document)
"""
if not reader:
# Ensures there's at least one document open and active.
self.switch_to_pdf()
reader = self.active_pdf_document.reader
writer = pypdf.PdfWriter()
for page in reader.pages:
try:
writer.add_page(page)
except Exception as exc: # pylint: disable=W0703
self.logger.warning(repr(exc))
raise
output_path = self.resolve_output(output_path)
with open(output_path, "wb") as stream:
writer.write(stream)
@staticmethod
def _get_page_numbers(
pages: PagesType = None, reader: Optional[pypdf.PdfReader] = None
) -> List[int]:
"""Resolve page numbers argument to a list of 1-indexed integer pages."""
if not pages and not reader:
raise ValueError("Need a reader instance or explicit page numbers")
if pages and isinstance(pages, str):
pages = pages.split(",")
elif pages and isinstance(pages, int):
pages = [pages]
elif reader and not pages:
pages = range(1, len(reader.pages) + 1)
return list(map(int, pages))
@keyword
def save_figure_as_image(
self, figure: Figure, images_folder: str = ".", file_prefix: str = ""
) -> Optional[str]:
"""Try to save the image data from Figure object, and return
the file name, if successful.
Figure needs to have byte `stream` and that needs to be recognized
as image format for successful save.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keyword ***
Figure to Image
${image_file_path} = Save figure as image
... figure=pdf_figure_object
... images_folder=/tmp/images
... file_prefix=file_name_here
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def figure_to_image():
image_file_path = pdf.save_figure_as_image(
figure="pdf_figure_object"
images_folder="/tmp/images"
file_prefix="file_name_here"
)
:param figure: PDF Figure object which will be saved as an image.
The PDF Figure object can be determined from the `Get All Figures` keyword
:param images_folder: directory where image files will be created
:param file_prefix: image filename prefix
:return: image filepath or None
"""
result = None
images_folder = Path(images_folder)
lt_image = figure.item
if hasattr(lt_image, "stream") and lt_image.stream:
file_stream = lt_image.stream.get_rawdata()
file_ext = imghdr.what("", file_stream)
if file_ext:
filename = "".join([str(file_prefix), lt_image.name, ".", file_ext])
imagepath = images_folder / filename
with open(imagepath, "wb") as fout:
fout.write(file_stream)
result = str(imagepath)
elif isinstance(lt_image, LTImage):
img_writer = ImageWriter(images_folder)
filename = img_writer.export_image(lt_image)
src = images_folder / filename
if file_prefix:
dest = images_folder / f"{file_prefix}{filename}"
os.rename(src, dest)
src = dest
result = str(src)
else:
self.logger.info("Unable to determine image type for a figure")
else:
self.logger.info(
"Image object does not have stream and can't be saved as an image"
)
return result
@keyword
def save_figures_as_images(
self,
source_path: Optional[str] = None,
images_folder: str = ".",
pages: Optional[str] = None,
file_prefix: str = "",
) -> List[str]:
"""Save figures from given PDF document as image files.
If no source path given, assumes a PDF is already opened.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keyword ***
Figures to Images
${image_filenames} = Save figures as images
... source_path=/tmp/sample.pdf
... images_folder=/tmp/images
... pages=${4}
... file_prefix=file_name_here
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def figures_to_images():
image_filenames = pdf.save_figures_as_image(
source_path="/tmp/sample.pdf"
images_folder="/tmp/images"
pages=4
file_prefix="file_name_here"
)
:param source_path: filepath to PDF document
:param images_folder: directory where image files will be created
:param pages: target figures in the pages, can be single page or range,
default `None` means that all pages are scanned for figures to save
(numbers start from 1)
:param file_prefix: image filename prefix
:return: list of image filenames created
"""
figures = self.get_all_figures(source_path)
pagecount = self.get_number_of_pages(source_path)
page_list = self._get_pages(pagecount, pages)
image_files = []
for n in page_list:
for _, figure in figures[n].items():
image_file = self.save_figure_as_image(
figure, images_folder, file_prefix
)
if image_file:
image_files.append(image_file)
return image_files
@keyword
def add_files_to_pdf(
self, files: list = None, target_document: str = None, append: bool = False
) -> None:
"""Add images and/or pdfs to new PDF document.
Supports merging and splitting PDFs.
Image formats supported are JPEG, PNG and GIF.
The file can be added with extra properties by
denoting `:` at the end of the filename. Each
property should be separated by comma.
Supported extra properties for PDFs are:
- page and/or page ranges
- no extras means that all source PDF pages are added
into new PDF
Supported extra properties for images are:
- format, the PDF page format, for example. Letter or A4
- rotate, how many degrees image is rotated counter-clockwise
- align, only possible value at the moment is center
- orientation, the PDF page orientation for the image, possible
values P (portrait) or L (landscape)
- x/y, coordinates for adjusting image position on the page
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Add files to pdf
${files}= Create List
... ${TESTDATA_DIR}${/}invoice.pdf
... ${TESTDATA_DIR}${/}approved.png:align=center
... ${TESTDATA_DIR}${/}robot.pdf:1
... ${TESTDATA_DIR}${/}approved.png:x=0,y=0
... ${TESTDATA_DIR}${/}robot.pdf:2-10,15
... ${TESTDATA_DIR}${/}approved.png
... ${TESTDATA_DIR}${/}landscape_image.png:rotate=-90,orientation=L
... ${TESTDATA_DIR}${/}landscape_image.png:format=Letter
Add Files To PDF ${files} newdoc.pdf
Merge pdfs
${files}= Create List
... ${TESTDATA_DIR}${/}invoice.pdf
... ${TESTDATA_DIR}${/}robot.pdf:1
... ${TESTDATA_DIR}${/}robot.pdf:2-10,15
Add Files To Pdf ${files} merged-doc.pdf
Split pdf
${files}= Create List
... ${OUTPUT_DIR}${/}robot.pdf:2-10,15
Add Files To Pdf ${files} split-doc.pdf
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def example_addfiles():
list_of_files = [
'invoice.pdf',
'approved.png:align=center',
'robot.pdf:1',
'approved.png:x=0,y=0',
]
pdf.add_files_to_pdf(
files=list_of_files,
target_document="output/output.pdf"
)
def example_merge():
list_of_files = [
'invoice.pdf',
'robot.pdf:1',
'robot.pdf:2-10,15',
]
pdf.add_files_to_pdf(
files=list_of_files,
target_document="output/merged-doc.pdf"
)
def example_split():
list_of_files = [
'robot.pdf:2-10,15',
]
pdf.add_files_to_pdf(
files=list_of_files,
target_document="output/split-doc.pdf"
)
:param files: list of filepaths to add into PDF (can be either images or PDFs)
:param target_document: filepath of target PDF
:param append: appends files to existing document if `append` is `True`
"""
writer = pypdf.PdfWriter()
if append:
self._add_pages_to_writer(writer, target_document)
for f in files:
file_to_add = Path(f)
namesplit = file_to_add.name.rsplit(":", 1)
basename = namesplit[0]
parameters = namesplit[1] if len(namesplit) == 2 else None
file_to_add = file_to_add.parent / basename
image_filetype = imghdr.what(str(file_to_add))
self.logger.info("File %s type: %s", str(file_to_add), image_filetype)
if basename.lower().endswith(".pdf"):
reader = pypdf.PdfReader(str(file_to_add), strict=False)
pages = self._get_pages(len(reader.pages), parameters)
for page_nr in pages:
try:
# Because is 1-offset with `_get_pages()`.
page = reader.pages[page_nr - 1]
writer.add_page(page)
except IndexError:
self.logger.warning(
"File %s does not have page %d", file_to_add, page_nr
)
elif image_filetype in ["png", "jpg", "jpeg", "gif"]:
temp_pdf = os.path.join(tempfile.gettempdir(), "temp.pdf")
settings = self._get_image_settings(str(file_to_add), parameters)
if settings["format"]:
pdf = FPDF(
format=settings["format"], orientation=settings["orientation"]
)
else:
pdf = FPDF(orientation=settings["orientation"])
pdf.add_page()
pdf.image(
name=settings["name"],
x=settings["x"],
y=settings["y"],
w=settings["width"],
h=settings["height"],
)
pdf.output(name=temp_pdf)
reader = pypdf.PdfReader(temp_pdf)
writer.add_page(reader.pages[0])
with open(target_document, "wb") as f:
writer.write(f)
def _add_pages_to_writer(self, writer, target_document):
if not Path(target_document).exists():
self.logger.warn(
"Trying to append files to document '%s' which does not exist."
"Creating document instead." % target_document
)
else:
reader = pypdf.PdfReader(str(target_document), strict=False)
for idx, page in enumerate(reader.pages):
self.logger.info("Adding page: %s", idx)
writer.add_page(page)
@staticmethod
def _get_pages(pagecount: int, page_reference: Optional[str]) -> List[int]:
"""Returns a flattened list of pages based on provided 1-indexed ranges."""
page_reference = page_reference or f"1-{pagecount}"
temp = [
(lambda sub: range(sub[0], sub[-1] + 1))(
list(map(int, ele.strip().split("-")))
)
for ele in page_reference.split(",")
]
return [b for a in temp for b in a]
def _get_image_settings(self, imagepath, parameters):
if isinstance(parameters, str):
image_parameters = (
dict(ele.lower().strip().split("=") for ele in parameters.split(","))
if parameters
else {}
)
else:
image_parameters = parameters or {}
self.logger.info("Image parameters: %s" % image_parameters)
settings = {
"x": int(image_parameters.get("x", 10)),
"y": int(image_parameters.get("y", 10)),
"format": image_parameters.get("format", None),
"orientation": str(image_parameters.get("orientation", "P")).upper(),
"width": None,
"height": None,
"name": imagepath,
}
rotate = image_parameters.get("rotate", None)
align = image_parameters.get("align", None)
max_width = 188 if settings["orientation"] == "P" else 244
max_height = 244 if settings["orientation"] == "P" else 188
im = Image.open(settings["name"])
if rotate:
rotate = int(rotate)
file_ext = Path(settings["name"]).suffix
temp_image = os.path.join(tempfile.gettempdir(), f"temp{file_ext}")
rotated = im.rotate(rotate, expand=True)
rotated.save(temp_image)
settings["name"] = temp_image
del image_parameters["rotate"]
im.close()
rotated.close()
return self._get_image_settings(temp_image, image_parameters)
elif align and align == "center":
width, height = self.fit_dimensions_to_box(*im.size, max_width, max_height)
settings["width"] = width
settings["height"] = height
settings["x"] = int((max_width / 2) - (width / 2)) + 10
settings["y"] = int((max_height / 2) - (height / 2)) + 10
if not settings["width"] or not settings["height"]:
width, height = self.fit_dimensions_to_box(*im.size, max_width, max_height)
settings["width"] = width
settings["height"] = height
im.close()
return settings | /rpaframework_pdf-7.2.0.tar.gz/rpaframework_pdf-7.2.0/src/RPA/PDF/keywords/document.py | 0.754734 | 0.222267 | document.py | pypi |
import re
import sys
import typing
from collections import OrderedDict
from typing import Any, Iterable, Optional, Set, Tuple, Union
import pdfminer
import pypdf
from pdfminer.converter import PDFConverter
from pdfminer.layout import (
LTChar,
LTCurve,
LTFigure,
LTImage,
LTLine,
LTPage,
LTRect,
LTText,
LTTextBox,
LTTextBoxVertical,
LTTextGroup,
LTTextLine,
)
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
from pdfminer.utils import bbox2str, enc
from RPA.PDF.keywords import LibraryContext, keyword
Coords = Tuple[int, ...]
BOXES_FLOW_NOT_SET = 0.5
def iterable_items_to_ints(bbox: Optional[Iterable]) -> Coords:
if bbox is None:
return ()
return tuple(map(int, bbox))
class BaseElement:
"""Base class for all kind of elements found in PDFs."""
def __init__(self, bbox: Optional[Iterable]):
self._bbox: Coords = iterable_items_to_ints(bbox)
assert len(self._bbox) == 4, "must be in (left, bottom, right, top) format"
@property
def bbox(self) -> Coords:
return self._bbox
@property
def left(self) -> int:
return self.bbox[0]
@property
def bottom(self) -> int:
return self.bbox[1]
@property
def right(self) -> int:
return self.bbox[2]
@property
def top(self) -> int:
return self.bbox[3]
class Figure(BaseElement):
"""Class for each LTFigure element in the PDF"""
def __init__(self, item):
super().__init__(item.bbox)
self._item = item
@property
def item(self):
return self._item
def __str__(self) -> str:
return (
f'<image src="{self.item.name}" width="{int(self.item.width)}" '
f'height="{int(self.item.height)}" />'
)
class TextBox(BaseElement):
"""Class for each LTTextBox element in the PDF."""
def __init__(self, boxid: int, *, item: Any, trim: bool = True) -> None:
super().__init__(item.bbox)
self._boxid = boxid
self._text = item.get_text()
if trim:
self._text = self._text.strip()
@property
def boxid(self) -> int:
return self._boxid
@property
def text(self) -> str:
return self._text
def __str__(self) -> str:
return f"{self.text} {self.bbox}"
class Page(BaseElement):
"""Class that abstracts a PDF page."""
def __init__(self, pageid: int, bbox: Iterable, rotate: int) -> None:
super().__init__(bbox)
self.pageid = pageid
self.rotate = rotate
self._content = OrderedDict()
self._content_id = 0
self._figures = OrderedDict()
self._textboxes = OrderedDict()
def add_content(self, content: Any) -> None:
self._content[self._content_id] = content
if isinstance(content, Figure):
content_dict = self._figures
elif isinstance(content, TextBox):
content_dict = self._textboxes
else:
content_dict = None
if content_dict is not None:
content_dict[self._content_id] = content
self._content_id += 1
@property
def content(self) -> OrderedDict:
return self._content
@property
def figures(self) -> OrderedDict:
# NOTE(cmin764): Usually all our figures are of type `LTImage` only. (as the
# `LTFigure` ones are duplicates of the previously extracted unique images)
return self._figures
@property
def textboxes(self) -> OrderedDict:
return self._textboxes
@property
def tag(self) -> str:
return (
f'<page id="{self.pageid}" bbox="{bbox2str(self.bbox)}" '
f'rotate="{self.rotate}">'
)
def __str__(self) -> str:
items_str = "\n".join(self._content.values())
return f"{self.tag}\n{items_str}"
class Document:
"""Class for the parsed PDF document."""
ENCODING: str = "utf-8"
def __init__(self, path: str, *, fileobject: typing.BinaryIO):
self._path = path
self._fileobject = fileobject
self._pages = OrderedDict()
self._xml_content_list: typing.List[bytes] = []
self.fields: Optional[dict] = None
self.has_converted_pages: Set[int] = set()
@property
def path(self):
return self._path
@property
def fileobject(self) -> typing.BinaryIO:
if self._fileobject.closed:
# pylint: disable=consider-using-with
self._fileobject = open(self.path, "rb")
self._fileobject.seek(0, 0)
return self._fileobject
@property
def reader(self) -> pypdf.PdfReader:
"""Get a PyPDF reader instance for the PDF."""
return pypdf.PdfReader(self.fileobject, strict=False)
def add_page(self, page: Page) -> None:
self._pages[page.pageid] = page
def get_pages(self) -> OrderedDict:
return self._pages
def get_page(self, pagenum: int) -> Page:
return self._pages[pagenum]
def append_xml(self, xml: bytes) -> None:
self._xml_content_list.append(xml)
def dump_xml(self) -> str:
return b"".join(self._xml_content_list).decode(self.ENCODING)
def close(self):
self._fileobject.close()
class Converter(PDFConverter):
"""Class for converting PDF into RPA classes"""
CONTROL = re.compile("[\x00-\x08\x0b-\x0c\x0e-\x1f]")
def __init__(
self,
active_document: Document,
rsrcmgr,
*,
logger,
codec: str = "utf-8",
pageno: int = 1,
laparams=None,
imagewriter=None,
stripcontrol=False,
trim=True,
):
super().__init__(
rsrcmgr, sys.stdout, codec=codec, pageno=pageno, laparams=laparams
)
self.active_pdf_document = active_document
self.current_page = None
self.imagewriter = imagewriter
self.stripcontrol = stripcontrol
self.trim = trim
self.write_header()
self._logger = logger
self._unique_figures: Set[Tuple[int, str, Coords]] = set()
def _add_unique_figure(self, figure: Figure):
figure_key = (self.current_page.pageid, str(figure), figure.bbox)
if figure_key not in self._unique_figures:
self.current_page.add_content(figure)
self._unique_figures.add(figure_key)
def write(self, text: str):
if self.codec:
text = text.encode(self.codec)
else:
text = text.encode()
self.active_pdf_document.append_xml(text)
def write_header(self):
if self.codec:
self.write('<?xml version="1.0" encoding="%s" ?>\n' % self.codec)
else:
self.write('<?xml version="1.0" ?>\n')
self.write("<pages>\n")
def write_footer(self):
self.write("</pages>\n")
def write_text(self, text: str):
if self.stripcontrol:
text = self.CONTROL.sub("", text)
self.write(enc(text))
def _show_group(self, item):
if isinstance(item, LTTextBox):
self.write(
'<textbox id="%d" bbox="%s" />\n' % (item.index, bbox2str(item.bbox))
)
elif isinstance(item, LTTextGroup):
self.write('<textgroup bbox="%s">\n' % bbox2str(item.bbox))
for child in item:
self._show_group(child)
self.write("</textgroup>\n")
# pylint: disable = R0912, R0915
def _render(self, item): # noqa: C901
if isinstance(item, LTPage):
self.current_page = Page(item.pageid, item.bbox, item.rotate)
self.write(self.current_page.tag + "\n")
for child in item:
self._render(child)
if item.groups is not None:
self.write("<layout>\n")
for group in item.groups:
self._show_group(group)
self.write("</layout>\n")
self.write("</page>\n")
self.active_pdf_document.add_page(self.current_page)
elif isinstance(item, LTLine):
s = '<line linewidth="%d" bbox="%s" />\n' % (
item.linewidth,
bbox2str(item.bbox),
)
self.write(s)
elif isinstance(item, LTRect):
s = '<rect linewidth="%d" bbox="%s" />\n' % (
item.linewidth,
bbox2str(item.bbox),
)
self.write(s)
elif isinstance(item, LTCurve):
s = '<curve linewidth="%d" bbox="%s" pts="%s"/>\n' % (
item.linewidth,
bbox2str(item.bbox),
item.get_pts(),
)
self.write(s)
elif isinstance(item, LTFigure):
s = '<figure name="%s" bbox="%s">\n' % (
item.name,
bbox2str(item.bbox),
)
self.write(s)
for child in item:
self._render(child)
if isinstance(child, LTImage):
figure = Figure(child)
self._add_unique_figure(figure)
self.write("</figure>\n")
elif isinstance(item, LTTextLine):
self.write('<textline bbox="%s">\n' % bbox2str(item.bbox))
for child in item:
self._render(child)
self.write("</textline>\n")
elif isinstance(item, LTTextBox):
wmode = ""
if isinstance(item, LTTextBoxVertical):
wmode = ' wmode="vertical"'
s = '<textbox id="%d" bbox="%s"%s>\n' % (
item.index,
bbox2str(item.bbox),
wmode,
)
box = TextBox(item.index, item=item, trim=self.trim)
self.write(s)
self.current_page.add_content(box)
for child in item:
self._render(child)
self.write("</textbox>\n")
elif isinstance(item, LTChar):
s = (
'<text font="%s" bbox="%s" colourspace="%s" '
'ncolour="%s" size="%.3f">'
% (
enc(item.fontname),
bbox2str(item.bbox),
item.ncs.name,
item.graphicstate.ncolor,
item.size,
)
)
self.write(s)
self.write_text(item.get_text())
self.write("</text>\n")
elif isinstance(item, LTText):
self.write("<text>%s</text>\n" % item.get_text())
elif isinstance(item, LTImage):
if self.imagewriter is not None:
name = self.imagewriter.export_image(item)
self.write(
'<image src="%s" width="%d" height="%d" />\n'
% (enc(name), item.width, item.height)
)
else:
self.write(
'<image width="%d" height="%d" />\n' % (item.width, item.height)
)
figure = Figure(item)
self._add_unique_figure(figure)
else:
self._logger.warning("Unknown item: %r", item)
def receive_layout(self, ltpage: LTPage):
self._render(ltpage)
def close(self):
self.write_footer()
class ModelKeywords(LibraryContext):
"""Keywords for converting PDF document into specific RPA object model"""
FIELDS_ENCODING = "iso-8859-1"
@keyword
def convert(
self,
source_path: Optional[str] = None,
trim: bool = True,
pagenum: Optional[Union[int, str]] = None,
):
"""Parse source PDF into entities.
These entities can be used for text searches or XML dumping for example. The
conversion will be done automatically when using the dependent keywords
directly.
:param source_path: source PDF filepath
:param trim: trim whitespace from the text is set to True (default)
:param pagenum: Page number where search is performed on, defaults to `None`.
(meaning all pages get converted -- numbers start from 1)
**Examples**
**Robot Framework**
.. code-block:: robotframework
***Settings***
Library RPA.PDF
***Tasks***
Example Keyword
Convert /tmp/sample.pdf
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def example_keyword():
pdf.convert("/tmp/sample.pdf")
"""
self.ctx.switch_to_pdf(source_path)
converted_pages = self.active_pdf_document.has_converted_pages
if pagenum is not None:
pagenum = int(pagenum)
if pagenum in converted_pages:
return # specific page already converted
else:
pages_count = self.pages_count
if len(converted_pages) >= pages_count:
return # all pages got converted already
self.logger.debug(
"Converting active PDF document page %s on: %s",
pagenum if pagenum is not None else "<all>",
self.active_pdf_document.path,
)
rsrcmgr = PDFResourceManager()
if not self.ctx.convert_settings:
self.set_convert_settings()
laparams = pdfminer.layout.LAParams(**self.ctx.convert_settings)
device = Converter(
self.active_pdf_document,
rsrcmgr,
laparams=laparams,
trim=trim,
logger=self.logger,
# Also explicitly set by us when iterating pages for processing.
pageno=pagenum if pagenum is not None else 1,
)
interpreter = pdfminer.pdfinterp.PDFPageInterpreter(rsrcmgr, device)
# Look at all (nested) objects on each page.
source_parser = PDFParser(self.active_pdf_document.fileobject)
source_document = PDFDocument(source_parser)
source_pages = PDFPage.create_pages(source_document)
for idx, page in enumerate(source_pages, start=1):
# Process relevant pages only if instructed like so.
# (`pagenum` starts from 1 as well)
if pagenum is None or idx == pagenum:
if idx not in converted_pages:
# Skipping converted pages will leave this counter un-incremented,
# therefore we increment it explicitly.
device.pageno = idx
interpreter.process_page(page)
converted_pages.add(idx)
device.close()
@classmethod
def _decode_field(cls, binary: Optional[bytes], *, encoding) -> Optional[str]:
can_decode = binary is not None and hasattr(binary, "decode")
if not can_decode:
return binary
try:
return binary.decode(encoding)
except UnicodeDecodeError:
if encoding == cls.FIELDS_ENCODING:
raise
# Defaults to a fallback default encoding if the custom one fails.
return binary.decode(cls.FIELDS_ENCODING)
@keyword
def get_input_fields(
self,
source_path: Optional[str] = None,
replace_none_value: bool = False,
encoding: Optional[str] = FIELDS_ENCODING,
) -> dict:
"""Get input fields in the PDF.
Stores input fields internally so that they can be used without parsing the PDF
again.
:param source_path: Filepath to source, if not given use the currently active
PDF.
:param replace_none_value: Enable this to conveniently visualize the fields. (
replaces the null value with field's default or its name if absent)
:param encoding: Use an explicit encoding for field name/value parsing. (
defaults to "iso-8859-1" but "utf-8/16" might be the one working for you)
:returns: A dictionary with all the found fields. Use their key names when
setting values into them.
:raises KeyError: If no input fields are enabled in the PDF.
**Examples**
**Robot Framework**
.. code-block:: robotframework
Example Keyword
${fields} = Get Input Fields form.pdf
Log Dictionary ${fields}
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def example_keyword():
fields = pdf.get_input_fields("form.pdf")
print(fields)
example_keyword()
"""
self.ctx.switch_to_pdf(source_path)
active_document = self.active_pdf_document
active_fields = active_document.fields
if active_fields:
return active_fields
source_parser = PDFParser(active_document.fileobject)
source_document = PDFDocument(source_parser)
try:
miner_fields = pdfminer.pdftypes.resolve1(
source_document.catalog["AcroForm"]
)["Fields"]
pypdf_fields = active_document.reader.get_fields()
except KeyError as err:
raise KeyError(
f"PDF {active_document.path!r} does not have any input fields."
) from err
record_fields = {}
for miner_field in miner_fields:
field = pdfminer.pdftypes.resolve1(miner_field)
if field is None:
continue
name, value, label = (
self._decode_field(field.get("T"), encoding=encoding),
self._decode_field(field.get("V"), encoding=encoding),
self._decode_field(field.get("TU"), encoding=encoding),
)
raw_rect = field.get("Rect")
states = pypdf_fields.get(name, {}).get("/_States_")
if value is None and replace_none_value:
value = states[0] if states else name
parsed_field = {
"value": value,
"label": label or None,
"rect": iterable_items_to_ints(raw_rect),
"states": states,
}
record_fields[name] = parsed_field
active_document.fields = record_fields or None
return record_fields
@keyword
def set_field_value(
self, field_name: str, value: Any, source_path: Optional[str] = None
) -> None:
"""Set value for field with given name on the active document.
Tries to match with field's identifier directly or its label. When ticking
checkboxes, try with the `/Yes` string value as simply `Yes` might not work
with most previewing apps.
:param field_name: Field to update.
:param value: New value for the field.
:param source_path: Source PDF file path.
:raises ValueError: When field can't be found or more than one field matches
the given `field_name`.
**Examples**
**Robot Framework**
.. code-block:: robotframework
Example Keyword
Open PDF ./tmp/sample.pdf
Set Field Value phone_nr 077123123
Save Field Values output_path=./tmp/output.pdf
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def example_keyword():
pdf.open_pdf("./tmp/sample.pdf")
pdf.set_field_value("phone_nr", "077123123")
pdf.save_field_values(output_path="./tmp/output.pdf")
"""
fields = self.get_input_fields(source_path=source_path)
if not fields:
raise ValueError("Document does not have input fields.")
if field_name in fields.keys():
fields[field_name]["value"] = value # pylint: disable=E1136
else:
label_matches = 0
field_key = None
for key in fields.keys():
# pylint: disable=E1136
if fields[key]["label"] == field_name:
label_matches += 1
field_key = key
if label_matches == 1:
fields[field_key]["value"] = value # pylint: disable=E1136
elif label_matches > 1:
raise ValueError(
f"Unable to set field value - field name: {field_name!r} matched"
f" {label_matches} fields"
)
else:
raise ValueError(
f"Unable to set field value for {field_name!r}:"
" not found in the document"
)
@keyword
def save_field_values(
self,
source_path: Optional[str] = None,
output_path: Optional[str] = None,
newvals: Optional[dict] = None,
use_appearances_writer: bool = False,
) -> None:
"""Save field values in PDF if it has fields.
:param source_path: Source PDF with fields to update.
:param output_path: Updated target PDF.
:param newvals: New values when updating many at once.
:param use_appearances_writer: For some PDF documents the updated fields won't
be visible (or will look strange). When this happens, try to set this to
`True` so the previewer will re-render these based on the actual values.
(and viewing the output PDF in a browser might display the field values
correcly then)
**Examples**
**Robot Framework**
.. code-block:: robotframework
Example Keyword
Open PDF ./tmp/sample.pdf
Set Field Value phone_nr 077123123
Save Field Values output_path=./tmp/output.pdf
Multiple operations
&{new_fields}= Create Dictionary
... phone_nr=077123123
... title=dr
Save Field Values source_path=./tmp/sample.pdf
... output_path=./tmp/output.pdf
... newvals=${new_fields}
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def example_keyword():
pdf.open_pdf("./tmp/sample.pdf")
pdf.set_field_value("phone_nr", "077123123")
pdf.save_field_values(output_path="./tmp/output.pdf")
def multiple_operations():
new_fields = {"phone_nr": "077123123", "title": "dr"}
pdf.save_field_values(
source_path="./tmp/sample.pdf",
output_path="./tmp/output.pdf",
newvals=new_fields
)
"""
# NOTE(cmin764): The resulting PDF won't be a mutated version anymore and the
# fields can be retrieved and replaced again.
self.ctx.switch_to_pdf(source_path)
reader = self.active_pdf_document.reader
writer = pypdf.PdfWriter(clone_from=reader)
writer.set_need_appearances_writer(use_appearances_writer)
if newvals:
self.logger.debug(
"Updating form fields with the provided argument values for all pages"
)
updated_fields = newvals
elif self.active_pdf_document.fields:
self.logger.debug(
"Updating form fields with the set PDF values for all pages"
)
updated_fields = {
key: value["value"] or "" # should never pass a null value
for (key, value) in self.active_pdf_document.fields.items()
}
else:
self.logger.debug("No values available for updating the form fields")
updated_fields = {}
if updated_fields:
for page in writer.pages:
try:
writer.update_page_form_field_values(
page,
fields=updated_fields,
auto_regenerate=use_appearances_writer,
)
except Exception as exc: # pylint: disable=W0703
self.logger.warning(repr(exc))
if output_path is None:
output_path = self.active_pdf_document.path
with open(output_path, "wb") as stream:
try:
writer.write(stream)
except IndexError as exc:
raise ValueError(
"Output PDF saving failed, as there are required fields which"
" haven't been set. Enable `replace_none_value` when retrieving"
" the fields or pass them directly with `newvals` during save."
) from exc
@keyword
def dump_pdf_as_xml(self, source_path: Optional[str] = None) -> str:
"""Get PDFMiner format XML dump of the PDF
**Examples**
**Robot Framework**
.. code-block:: robotframework
***Settings***
Library RPA.PDF
***Tasks***
Example Keyword
${xml}= Dump PDF as XML /tmp/sample.pdf
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def example_keyword():
xml = pdf.dump_pdf_as_xml("/tmp/sample.pdf")
:param source_path: filepath to the source PDF
:return: XML content as a string
"""
self.convert(source_path)
return self.active_pdf_document.dump_xml()
@keyword
def set_convert_settings(
self,
line_margin: Optional[float] = None,
word_margin: Optional[float] = None,
char_margin: Optional[float] = None,
boxes_flow: Optional[float] = BOXES_FLOW_NOT_SET,
):
"""Change settings for PDFMiner document conversion.
`line_margin` controls how textboxes are grouped - if conversion results in
texts grouped into one group then set this to lower value
`word_margin` controls how spaces are inserted between words - if conversion
results in text without spaces then set this to lower value
`char_margin` controls how characters are grouped into words - if conversion
results in individual characters instead of then set this to higher value
`boxes_flow` controls how much horizontal and vertical position of the text
matters when determining the order of text boxes. Value can be between range
of -1.0 (only horizontal position matters) to +1.0 (only vertical position
matters). This feature (advanced layout analysis) can be disabled by setting
value to `None` thus bottom left corner of the text box is used to determine
order of the text boxes.
:param line_margin: relative margin between bounding lines, default 0.5
:param word_margin: relative margin between words, default 0.1
:param char_margin: relative margin between characters, default 2.0
:param boxes_flow: positioning of the text boxes based on text, default 0.5
**Examples**
**Robot Framework**
.. code-block:: robotframework
***Settings***
Library RPA.PDF
***Tasks***
Example Keyword
Set Convert Settings line_margin=0.00000001
${texts}= Get Text From PDF /tmp/sample.pdf
**Python**
.. code-block:: python
from RPA.PDF import PDF
pdf = PDF()
def example_keyword():
pdf.set_convert_settings(boxes_flow=None)
texts = pdf.get_text_from_pdf("/tmp/sample.pdf")
"""
self.ctx.convert_settings["detect_vertical"] = True
self.ctx.convert_settings["all_texts"] = True
if line_margin:
self.ctx.convert_settings["line_margin"] = line_margin
if char_margin:
self.ctx.convert_settings["char_margin"] = char_margin
if word_margin:
self.ctx.convert_settings["word_margin"] = word_margin
self.ctx.convert_settings["boxes_flow"] = boxes_flow | /rpaframework_pdf-7.2.0.tar.gz/rpaframework_pdf-7.2.0/src/RPA/PDF/keywords/model.py | 0.802013 | 0.27938 | model.py | pypi |
import logging
from collections import defaultdict
from difflib import SequenceMatcher
from pathlib import Path
from typing import Union, Dict, List, Generator, Optional
import pytesseract
from pytesseract import TesseractNotFoundError
from PIL import Image
from RPA.core import geometry
from RPA.core.geometry import Region
from RPA.recognition.utils import to_image, clamp
LOGGER = logging.getLogger(__name__)
# TODO: refer to conda package when created?
INSTALL_PROMPT = (
"tesseract is not installed or not in PATH, "
"see library documentation for installation instructions"
)
DEFAULT_CONFIDENCE = 80.0
def read(image: Union[Image.Image, Path]):
"""Scan image for text and return it as one string.
:param image: Path to image or Image object
"""
image = to_image(image)
try:
return pytesseract.image_to_string(image).strip()
except TesseractNotFoundError as err:
raise EnvironmentError(INSTALL_PROMPT) from err
def find(
image: Union[Image.Image, Path],
text: str,
confidence: float = DEFAULT_CONFIDENCE,
region: Optional[Region] = None,
language: Optional[str] = None,
):
"""Scan image for text and return a list of regions
that contain it (or something close to it).
:param image: Path to image or Image object
:param text: Text to find in image
:param confidence: Minimum confidence for text similaritys
:param region: Limit the region of the screen where to look for the text
:param language: 3-character ISO 639-2 language code of the text.
This is passed directly to the pytesseract lib in the lang parameter.
See https://tesseract-ocr.github.io/tessdoc/Command-Line-Usage.html#using-one-language
""" # noqa: E501
image = to_image(image)
confidence = clamp(1, float(confidence), 100)
text = str(text).strip()
if not text:
raise ValueError("Empty search string")
if region is not None:
region = geometry.to_region(region)
image = image.crop(region.as_tuple())
try:
data = pytesseract.image_to_data(
image, lang=language, output_type=pytesseract.Output.DICT
)
except TesseractNotFoundError as err:
raise EnvironmentError(INSTALL_PROMPT) from err
lines = _dict_lines(data)
matches = _match_lines(lines, text, confidence)
if region is not None:
for match in matches:
match["region"] = match["region"].move(region.left, region.top)
return matches
def _dict_lines(data: Dict) -> List:
lines = defaultdict(list)
for word in _iter_rows(data):
if word["level"] != 5:
continue
if not word["text"].strip():
continue
key = "{:d}-{:d}-{:d}".format(
word["block_num"], word["par_num"], word["line_num"]
)
region = Region.from_size(
word["left"], word["top"], word["width"], word["height"]
)
# NOTE: Currently ignoring confidence in tesseract results
lines[key].append({"text": word["text"], "region": region})
assert len(lines[key]) == word["word_num"]
return list(lines.values())
def _iter_rows(data: Dict) -> Generator:
"""Iterate dictionary of columns by row."""
return (dict(zip(data.keys(), values)) for values in zip(*data.values()))
def _match_lines(lines: List[Dict], text: str, confidence: float) -> List[Dict]:
"""Find best matches between lines of text and target text,
and return resulting bounding boxes and confidences.
A line of N words will be matched to the given text in all 1 to N
length sections, in every sequential position.
"""
matches = []
for line in lines:
match = {}
for window in range(1, len(line) + 1):
for index in range(len(line) - window + 1):
words = line[index : index + window]
regions = [word["region"] for word in words]
sentence = " ".join(word["text"] for word in words)
ratio = SequenceMatcher(None, sentence, text).ratio() * 100.0
if ratio < confidence:
continue
if match and match["confidence"] >= ratio:
continue
match = {
"text": sentence,
"region": Region.merge(regions),
"confidence": ratio,
}
if match:
matches.append(match)
return sorted(matches, key=lambda match: match["confidence"], reverse=True) | /rpaframework_recognition-5.2.0-py3-none-any.whl/RPA/recognition/ocr.py | 0.808635 | 0.400515 | ocr.py | pypi |
import logging
from pathlib import Path
from typing import Iterator, List, Optional, Union
import cv2
import numpy
from PIL import Image
from RPA.core import geometry
from RPA.core.geometry import Region
from RPA.recognition.utils import to_image, clamp, log2lin
DEFAULT_CONFIDENCE = 80.0
LIMIT_FAILSAFE = 256
LOGGER = logging.getLogger(__name__)
class ImageNotFoundError(Exception):
"""Raised when template matching fails."""
def find(
image: Union[Image.Image, Path],
template: Union[Image.Image, Path],
region: Optional[Region] = None,
limit: Optional[int] = None,
confidence: float = DEFAULT_CONFIDENCE,
) -> List[Region]:
"""Attempt to find the template from the given image.
:param image: Path to image or Image instance, used to search from
:param template: Path to image or Image instance, used to search with
:param limit: Limit returned results to maximum of `limit`.
:param region: Area to search from. Can speed up search significantly.
:param confidence: Confidence for matching, value between 1 and 100
:return: List of matching regions
:raises ImageNotFoundError: No match was found
"""
# Ensure images are in Pillow format
image = to_image(image)
template = to_image(template)
# Convert confidence value to tolerance
tolerance = _to_tolerance(confidence)
# Crop image if requested
if region is not None:
region = geometry.to_region(region)
image = image.crop(region.as_tuple())
# Verify template still fits in image
if template.size[0] > image.size[0] or template.size[1] > image.size[1]:
raise ValueError("Template is larger than search region")
# Do the actual search
matches: List[Region] = []
for match in _match_template(image, template, tolerance):
matches.append(match)
if limit is not None and len(matches) >= int(limit):
break
elif len(matches) >= LIMIT_FAILSAFE:
LOGGER.warning("Reached maximum of %d matches", LIMIT_FAILSAFE)
break
if not matches:
raise ImageNotFoundError("No matches for given template")
# Convert region coördinates back to full-size coördinates
if region is not None:
matches = [match.move(region.left, region.top) for match in matches]
return matches
def _to_tolerance(confidence):
"""Convert confidence value to tolerance.
Confidence is a logarithmic scale from 1 to 100,
tolerance is a linear scale from 0.01 to 1.00.
"""
value = float(confidence)
value = clamp(1, value, 100)
value = log2lin(1, value, 100)
value = value / 100.0
return value
def _match_template(
image: Image.Image, template: Image.Image, tolerance: float
) -> Iterator[Region]:
"""Use opencv's matchTemplate() to slide the `template` over
`image` to calculate correlation coefficients, and then
filter with a tolerance to find all relevant global maximums.
"""
template_width, template_height = template.size
if image.mode == "RGBA":
image = image.convert("RGB")
if template.mode == "RGBA":
template = template.convert("RGB")
image = numpy.array(image)
template = numpy.array(template)
# pylint: disable=no-member
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
template = cv2.cvtColor(template, cv2.COLOR_RGB2BGR)
# Template matching result is a single channel array of shape:
# Width: Image width - template width + 1
# Height: Image height - template height + 1
coefficients = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
coeff_height, coeff_width = coefficients.shape
while True:
# The point (match_x, match_y) is the top-left of the best match
_, match_coeff, _, (match_x, match_y) = cv2.minMaxLoc(coefficients)
if match_coeff < tolerance:
break
# Zero out values for a template-sized region around the best match
# to prevent duplicate matches for the same element.
left = clamp(0, match_x - template_width // 2, coeff_width)
top = clamp(0, match_y - template_height // 2, coeff_height)
right = clamp(0, match_x + template_width // 2, coeff_width)
bottom = clamp(0, match_y + template_height // 2, coeff_height)
coefficients[top:bottom, left:right] = 0
yield Region.from_size(match_x, match_y, template_width, template_height) | /rpaframework_recognition-5.2.0-py3-none-any.whl/RPA/recognition/templates.py | 0.942902 | 0.560614 | templates.py | pypi |
from PIL import Image
from pyscreenshot.plugins.backend import CBackend
from pyscreenshot.util import platform_is_osx
class Gdk3BackendError(Exception):
pass
class Gdk3PixbufWrapper(CBackend):
name = "pygdk3"
childprocess = False
def __init__(self):
pass
def grab(self, bbox=None):
"""Grabs an image directly to a buffer.
:param bbox: Optional tuple or list containing (x1, y1, x2, y2) coordinates
of sub-region to capture.
:return: PIL RGB image
:raises: ValueError, if image data does not have 3 channels (RGB), each with 8
bits.
:rtype: Image
"""
if platform_is_osx():
raise Gdk3BackendError("osx not supported") # TODO
import gi
gi.require_version("Gdk", "3.0")
# gi.require_version('GdkPixbuf', '2.0')
from gi.repository import Gdk
from gi.repository import GdkPixbuf
# read_pixel_bytes: New in version 2.32.
if GdkPixbuf.PIXBUF_MAJOR == 2:
if GdkPixbuf.PIXBUF_MINOR < 32:
raise ValueError(
"GdkPixbuf min supported version: 2.32 current:"
+ GdkPixbuf.PIXBUF_VERSION
)
w = Gdk.get_default_root_window()
if bbox is not None:
g = [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]]
else:
g = w.get_geometry()
pb = Gdk.pixbuf_get_from_window(w, *g)
if not pb:
raise Gdk3BackendError("empty buffer")
if pb.get_bits_per_sample() != 8:
raise Gdk3BackendError("Expected 8 bits per pixel.")
elif pb.get_n_channels() != 3:
raise Gdk3BackendError("Expected RGB image.")
# Read the entire buffer into a python bytes object.
# read_pixel_bytes: New in version 2.32.
pixel_bytes = pb.read_pixel_bytes().get_data() # type: bytes
width, height = g[2], g[3]
# Probably for SSE alignment reasons, the pixbuf has extra data in each line.
# The args after "raw" help handle this; see
# http://effbot.org/imagingbook/decoder.htm#the-raw-decoder
return Image.frombytes(
"RGB", (width, height), pixel_bytes, "raw", "RGB", pb.get_rowstride(), 1
)
def backend_version(self):
import gi
return ".".join(map(str, gi.version_info)) | /rpaframework-screenshot-0.4.2.tar.gz/rpaframework-screenshot-0.4.2/pyscreenshot/plugins/gdk3pixbuf.py | 0.658966 | 0.272217 | gdk3pixbuf.py | pypi |
from datetime import datetime
from typing import List, Optional
import fire
from comtypes import COMError
from pynput_robocorp import keyboard, mouse # pylint: disable=C0415
from RPA.core.windows.inspect import ElementInspector, RecordElement
recording: List[RecordElement] = []
def get_recording(show_sleeps: bool = False) -> str:
"""Get a list of the recorded steps after stopping clicking elements.
:param show_sleeps: Exclude recording sleeps when `False`.
:returns: The string report of the recorded elements.
"""
output = []
top_window = None
# NOTE(cmin764): Works with "Click" actions only for now.
action_name = "Click"
for item in recording:
if show_sleeps and item["type"] == "sleep":
output.append(f"Sleep {item['value']}s")
if item["type"] == "locator":
new_top = item["top"]
if not top_window or new_top != top_window:
output.append(
f"\nControl Window {new_top} # handle:{item['top_handle']}"
)
top_window = new_top
output.append(f"{action_name} {item['locator']}")
sep = "-" * 80
header = (
f"\n{sep}"
"\nCopy-paste the code below into your `*** Tasks ***` or `*** Keywords ***`"
f"\n{sep}\n"
)
result = "\n".join(output)
footer = f"\n\n{sep}"
return f"{header}{result}{footer}"
def start_recording(verbose: bool = False):
"""Start recording elements with mouse clicks.
Can be stopped by pressing the *ESC* key.
"""
recording_time: Optional[datetime] = None
recording.clear()
inspector = ElementInspector()
def on_click(x, y, button, pressed): # pylint: disable=W0613
nonlocal recording_time # pylint: disable=W0602
if not pressed:
return
inspect_time = datetime.now()
if recording_time:
timediff = inspect_time - recording_time
seconds = max(round(float(timediff.microseconds / 1000000.0), 1), 0.1)
recording.append({"type": "sleep", "value": seconds})
recording_time = inspect_time
try:
inspector.inspect_element(recording, verbose=verbose)
except (NotImplementedError, COMError) as err:
# At least in cases where Windows desktop is clicked as first event
# to capture, the recorder goes into some broken state where future
# clicks also fail to capture.
print(f"Could not capture element, got exception: {err}", flush=True)
key_listener.stop()
mouse_listener.stop()
def on_release(key):
if key == keyboard.Key.esc:
return False
return True
mouse_listener = mouse.Listener(on_click=on_click)
mouse_listener.start()
with keyboard.Listener(on_release=on_release) as key_listener:
print(
"Mouse recording started. Use ESC to stop recording.",
flush=True,
)
key_listener.join()
mouse_listener.stop()
the_recording = get_recording()
print(the_recording)
def main():
fire.Fire(start_recording) | /rpaframework_windows-7.4.0-py3-none-any.whl/RPA/Windows/main.py | 0.801548 | 0.191479 | main.py | pypi |
import inspect
from typing import List, Optional
from RPA.core.windows.elements import ElementMethods, StructureType
from RPA.core.windows.locators import Locator
from RPA.Windows.keywords import ActionNotPossible, keyword
class ElementKeywords(ElementMethods):
"""Keywords for handling Control elements"""
@keyword
def set_anchor(
self,
locator: Locator,
timeout: Optional[float] = None,
) -> None:
"""Set anchor to an element specified by the locator.
All following keywords using locators will use this element
as a root element. Specific use case could be setting
anchor to TableControl element and then getting column data
belonging to that TableControl element.
To release anchor call ``Clear Anchor`` keyword.
:param locator: string locator or Control element
:param timeout: timeout in seconds for element lookup (default 10.0)
Example:
.. code-block:: robotframework
Set Anchor type:Table name:Orders depth:16
FOR ${row} IN RANGE 200
${number}= Get Value name:number row ${row}
Exit For Loop If $number == ${EMPTY}
${sum}= Get Value name:sum row ${row}
Log Order number:${number} has sum:{sum}
END
Clear Anchor
"""
self.ctx.anchor_element = self.ctx.get_element(locator, timeout=timeout)
@keyword
def clear_anchor(self) -> None:
"""Clears control anchor set by ``Set Anchor``
This means that all following keywords accessing elements
will use active window or desktop as root element.
"""
self.ctx.anchor_element = None
@keyword
def print_tree(
self,
locator: Optional[Locator] = None,
max_depth: int = 8,
capture_image_folder: Optional[str] = None,
log_as_warnings: bool = False,
return_structure: bool = False,
) -> Optional[StructureType]:
"""Print a tree of control elements.
A Windows application structure can contain multilevel element structure.
Understanding this structure is crucial for creating locators. (based on
controls' details and their parent-child relationship)
This keyword can be used to output logs of application's element structure,
starting with the element defined by the provided `locator` as root. Switch
the `return_structure` parameter to `True` to get a tree of elements returned
as well. (off by default to save memory)
- The printed structure displays a tree prefixed with "depth" - "position" so
you know how deep (0 means root) in the tree you are and on what position
(1-indexed) the child you're looking for is.
- The returned structure is a dictionary with all the children flattened per
depth level. Additionally, these `WindowsElement` objects contain a relevant
locator composed of "root > path" which will help to identify the element in
the tree.
Portal example:
https://robocorp.com/portal/robot/robocorp/example-windows-element-path
:param locator: The root of the tree to output.
:param max_depth: Maximum depth level. (defaults to 8)
:param capture_image_folder: If set, controls' images will be captured in this
path.
:param log_as_warnings: Enables highlighted logs (at the beginning of the log
file as warnings) and increases visibility in the output console.
:param return_structure: A flattened tree with all the elements collated by
level will be returned if this is enabled.
:returns: Optionally a dictionary of children per depth level when
`return_structure` is enabled.
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Display Element Structure
${tree} = Print Tree Calculator > path:2|3|2|8
... return_structure=${True}
Log To Console ${tree}
**Example: Python**
.. code-block:: python
from RPA.Windows import Windows
lib = Windows()
tree = lib.print_tree("Calculator > path:2|3|2|8", return_structure=True)
print(tree)
"""
return super().print_tree(
locator=locator,
max_depth=max_depth,
capture_image_folder=capture_image_folder,
log_as_warnings=log_as_warnings,
return_structure=return_structure,
)
@keyword
def get_attribute(self, locator: Locator, attribute: str) -> str:
"""Get attribute value of the element defined by the locator.
:param locator: string locator or Control element
:param attribute: name of the attribute to get
:return: value of attribute
Example:
.. code-block:: robotframework
${id}= Get Attribute type:Edit name:firstname AutomationId
"""
# TODO. Add examples
element = self.ctx.get_element(locator)
attr = hasattr(element.item, attribute)
if not attr:
raise ActionNotPossible(
f"Element found with {locator!r} does not have {attribute!r} attribute"
)
if callable(attr):
raise ActionNotPossible(
f"Can't access attribute {attribute!r} of element {element!r}"
)
return str(getattr(element.item, attribute))
@keyword
def list_attributes(self, locator: Locator) -> List:
"""List all element attributes.
:param locator: string locator or Control element
:return: list of element attributes (strings)
"""
element = self.ctx.get_element(locator)
element_attributes = [e for e in dir(element.item) if not e.startswith("_")]
attributes = []
for attr_name in element_attributes:
attr = getattr(element.item, attr_name)
if not inspect.ismethod(attr):
attributes.append(attr_name)
return attributes | /rpaframework_windows-7.4.0-py3-none-any.whl/RPA/Windows/keywords/elements.py | 0.856707 | 0.449876 | elements.py | pypi |
import re
from pathlib import Path
from typing import Callable, Optional, Union
from RPA.core.windows.action import ActionMethods
from RPA.core.windows.locators import Locator, WindowsElement
from RPA.Windows import utils
from RPA.Windows.keywords import keyword
from RPA.Windows.keywords.context import ActionNotPossible
if utils.IS_WINDOWS:
import uiautomation as auto
PatternType = Union["auto.ValuePattern", "auto.LegacyIAccessiblePattern"]
def set_value_validator(expected: str, actual: str) -> bool:
"""Checks the passed against the final set value and returns status."""
return actual.strip() == expected.strip() # due to EOLs inconsistency
class ActionKeywords(ActionMethods):
"""Keywords for performing desktop actions."""
@keyword(tags=["action", "mouse"])
def click(
self,
locator: Locator,
wait_time: Optional[float] = None,
timeout: Optional[float] = None,
) -> WindowsElement:
"""Mouse click on element matching given locator.
Exception ``ActionNotPossible`` is raised if element does not
allow Click action.
:param locator: String locator or element object.
:param wait_time: time to wait after click, default is a
library `wait_time`, see keyword ``Set Wait Time``
:param timeout: float value in seconds, see keyword
``Set Global Timeout``
:return: WindowsElement object
Example:
.. code-block:: robotframework
Click id:button1
Click id:button2 offset:10,10
${element}= Click name:SendButton wait_time=5.0
"""
return self._mouse_click(locator, "Click", wait_time, timeout)
@keyword(tags=["action", "mouse"])
def double_click(
self,
locator: Locator,
wait_time: Optional[float] = None,
timeout: Optional[float] = None,
) -> WindowsElement:
"""Double mouse click on element matching given locator.
Exception ``ActionNotPossible`` is raised if element does not
allow Click action.
:param locator: String locator or element object.
:param wait_time: time to wait after click, default is a
library `wait_time`, see keyword ``Set Wait Time``
:param timeout: float value in seconds, see keyword
``Set Global Timeout``
:return: WindowsElement object
Example:
.. code-block:: robotframework
${element}= Double Click name:ResetButton
"""
return self._mouse_click(locator, "DoubleClick", wait_time, timeout)
@keyword(tags=["action", "mouse"])
def right_click(
self,
locator: Locator,
wait_time: Optional[float] = None,
timeout: Optional[float] = None,
) -> WindowsElement:
"""Right mouse click on element matching given locator.
Exception ``ActionNotPossible`` is raised if element does not
allow Click action.
:param locator: String locator or element object.
:param wait_time: time to wait after click, default is a
library `wait_time`, see keyword ``Set Wait Time``
:param timeout: float value in seconds, see keyword
``Set Global Timeout``
:return: WindowsElement object
Example:
.. code-block:: robotframework
${element}= Right Click name:MenuButton
"""
return self._mouse_click(locator, "RightClick", wait_time, timeout)
@keyword(tags=["action", "mouse"])
def middle_click(
self,
locator: Locator,
wait_time: Optional[float] = None,
timeout: Optional[float] = None,
) -> WindowsElement:
"""Right mouse click on element matching given locator.
Exception ``ActionNotPossible`` is raised if element does not
allow Click action.
:param locator: String locator or element object.
:param wait_time: time to wait after click, default is a
library `wait_time`, see keyword ``Set Wait Time``
:param timeout: float value in seconds, see keyword
``Set Global Timeout``
:return: WindowsElement object
Example:
.. code-block:: robotframework
${element}= Middle Click name:button2
"""
return self._mouse_click(locator, "MiddleClick", wait_time, timeout)
def _mouse_click(
self,
locator: Locator,
click_type: str,
wait_time: Optional[float],
timeout: Optional[float],
) -> WindowsElement:
click_wait_time: float = (
wait_time if wait_time is not None else self.ctx.wait_time
)
with self.set_timeout(timeout):
element = self.ctx.get_element(locator)
self._click_element(element, click_type, click_wait_time)
return element
def _click_element(
self, element: WindowsElement, click_type: str, click_wait_time: float
):
item = element.item
click_function = getattr(item, click_type, None)
if not click_function:
raise ActionNotPossible(
f"Element {element!r} does not have {click_type!r} attribute"
)
# Get a new fresh bounding box each time, since the element might have been
# moved from its initial spot.
rect = item.BoundingRectangle
if not rect or rect.width() == 0 or rect.height() == 0:
raise ActionNotPossible(
f"Element {element!r} is not visible for clicking, use a string"
" locator and ensure the root window is in focus"
)
# Attribute added in `RPA.core.windows.locators.LocatorMethods`.
offset: Optional[str] = getattr(item, "robocorp_click_offset", None)
offset_x: Optional[int] = None
offset_y: Optional[int] = None
log_message = f"{click_type}-ing element"
if offset:
# Now compute the new coordinates starting from the element center.
dist_x, dist_y = (int(dist.strip()) for dist in offset.split(","))
pos_x, pos_y = rect.xcenter() + dist_x, rect.ycenter() + dist_y
# If we pass the newly obtained absolute position to the clicking function
# that won't work as expected. You see (`help(item.Click)`), if the passed
# offset is positive then it gets relative to the left-top corner and if
# is negative then the right-bottom corner is used.
# Let's assume we end up with a positive relative offset. (using left-top
# fixed corner)
offset_x, offset_y = pos_x - rect.left, pos_y - rect.top
# If by any chance an offset is negative, it gets relative to the
# right-bottom corner, therefore adjust it accordingly.
if offset_x < 0:
offset_x -= rect.width()
if offset_y < 0:
offset_y -= rect.height()
log_message += f" with offset: {offset_x}, {offset_y}"
self.logger.debug(log_message)
click_function(
x=offset_x,
y=offset_y,
simulateMove=self.ctx.simulate_move,
waitTime=click_wait_time,
)
@keyword(tags=["action"])
def select(self, locator: Locator, value: str) -> WindowsElement:
"""Select a value on the passed element if such action is supported.
The ``ActionNotPossible`` exception is raised when the element does not allow
the `Select` action. This is usually used with combo box elements.
:param locator: String locator or element object.
:param value: String value to select on Control element
:returns: The controlled Windows element.
**Example: Robot Framework**
*** Settings ***
Library RPA.Windows
*** Tasks ***
Set Notepad Size
Select id:FontSizeComboBox 22
**Example: Python**
.. code-block:: python
from RPA.Windows import Windows
lib = Windows()
def set_notepad_size():
lib.select("id:FontSizeComboBox", "22")
"""
element = self.ctx.get_element(locator)
if hasattr(element.item, "Select"):
# NOTE(cmin764): This is not supposed to work on `*Pattern` or `TextRange`
# objects. (works with `Control`s and its derived flavors only, like a
# combobox)
element.item.Select(
value, simulateMove=self.ctx.simulate_move, waitTime=self.ctx.wait_time
)
else:
raise ActionNotPossible(
f"Element {locator!r} does not support selection (try with"
" `Set Value` instead)"
)
return element
@keyword(tags=["action", "keyboard"])
def send_keys(
self,
locator: Optional[Locator] = None,
keys: Optional[str] = None,
interval: float = 0.01,
wait_time: Optional[float] = None,
send_enter: bool = False,
):
"""Send keys to desktop, current window or to Control element
defined by given locator.
If ``locator`` is `None` then keys are sent to desktop.
Exception ``ActionNotPossible`` is raised if element does not
allow SendKeys action.
:param locator: Optional string locator or element object.
:param keys: The keys to send.
:param interval: Time between each sent key. (defaults to 0.01 seconds)
:param wait_time: Time to wait after sending all the keys. (defaults to
library's set value, see keyword ``Set Wait Time``)
:param send_enter: If `True` then the {Enter} key is pressed at the end of the
sent keys.
:returns: The element identified through `locator`.
Example:
.. code-block:: robotframework
Send Keys desktop {Ctrl}{F4}
Send Keys keys={Ctrl}{F4} # locator will be NONE, keys sent to desktop
Send Keys id:input5 username send_enter=${True}
${element}= Get Element id:pass
Send Keys ${element} password send_enter=${True}
"""
if locator:
element = self.ctx.get_element(locator).item
else:
element = auto
keys: str = keys or ""
if send_enter:
keys += "{Enter}"
if hasattr(element, "SendKeys"):
self.logger.info("Sending keys %r to element: %s", keys, element)
keys_wait_time = wait_time if wait_time is not None else self.ctx.wait_time
element.SendKeys(text=keys, interval=interval, waitTime=keys_wait_time)
else:
raise ActionNotPossible(
f"Element found with {locator!r} does not have 'SendKeys' attribute"
)
@keyword(tags=["action"])
def get_text(self, locator: Locator) -> str:
"""Get text from Control element defined by the locator.
Exception ``ActionNotPossible`` is raised if element does not
allow GetWindowText action.
:param locator: String locator or element object.
:return: value of WindowText attribute of an element
Example:
.. code-block:: robotframework
${date} = Get Text type:Edit name:"Date of birth"
"""
element = self.ctx.get_element(locator)
if hasattr(element.item, "GetWindowText"):
return element.item.GetWindowText()
raise ActionNotPossible(
f"Element found with {locator!r} does not have 'GetWindowText' attribute"
)
@staticmethod
def get_value_pattern(
element: WindowsElement,
) -> Optional[Callable[[], PatternType]]:
item: auto.Control = element.item
get_pattern: Optional[Callable] = getattr(
item, "GetValuePattern", getattr(item, "GetLegacyIAccessiblePattern", None)
)
return get_pattern
@keyword(tags=["action"])
def get_value(self, locator: Locator) -> Optional[str]:
"""Get the value of the element defined by the provided `locator`.
The ``ActionNotPossible`` exception is raised if the identified element doesn't
support value retrieval.
:param locator: String locator or element object.
:returns: Optionally the value of the identified element.
**Example: Robot Framework**
.. code-block:: robotframework
${value} = Get Value type:DataItem name:column1
**Example: Python**
.. code-block:: python
from RPA.Windows import Windows
lib_win = Windows()
text = lib_win.get_value("Rich Text Window")
print(text)
"""
element = self.ctx.get_element(locator)
get_value_pattern = self.get_value_pattern(element)
if get_value_pattern:
func_name = get_value_pattern.__name__
self.logger.info(
"Retrieving the element value with the %r method.", func_name
)
value_pattern = get_value_pattern()
return value_pattern.Value if value_pattern else None
raise ActionNotPossible(
f"Element found with {locator!r} doesn't support value retrieval"
)
def _set_value_with_pattern(
self,
value: str,
newline_string: str,
*,
action: str,
get_value_pattern: Callable[[], PatternType],
append: bool,
locator: Optional[Locator],
validator: Optional[Callable],
):
func_name = get_value_pattern.__name__
self.logger.info("%s the element value with the %r method.", action, func_name)
value_pattern = get_value_pattern()
current_value = value_pattern.Value if append else ""
expected_value = f"{current_value}{value}{newline_string}"
value_pattern.SetValue(expected_value)
if validator and not validator(expected_value, value_pattern.Value):
raise ValueError(
f"Element found with {locator!r} couldn't set value: {expected_value}"
)
def _set_value_with_keys(
self,
value: str,
newline_string: str,
*,
action: str,
element: WindowsElement,
append: bool,
locator: Optional[Locator],
validator: Optional[Callable],
):
self.logger.info(
"%s the element value with `Send Keys`. (no patterns found)", action
)
if newline_string or re.search("[\r\n]", value):
self.logger.warning(
"The `newline` switch and EOLs are ignored when setting a value"
" through keys! (insert them with the `enter` parameter only)"
)
get_text_pattern = getattr(element.item, "GetTextPattern", None)
get_text = (
lambda: get_text_pattern().DocumentRange.GetText()
if get_text_pattern
else None
)
if append:
current_value: str = get_text() or ""
else:
# Delete the entire present value inside.
self.send_keys(element, keys="{Ctrl}a{Del}")
current_value = ""
if value:
self.send_keys(element, keys=value, send_enter=False)
actual_value = get_text()
if actual_value is not None:
if validator and not validator(f"{current_value}{value}", actual_value):
raise ValueError(
f"Element found with {locator!r} couldn't send value"
f" through keys: {value}"
)
@keyword(tags=["action"])
def set_value(
self,
locator: Optional[Locator] = None,
value: Optional[str] = None,
append: bool = False,
enter: bool = False,
newline: bool = False,
send_keys_fallback: bool = True,
validator: Optional[Callable] = set_value_validator,
) -> WindowsElement:
"""Set value of the element defined by the locator.
*Note:* An anchor will work only on element structures where you can
rely on the stability of that root/child element tree, as remaining the same.
Usually these kind of structures are tables. (but not restricted to)
*Note:* It is important to set ``append=${True}`` if you want to keep the
current text in the element. Other option is to read the current text into a
variable, then modify that value as you wish and pass it to the ``Set Value``
keyword for a complete text replacement. (without setting the `append` flag)
The following exceptions may be raised:
- ``ActionNotPossible`` if the element does not allow the `SetValue` action
to be run on it nor having ``send_keys_fallback=${True}``.
- ``ValueError`` if the new value to be set can't be set correctly.
:param locator: String locator or element object.
:param value: String value to be set.
:param append: `False` for setting the value, `True` for appending it. (OFF by
default)
:param enter: Set it to `True` to press the *Enter* key at the end of the
input. (nothing is pressed by default)
:param newline: Set it to `True` to add a new line at the end of the value. (no
EOL included by default; this won't work with `send_keys_fallback` enabled)
:param send_keys_fallback: Tries to set the value by sending it through keys
if the main way of setting it fails. (enabled by default)
:param validator: Function receiving two parameters post-setting, the expected
and the current value, which returns `True` if the two values match. (by
default, the keyword will raise if the values are different, set this to
`None` to disable validation or pass your custom function instead)
:returns: The element object identified through the passed `locator`.
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Set Values In Notepad
Set Value type:DataItem name:column1 ab c # Set value to "ab c"
# Press ENTER after setting the value.
Set Value type:Edit name:"File name:" console.txt enter=${True}
# Add newline (manually) at the end of the string. (Notepad example)
Set Value name:"Text Editor" abc\\n
# Add newline with parameter.
Set Value name:"Text Editor" abc newline=${True}
# Clear Notepad window and start appending text.
Set Anchor name:"Text Editor"
# All the following keyword calls will use the anchor element as a
# starting point, UNLESS they specify a locator explicitly or
# `Clear Anchor` is used.
${time} = Get Time
# Clears with `append=${False}`. (default)
Set Value value=The time now is ${time}
# Append text and add a newline at the end.
Set Value value= and it's the task run time. append=${True}
... newline=${True}
# Continue appending and ensure a new line at the end by pressing
# the Enter key this time.
Set Value value=But this will appear on the 2nd line now.
... append=${True} enter=${True} validator=${None}
**Example: Python**
.. code-block:: python
from RPA.Windows import Windows
lib_win = Windows()
locator = "Document - WordPad > Rich Text Window"
elem = lib_win.set_value(locator, value="My text", send_keys_fallback=True)
text = lib_win.get_value(elem)
print(text)
"""
value = value or ""
if newline and enter:
self.logger.warning(
"Both `newline` and `enter` switches detected, expect to see multiple"
" new lines in the final text content."
)
newline_string = "\n" if newline else ""
element = self.ctx.get_element(locator)
get_value_pattern = self.get_value_pattern(element)
action = "Appending" if append else "Setting"
if get_value_pattern:
self._set_value_with_pattern(
value,
newline_string,
action=action,
get_value_pattern=get_value_pattern,
append=append,
locator=locator,
validator=validator,
)
elif send_keys_fallback:
self._set_value_with_keys(
value,
newline_string,
action=action,
element=element,
append=append,
locator=locator,
validator=validator,
)
else:
raise ActionNotPossible(
f"Element found with {locator!r} doesn't support value setting"
)
if enter:
self.logger.info("Inserting a new line by sending the *Enter* key.")
self.send_keys(element, keys="{Ctrl}{End}{Enter}")
return element
@keyword(tags=["action"])
def set_wait_time(self, wait_time: float) -> float:
"""Set library wait time for action keywords.
The wait_time is spent after each keyword performing
mouse or keyboard action.
Library default wait_time is `0.5`
Returns value of the previous wait_time value.
:param wait_time: float value (in seconds), e.g. `0.1`
:return: previous wait value
Example:
.. code-block:: robotframework
${old_wait_time}= Set Wait Time 0.2
"""
old_value = self.ctx.wait_time
self.logger.info("Previous wait time: %f", old_value)
self.ctx.wait_time = wait_time
self.logger.info("Current wait time: %f", self.ctx.wait_time)
return old_value
@keyword(tags=["action"])
def screenshot(self, locator: Locator, filename: Union[str, Path]) -> str:
"""Take a screenshot of the element defined by the locator.
An `ActionNotPossible` exception is raised if the element doesn't allow being
captured.
:param locator: String locator or element object.
:param filename: Image file name/path. (can be absolute/relative)
:raises ActionNotPossible: When the element can't be captured.
:returns: Absolute file path of the taken screenshot image.
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Take Screenshots
Screenshot desktop desktop.png
Screenshot subname:Notepad ${OUTPUT_DIR}${/}notepad.png
**Example: Python**
.. code-block:: python
from RPA.Windows import Windows
lib = Windows()
def take_screenshots():
lib.screenshot("desktop", "desktop.png")
lib.screenshot("subname:Notepad", "output/notepad.png")
"""
return super().screenshot(locator, filename)
@keyword(tags=["action"])
def set_global_timeout(self, timeout: float) -> float:
"""Set global timeout for element search. Applies also
to ``Control Window`` keyword.
By default, the library has a timeout of 10 seconds.
:param timeout: float value in seconds
:return: previous timeout value
Example:
.. code-block:: robotframework
${old_timeout}= Set Global Timeout 20
${old_timeout}= Set Global Timeout 9.5
"""
previous_timeout = self.ctx.global_timeout
self.ctx.global_timeout = timeout
auto.SetGlobalSearchTimeout(self.ctx.global_timeout)
return previous_timeout
@keyword(tags=["action"])
def set_focus(self, locator: Locator) -> None:
"""Set view focus to the element defined by the locator.
:param locator: String locator or element object.
Example:
.. code-block:: robotframework
Set Focus name:Buy type:Button
"""
element = self.ctx.get_element(locator)
if not hasattr(element.item, "SetFocus"):
raise ActionNotPossible(
f"Element found with {locator!r} does not have 'SetFocus' attribute"
)
element.item.SetFocus()
@keyword(tags=["action", "mouse"])
def drag_and_drop(
self,
source_element: Locator,
target_element: Locator,
speed: Optional[float] = 1.0,
copy: Optional[bool] = False,
wait_time: Optional[float] = 1.0,
):
"""Drag and drop the source element into target element.
:param source: source element for the operation
:param target: target element for the operation
:param speed: adjust speed of operation, bigger value means more speed
:param copy: on True does copy drag and drop, defaults to move
:param wait_time: time to wait after drop, default 1.0 seconds
Example:
.. code-block:: robotframework
# copying a file, report.html, from source (File Explorer) window
# into a target (File Explorer) Window
# locator
Drag And Drop
... name:C:\\temp type:Windows > name:report.html type:ListItem
... name:%{USERPROFILE}\\Documents\\artifacts type:Windows > name:"Items View"
... copy=True
Example:
.. code-block:: robotframework
# moving *.txt files into subfolder within one (File Explorer) window
${source_dir}= Set Variable %{USERPROFILE}\\Documents\\test
Control Window name:${source_dir}
${files}= Find Files ${source_dir}${/}*.txt
# first copy files to folder2
FOR ${file} IN @{files}
Drag And Drop name:${file.name} name:folder2 type:ListItem copy=True
END
# second move files to folder1
FOR ${file} IN @{files}
Drag And Drop name:${file.name} name:folder1 type:ListItem
END
""" # noqa: E501
source = self.ctx.get_element(source_element)
target = self.ctx.get_element(target_element)
try:
if copy:
auto.PressKey(auto.Keys.VK_CONTROL)
auto.DragDrop(
source.xcenter,
source.ycenter,
target.xcenter,
target.ycenter,
moveSpeed=speed,
waitTime=wait_time,
)
finally:
if copy:
self.click(source)
auto.ReleaseKey(auto.Keys.VK_CONTROL)
@keyword(tags=["action"])
def set_mouse_movement(self, simulate: bool) -> bool:
"""Enable or disable mouse movement simulation during clicks and other actions.
Returns the previous set value as `True`/`False`.
:param simulate: Decide whether to simulate the move. (OFF by default)
:returns: Previous state.
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Disable Mouse Move
${previous} = Set Mouse Movement ${True}
Log To Console Previous mouse simulation: ${previous} (now enabled)
**Example: Python**
.. code-block:: python
from RPA.Windows import Windows
lib_win = Windows()
previous = lib_win.set_mouse_movement(True)
print(f"Previous mouse simulation: {previous} (now enabled)")
"""
to_str = lambda state: "ON" if state else "OFF" # noqa: E731
previous = self.ctx.simulate_move
self.logger.info("Previous mouse movement simulation: %s", to_str(previous))
self.ctx.simulate_move = simulate
self.logger.info(
"Current mouse movement simulation: %s", to_str(self.ctx.simulate_move)
)
return previous | /rpaframework_windows-7.4.0-py3-none-any.whl/RPA/Windows/keywords/action.py | 0.938773 | 0.360208 | action.py | pypi |
from typing import List, Optional
from RPA.core.windows.locators import (
Locator,
LocatorMethods,
MatchObject,
WindowsElement,
)
from RPA.Windows import utils
from RPA.Windows.keywords import keyword
from RPA.Windows.keywords.context import with_timeout
if utils.IS_WINDOWS:
import uiautomation as auto
from uiautomation import Control
class LocatorKeywords(LocatorMethods):
"""Keywords for handling Windows locators."""
# NOTE(cmin764): Timeout is automatically set to `None` in the upper calls by the
# `with_timeout` decorator, so we alter the behaviour (context timeout setting)
# on the first call only.
@keyword
@with_timeout
def get_element(
self,
locator: Optional[Locator] = None,
search_depth: int = 8,
root_element: Optional[WindowsElement] = None,
timeout: Optional[float] = None,
) -> WindowsElement:
"""Get a Control Windows element defined by the locator.
The returned element can be used instead of a locator string for other keywords
accepting the `locator` parameter.
Keyword ``Get Attribute`` can be used to read element attribute values.
If `locator` is `None`, then the returned element will be in this priority:
1. `root_element` if provided.
2. Anchor element if that has been previously set with ``Set Anchor``.
3. Current active window if that has been set with ``Control Window``.
4. Last resort is the "Desktop" element.
:param locator: Locator as a string or as an element object.
:param search_depth: How deep the element search will traverse. (default 8)
:param root_element: Will be used as search root element object if provided.
:param timeout: After how many seconds (float) to give up on search. (see
keyword ``Set Global Timeout``)
:returns: The identified `WindowsElement` object.
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Set Text Into Notepad Window
Windows Run Notepad
Control Window subname:Notepad
${element} = Get Element regex:"Text (E|e)ditor"
Set Value ${element} note to myself
**Example: Python**
.. code-block:: python
from RPA.Windows import Windows
lib = Windows()
lib.windows_run("calc.exe")
one_btn = lib.get_element("Calculator > path:2|3|2|8|2")
lib.close_window("Calculator")
"""
return super().get_element(
locator=locator,
search_depth=search_depth,
root_element=root_element,
timeout=timeout,
)
@classmethod
def _search_siblings(
cls, initial_element: WindowsElement, *, locator: Optional[Locator]
) -> List[WindowsElement]:
elements = [initial_element]
element = initial_element
while True:
next_control = element.item.GetNextSiblingControl()
if not next_control:
break
element = WindowsElement(next_control, locator)
if initial_element.is_sibling(element):
# Every newly found matching element will inherit the offset set in the
# original initially found element.
element.item.robocorp_click_offset = (
initial_element.item.robocorp_click_offset
)
elements.append(element)
return elements
def _search_globally(
self,
initial_element: WindowsElement,
*,
locator: Optional[Locator],
search_depth: int,
root_element: Optional[WindowsElement],
timeout: Optional[float],
) -> List[WindowsElement]:
def get_first_child(ctrl: Control) -> Control:
return ctrl.GetFirstChildControl()
def get_next_sibling(ctrl: Control) -> Control:
return ctrl.GetNextSiblingControl()
def compare(ctrl: Control, _) -> bool:
element = WindowsElement(ctrl, locator)
return initial_element.is_sibling(element)
# Take all the elements (no matter their level) starting from a parent as
# search tree root.
parent_locator: Optional[str] = None
locator_str: Optional[str] = WindowsElement.norm_locator(locator)
if locator_str:
branches = locator_str.rsplit(MatchObject.TREE_SEP, 1)
if len(branches) == 2:
# Full locator's parent becomes the root for the search.
parent_locator = branches[0]
top_element = self.get_element(
# If the locator doesn't have a parent (null `parent_locator`) then simply
# rely on the resulting root resolution: root > anchor > window > Desktop.
parent_locator,
search_depth,
root_element,
timeout,
)
# Explore the entire subtree of elements starting from the resulted root above
# and keep only the ones matching the strategies in the last locator branch.
tree_generator = auto.WalkTree(
top_element.item,
getFirstChild=get_first_child,
getNextSibling=get_next_sibling,
yieldCondition=compare,
includeTop=not locator,
maxDepth=search_depth,
)
elements = []
for control, _ in tree_generator:
element = WindowsElement(control, locator)
# Every newly found matching element will inherit the offset set in the
# original initially found element.
element.item.robocorp_click_offset = (
initial_element.item.robocorp_click_offset
)
elements.append(element)
return elements
@keyword
@with_timeout
def get_elements(
self,
locator: Optional[Locator] = None,
search_depth: int = 8,
root_element: Optional[WindowsElement] = None,
timeout: Optional[float] = None,
siblings_only: bool = True,
) -> List[WindowsElement]:
"""Get a list of elements matching the locator.
By default, only the siblings (similar elements on the same level) are taken
into account. In order to search globally, turn `siblings_only` off, but be
aware that this will take more time to process.
For more details on the rest of parameters, take a look at the ``Get Element``
keyword.
:param locator: Locator as a string or as an element object.
:param search_depth: How deep the element search will traverse. (default 8)
:param root_element: Will be used as search root element object if provided.
:param timeout: After how many seconds (float) to give up on search. (see
keyword ``Set Global Timeout``)
:param siblings_only: Filter for elements on the same level as the initially
found one. Turn it off for a global search. (`True` by default)
:returns: A list of matching `WindowsElement` objects.
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Get Headers On Same Level
Set Anchor id:DataGrid
@{elements} = Get Elements type:HeaderItem
FOR ${element} IN @{elements}
Log To Console ${element.name}
END
Get All Calculator Buttons Matching Expression
Windows Run Calc
Control Window subname:Calc
@{buttons} = Get Elements class:Button regex:.*o.*
... siblings_only=${False}
Log List ${buttons}
${length} = Get Length ${buttons}
Log To Console Number of buttons: ${length}
"""
initial_element = self.get_element(locator, search_depth, root_element, timeout)
if siblings_only:
return self._search_siblings(initial_element, locator=locator)
return self._search_globally(
initial_element,
locator=locator,
search_depth=search_depth,
root_element=root_element,
timeout=timeout,
) | /rpaframework_windows-7.4.0-py3-none-any.whl/RPA/Windows/keywords/locators.py | 0.933188 | 0.372762 | locators.py | pypi |
import logging
import os
import platform
import shutil
import time
from pathlib import Path
from typing import Any, List, NamedTuple, Optional, Union
from robot.libraries.BuiltIn import BuiltIn
# Used for reading file ownership information
if platform.system() == "Windows":
import win32security
else:
from pwd import getpwuid
class TimeoutException(Exception):
"""Exception raised from wait-prefixed keywords"""
class File(NamedTuple):
"""Robot Framework -friendly container for files."""
path: str
name: str
size: int
mtime: float
def __str__(self):
return self.path
def __fspath__(self):
# os.PathLike interface
return self.path
@classmethod
def from_path(cls, path):
"""Create a File object from pathlib.Path or a path string."""
path = Path(path)
stat = path.stat()
return cls(
path=str(path.resolve()),
name=path.name,
size=stat.st_size,
mtime=stat.st_mtime,
)
class Directory(NamedTuple):
"""Robot Framework -friendly container for directories."""
path: str
name: str
def __str__(self):
return self.path
def __fspath__(self):
# os.PathLike interface
return self.path
@classmethod
def from_path(cls, path):
"""Create a directory object from pathlib.Path or a path string."""
path = Path(path)
return cls(str(path.resolve()), path.name)
class FileSystem:
"""The `FileSystem` library can be used to interact with files and directories
on the local computer. It can inspect and list files, remove and create them,
read contents from files, and write data out.
It shadows the built-in `OperatingSystem` library but contains keywords
which are more RPA-oriented.
**Examples**
**Robot Framework**
The library allows, for instance, iterating over files and inspecting them.
.. code-block:: robotframework
*** Settings ***
Library RPA.FileSystem
*** Keywords ***
Delete large files
${files}= List files in directory archive/orders/
FOR ${file} IN @{FILES}
Run keyword if ${file.size} > 10**8 Remove file ${file}
END
Read process output
Start external program
Wait until modified process.log
${output}= Read file process.log
[Return] ${output}
**Python**
The library can also be used inside Python.
.. code-block:: python
from RPA.FileSystem import FileSystem
def move_to_archive():
lib = FileSystem()
matches = lib.find_files("**/*.xlsx")
if matches:
lib.create_directory("archive")
lib.move_files(matches, "archive")
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
PATH_TYPE = Union[str, Path]
def __init__(self):
self.logger = logging.getLogger(__name__)
def find_files(
self,
pattern: Union[str, Path],
include_dirs: bool = True,
include_files: bool = True,
) -> list:
"""Find files recursively according to a pattern.
:param pattern: search path in glob format pattern,
e.g. *.xls or **/orders.txt
:param include_dirs: include directories in results (defaults to True)
:param include_files: include files in results (defaults to True)
:return: list of paths that match the pattern
Example:
.. code-block:: robotframework
*** Tasks ***
Finding files recursively
${files}= Find files **/*.log
FOR ${file} IN @{files}
Read file ${file}
END
"""
pattern = Path(pattern)
if pattern.is_absolute():
root = Path(pattern.anchor)
parts = pattern.parts[1:]
else:
root = Path.cwd()
parts = pattern.parts
pattern = str(Path(*parts))
matches = []
for path in root.glob(pattern):
if path == root:
continue
if path.is_dir() and include_dirs:
matches.append(Directory.from_path(path))
elif path.is_file() and include_files:
matches.append(File.from_path(path))
return sorted(matches)
def list_files_in_directory(self, path: Optional[PATH_TYPE] = None) -> list:
"""Lists all the files in the given directory, relative to it.
:param path: base directory for search, defaults to current working directory
:return: list of files in directory
Example:
.. code-block:: robotframework
*** Tasks ***
List directory file
${files}= List files in directory output
FOR ${file} IN @{files}
Log ${file}
END
"""
path = path or Path.cwd()
return self.find_files(Path(path, "*"), include_dirs=False)
def list_directories_in_directory(self, path: Optional[PATH_TYPE] = None) -> list:
"""Lists all the directories in the given directory, relative to it.
:param path: base directory for search, defaults to current working dir
:return: list of directories in selected directory
Example:
.. code-block:: robotframework
*** Tasks ***
List directories
${directories}= List directories in directory devdata
FOR ${path} IN @{directories}
Log ${path}
END
"""
path = path or Path.cwd()
return self.find_files(Path(path, "*"), include_files=False)
def log_directory_tree(self, path: Optional[PATH_TYPE] = None) -> None:
"""Logs all the files in the directory recursively.
:param path: base directory to start from, defaults to current working dir
Example:
.. code-block:: robotframework
*** Tasks ***
List directory tree
Log directory tree
"""
root = Path(path) if path else Path.cwd()
files = self.find_files(Path(root, "**/*"))
rows = []
previous = None
for current in files:
current = Path(current)
if previous is None:
shared = root
elif previous == current.parent:
shared = previous
else:
shared = set(previous.parents) & set(current.parents)
shared = max(shared) if shared else root
previous = current
indent = " " * len(shared.parts)
relative = current.relative_to(shared)
rows.append(f"{indent}{relative}")
self.logger.info("\n".join(rows))
def does_file_exist(self, path: PATH_TYPE) -> bool:
"""Returns True if the given file exists, False if not.
:param path: path to inspected file
:return: true or false if file exists
Example:
.. code-block:: robotframework
*** Tasks ***
Check for file
${log_exists}= Does file exist output/log.html
IF ${log_exists}
${file}= Find files output/log.html
Open user browser ${file}[0]
END
"""
return bool(self.find_files(path, include_dirs=False))
def does_file_not_exist(self, path: PATH_TYPE) -> bool:
# pylint: disable=anomalous-backslash-in-string
"""Returns True if the file does not exist, False if it does.
See ``Does File Exist`` for usage example.
:param path: path to inspected file
:return: true or false if the files does not exist
""" # noqa: W605
return not self.does_file_exist(path)
def does_directory_exist(self, path: PATH_TYPE) -> bool:
# pylint: disable=anomalous-backslash-in-string
"""Returns True if the given directory exists, False if not.
See ``Does Directory Not Exist`` for usage example.
:param path: path to inspected directory
:return: true or false if the directory exists
""" # noqa: W605
return bool(self.find_files(path, include_files=False))
def does_directory_not_exist(self, path: PATH_TYPE) -> bool:
"""Returns True if the directory does not exist, False if it does.
:param path: path to inspected directory
:return: true or false if the directory does not exists
Example:
.. code-block:: robotframework
*** Tasks ***
Check for directory
${directory_exists}= Does directory not exist output
IF ${directory_exists} Create directory output
"""
return not self.does_directory_exist(path)
def is_directory_empty(self, path: Optional[PATH_TYPE] = None) -> bool:
"""Returns True if the given directory has no files or subdirectories.
:param path: path to inspected directory
:return: true or false if the directory is empty
Example:
.. code-block:: robotframework
*** Tasks ***
Check for empty directory
${directory_empty}= Is directory empty output
IF ${directory_empty}
Copy file ${source} output/new_file.txt
END
"""
path = path or Path.cwd()
if self.does_directory_not_exist(path):
raise NotADirectoryError(f"Not a valid directory: {path}")
return not bool(self.find_files(Path(path, "*")))
def is_directory_not_empty(self, path: Optional[PATH_TYPE] = None) -> bool:
# pylint: disable=anomalous-backslash-in-string
"""Returns True if the given directory has any files or subdirectories.
See ``Is Directory Empty`` for usage example.
:param path: path to inspected directory
:return: true or false if the directory is not empty
""" # noqa: W605
return not self.is_directory_empty(path)
def is_file_empty(self, path: PATH_TYPE) -> bool:
"""Returns True if the given file has no content, i.e. has zero size.
:param path: path to inspected file
:return: true or false if the file is empty
"""
if self.does_file_not_exist(path):
raise FileNotFoundError(f"Not a valid file: {path}")
path = Path(path)
return path.stat().st_size == 0
def is_file_not_empty(self, path: PATH_TYPE) -> bool:
"""Returns True if the given file has content, i.e. larger than zero size.
:param path: path to inspected file
:return: true or false if the file is not empty
Example:
.. code-block:: robotframework
*** Tasks ***
Check for empty file
${file_empty}= Is file not empty output/log.html
IF ${file_empty}
Copy file output/log.html ${alt_dir}
END
"""
return not self.is_file_empty(path)
def read_file(self, path: PATH_TYPE, encoding: str = "utf-8") -> str:
# pylint: disable=anomalous-backslash-in-string
"""Reads a file as text, with given `encoding`, and returns the content."
See ``Find Files`` for usage example.
:param path: path to file to read
:param encoding: character encoding of file (default ``utf-8``)
:return: file content as string
""" # noqa: W605
with open(path, "r", encoding=encoding) as fd:
return fd.read()
def read_binary_file(self, path: PATH_TYPE) -> bytes:
"""Reads a file in binary mode and returns the content.
Does not attempt to decode the content in any way.
:param path: path to file to read
:return: the file content as bytes
Example:
.. code-block:: robotframework
*** Tasks ***
Read picture as binary
${pictures}= Find files **/*.png
FOR ${picture} IN @{pictures}
Read binary file ${picture}
END
"""
with open(path, "rb") as fd:
return fd.read()
def touch_file(self, path: PATH_TYPE) -> None:
"""Creates a file with no content, or if file already exists,
updates the modification and access times.
:param path: path to file which is touched
"""
Path(path).touch()
def create_file(
self,
path: PATH_TYPE,
content: Optional[str] = None,
encoding: str = "utf-8",
overwrite: bool = False,
) -> None:
"""Creates a new text file, and writes content if any is given.
:param path: path to file to write
:param content: content to write to file (optional)
:param encoding: character encoding of written content (default ``utf-8``)
:param overwrite: replace destination file if it already
exists (default ``False``)
Example:
.. code-block:: robotframework
*** Tasks ***
Create a new file
${content}= Get url=https://www.example.com
Create file output/newfile.html content=${content.text}
... overwrite=${True}
"""
if not overwrite and Path(path).exists():
raise FileExistsError(f"Path already exists: {path}")
with open(path, "w", encoding=encoding) as fd:
if content:
fd.write(content)
def create_binary_file(
self, path: PATH_TYPE, content: Optional[Any] = None, overwrite: bool = False
) -> None:
"""Creates a new binary file, and writes content if any is given.
:param path: path to file to write
:param content: content to write to file (optional)
:param overwrite: replace destination file if it already exists
Example:
.. code-block:: robotframework
*** Tasks ***
Create a new file
${content}= Get
... url=https://file-examples.com/storage/fe88505b6162b2538a045ce/2017/10/file_example_JPG_100kB.jpg
Create binary file output/sample.jpg content=${content.content} overwrite=${True}
""" # noqa: E501
if not overwrite and Path(path).exists():
raise FileExistsError(f"Path already exists: {path}")
with open(path, "wb") as fd:
if content:
fd.write(content)
def append_to_file(
self, path: PATH_TYPE, content: str, encoding: str = "utf-8"
) -> None:
# pylint: disable=anomalous-backslash-in-string
"""Appends text to the given file.
See ``Create File`` for usage example.
:param path: path to file to append to
:param content: content to append
:param encoding: character encoding of appended content
""" # noqa: W605
if not Path(path).exists():
raise FileNotFoundError(f"File does not exist: {path}")
with open(path, "a", encoding=encoding) as fd:
fd.write(content)
def append_to_binary_file(self, path: PATH_TYPE, content: Any) -> None:
# pylint: disable=anomalous-backslash-in-string
"""Appends binary content to the given file.
See ``Create Binary File`` for usage example.
:param path: path to file to append to
:param content: content to append
""" # noqa: W605
if not Path(path).exists():
raise FileNotFoundError(f"File does not exist: {path}")
with open(path, "ab") as fd:
fd.write(content)
def create_directory(
self, path: PATH_TYPE, parents: bool = False, exist_ok: bool = True
) -> None:
"""Creates a directory and (optionally) non-existing parent directories.
:param path: path to new directory
:param parents: create missing parent directories (defaults to ``False``)
:param exist_ok: continue without errors if directory
already exists (defaults to ``True``)
Example:
.. code-block:: robotframework
*** Tasks ***
Create new path
Create directory output/my/new/path parents=${True}
"""
Path(path).mkdir(parents=parents, exist_ok=exist_ok)
def remove_file(self, path: PATH_TYPE, missing_ok: bool = True) -> None:
"""Removes the given file.
:param path: path to the file to remove
:param missing_ok: ignore non-existent file (defaults to ``True``)
Example:
.. code-block:: robotframework
*** Tasks ***
Delete a file
Remove file output/log.html
"""
try:
Path(path).unlink()
except FileNotFoundError:
if not missing_ok:
raise
def remove_files(self, *paths: PATH_TYPE, missing_ok: bool = True) -> None:
"""Removes multiple files.
:param paths: paths to files to be removed
:param missing_ok: ignore non-existent files (default to ``True``)
Example:
.. code-block:: robotframework
*** Tasks ***
Delete some files
Remove files output/log.html output/output.xml
"""
# TODO: glob support
for path in paths:
self.remove_file(path, missing_ok=missing_ok)
def remove_directory(self, path: PATH_TYPE, recursive: bool = False) -> None:
"""Removes the given directory, and optionally everything it contains.
:param path: path to directory
:param recursive: remove all subdirectories and files (default to ``False``)
Example:
.. code-block:: robotframework
*** Tasks ***
Delete a directory
Remove directory output recursive=${True}
"""
if recursive:
shutil.rmtree(str(path))
else:
Path(path).rmdir()
def empty_directory(self, path: PATH_TYPE) -> None:
"""Removes all the files in the given directory.
:param path: directory to remove files from
Example:
.. code-block:: robotframework
*** Tasks ***
Empty out directory
Empty directory output
"""
# TODO: Should it remove all subdirectories too?
for item in self.list_files_in_directory(path):
filepath = Path(path, item.name)
self.remove_file(filepath)
self.logger.info("Removed file: %s", filepath)
def copy_file(self, source: PATH_TYPE, destination: PATH_TYPE) -> None:
# pylint: disable=anomalous-backslash-in-string
"""Copy a file from source path to destination path.
See ``Is Directory Empty`` for usage example.
:param source: path to source file
:param destination: path to copy destination
""" # noqa: W605
src = Path(source)
dst = Path(destination)
if not src.is_file():
raise FileNotFoundError(f"Source '{src}' is not a file")
shutil.copyfile(src, dst)
self.logger.info("Copied file: %s -> %s", src, dst)
def copy_files(self, sources: List[PATH_TYPE], destination: PATH_TYPE) -> None:
"""Copy multiple files to destination folder.
:param sources: list of source files
:param destination: path to destination folder
Example:
.. code-block:: robotframework
*** Tasks ***
Copy some files
${files}= Find files devdata/*.json
Copy files ${files} output
"""
# TODO: glob support
dst_dir = Path(destination)
if not dst_dir.is_dir():
raise NotADirectoryError(f"Destination '{dst_dir}' is not a directory")
for src in sources:
name = src.name if isinstance(src, File) else Path(src).name
dst = Path(dst_dir, name)
self.copy_file(src, dst)
def copy_directory(self, source: PATH_TYPE, destination: PATH_TYPE) -> None:
"""Copy directory from source path to destination path.
:param source: path to source directory
:param destination: path to copy destination
Example:
.. code-block:: robotframework
*** Tasks ***
Copy a directory
Copy directory output temp
"""
src = Path(source)
dst = Path(destination)
if not src.is_dir():
raise NotADirectoryError(f"Source {src} is not a directory")
if dst.exists():
raise FileExistsError(f"Destination {dst} already exists")
shutil.copytree(src, dst)
def move_file(
self, source: PATH_TYPE, destination: PATH_TYPE, overwrite: bool = False
) -> None:
"""Move a file from source path to destination path,
optionally overwriting the destination.
:param source: source file path for moving
:param destination: path to move to
:param overwrite: replace destination file if it already
exists (defaults to ``False``)
Example:
.. code-block:: robotframework
*** Tasks ***
Move a file
Create directory temp
Move file output/log.html temp/log.html
"""
src = Path(source)
dst = Path(destination)
if not src.is_file():
raise FileNotFoundError(f"Source {src} is not a file")
if dst.exists() and not overwrite:
raise FileExistsError(f"Destination {dst} already exists")
src.replace(dst)
self.logger.info("Moved file: %s -> %s", src, dst)
def move_files(
self, sources: List[PATH_TYPE], destination: PATH_TYPE, overwrite: bool = False
) -> None:
"""Move multiple files to the destination folder.
:param sources: list of files to move
:param destination: path to move destination
:param overwrite: replace destination files if they already exist
Example:
.. code-block:: robotframework
*** Tasks ***
Move some files
Create directory temp
Move files output/log.html output/output.xml temp
"""
dst_dir = Path(destination)
if not dst_dir.is_dir():
raise NotADirectoryError(f"Destination '{dst_dir}' is not a directory")
for src in sources:
dst = Path(dst_dir, Path(src).name)
self.move_file(str(src), dst, overwrite)
def move_directory(
self, source: PATH_TYPE, destination: PATH_TYPE, overwrite: bool = False
) -> None:
"""Move a directory from source path to destination path.
:param source: source directory path for moving
:param destination: path to move to
:param overwrite: replace destination directory if it already
exists (defaults to ``False``)
Example:
.. code-block:: robotframework
*** Tasks ***
Move a directory
Move directory output temp
"""
src = Path(source)
dst = Path(destination)
if not src.is_dir():
raise NotADirectoryError(f"Source {src} is not a directory")
if dst.exists() and not overwrite:
raise FileExistsError(f"Destination {dst} already exists")
src.replace(dst)
def change_file_extension(self, path: PATH_TYPE, extension: str) -> None:
"""Replaces file extension for file at given path. the file
extension can be removed by passing an empty string.
:param path: path to file to rename
:param extension: new extension, e.g. .xlsx
Example:
.. code-block:: robotframework
*** Tasks ***
Change a file extension
Change file extension
... devdata/work-items-in/default/orders.xls
... .xlsx
"""
dst = Path(path).with_suffix(extension)
self.move_file(path, dst)
def join_path(self, *parts: PATH_TYPE) -> str:
"""Joins multiple parts of a path together.
:param parts: Components of the path, e.g. dir, subdir, filename.ext
:return: complete file path as a single string
Example:
.. code-block:: robotframework
*** Tasks ***
Join path together
Join path output/nested folder
"""
parts = [str(part) for part in parts]
return str(Path(*parts))
def absolute_path(self, path: PATH_TYPE) -> str:
"""Returns the absolute path to a file, and resolves symlinks.
:param path: path that will be resolved
:return: absolute path to file as a string
"""
return str(Path(path).resolve())
def normalize_path(self, path: PATH_TYPE) -> str:
"""Removes redundant separators or up-level references from path.
:param path: path that will be normalized
:return: path to file as a string
Example:
.. code-block:: robotframework
*** Tasks ***
Get normal path
# Normalized path becomes ../inputs/input.xlsx
${normalized_path}= Normalize path ..//inputs/./new/../input.xlsx
Create work items ${normalized_path}
"""
return str(os.path.normpath(Path(path)))
def get_file_name(self, path: PATH_TYPE) -> str:
"""Returns only the full file name portion of a path.
:param path: path to file
:return: filename portion of a path as a string
"""
return Path(path).name
def get_file_stem(self, path: PATH_TYPE) -> str:
"""Returns the name of the file without its extension.
:param path: path to file
:return: filename without its suffix as a string
"""
return Path(path).stem
def get_file_extension(self, path: PATH_TYPE) -> str:
"""Returns the suffix for the file.
:param path: path to file
:return: file suffix as a string
"""
return Path(path).suffix
def get_file_modified_date(self, path: PATH_TYPE) -> float:
"""Returns the modified time in seconds.
:param path: path to file to inspect
:return: modified time in seconds as a float
"""
# TODO: Convert to proper date
return Path(path).stat().st_mtime
def get_file_creation_date(self, path: PATH_TYPE) -> float:
"""Returns the creation time in seconds.
Note: Linux sets this whenever file metadata changes
:param path: path to file to inspect
:return: creation time in seconds as a float
"""
# TODO: Convert to proper date
return Path(path).stat().st_ctime
def get_file_size(self, path: PATH_TYPE) -> int:
"""Returns the file size in bytes.
:param path: path to file to inspect
:return: file size in bytes as an int
"""
# TODO: Convert to human-friendly?
return Path(path).stat().st_size
def get_file_owner(self, path: PATH_TYPE) -> str:
"""Return the name of the user who owns the file.
:param path: path to file to inspect
:return: file owner as a string
"""
path = Path(path)
if platform.system() == "Windows":
desc = win32security.GetFileSecurity(
str(path), win32security.OWNER_SECURITY_INFORMATION
)
sid = desc.GetSecurityDescriptorOwner()
name, _, _ = win32security.LookupAccountSid(None, sid)
else:
sid = path.stat().st_uid
name = getpwuid(sid).pw_name
return name
def _wait_file(self, path, condition, timeout) -> bool:
"""Poll file with `condition` callback until it returns True,
or timeout is reached.
"""
path = Path(path)
end_time = time.time() + float(timeout)
while time.time() < end_time:
if condition(path):
return True
time.sleep(0.1)
return False
def wait_until_created(
self, path: PATH_TYPE, timeout: Union[int, float] = 5.0
) -> str:
"""Poll path until it exists, or raise exception if timeout
is reached.
:param path: path to poll
:param timeout: time in seconds until keyword fails
:return: path to the created file as a string
Example:
.. code-block:: robotframework
*** Tasks ***
Wait for existence
Wait until created orders.xlsx 10
Process orders orders.xlsx
"""
if not self._wait_file(path, lambda p: p.exists(), timeout):
raise TimeoutException("Path was not created within timeout")
return File.from_path(path)
def wait_until_modified(
self, path: PATH_TYPE, timeout: Union[int, float] = 5.0
) -> str:
"""Poll path until it has been modified after the keyword was called,
or raise exception if timeout is reached.
:param path: path to poll
:param timeout: time in seconds until keyword fails
:return: path to the modified file as a string
Example:
.. code-block:: robotframework
*** Tasks ***
Wait for change
Wait until modified orders.xlsx 10
Process orders orders.xlsx
"""
now = time.time()
if not self._wait_file(path, lambda p: p.stat().st_mtime >= now, timeout):
raise TimeoutException("Path was not modified within timeout")
return File.from_path(path)
def wait_until_removed(
self, path: PATH_TYPE, timeout: Union[int, float] = 5.0
) -> None:
"""Poll path until it doesn't exist, or raise exception if timeout
is reached.
:param path: path to poll
:param timeout: time in seconds until keyword fails
"""
if not self._wait_file(path, lambda p: not p.exists(), timeout):
raise TimeoutException("Path was not removed within timeout")
def run_keyword_if_file_exists(self, path: PATH_TYPE, keyword: str, *args) -> None:
"""If file exists at `path`, execute given keyword with arguments.
:param path: path to file to inspect
:param keyword: Robot Framework keyword to execute
:param args: arguments to keyword
Example:
.. code:: robotframework
*** Tasks ***
Execute if orders exists
Run keyword if file exists orders.xlsx Process orders
"""
if self.does_file_exist(path):
return BuiltIn().run_keyword(keyword, *args)
else:
self.logger.info("File %s does not exist", path)
return None | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/FileSystem.py | 0.869535 | 0.241523 | FileSystem.py | pypi |
import json
import logging
from typing import Any, Callable, Dict, Hashable, List, Optional, Union
from jsonpath_ng import Index, Fields
from jsonpath_ng.ext.filter import Filter
from jsonpath_ng.ext.parser import ExtentedJsonPathParser
from robot.api.deco import keyword
JSONValue = Optional[Union[str, int, float, bool, list, dict]]
JSONType = Union[Dict[Hashable, JSONValue], List[JSONValue], JSONValue]
class RPAFilter(Filter):
"""Extends default filtering JSON path logic."""
def filter(self, fn: Callable[[JSONType], bool], data: JSONType) -> JSONType:
for datum in reversed(self.find(data)):
index_obj = datum.path
if isinstance(data, dict):
index_obj.index = list(data)[index_obj.index]
index_obj.filter(fn, data)
return data
class RPAJsonPathParser(ExtentedJsonPathParser):
"""Extends the default JSON path parser found in `jsonpath_ng.ext`."""
def p_filter(self, p):
"""filter : '?' expressions"""
p[0] = RPAFilter(p[2])
def parse(path: str, debug: bool = False) -> RPAJsonPathParser:
return RPAJsonPathParser(debug=debug).parse(path)
class JSON:
r"""`JSON` is a library for manipulating `JSON`_ files and strings.
JSON is a common data interchange format inspired by a subset of
the Javascript programming language, but these days is a de facto
standard in modern web APIs and is language agnostic.
.. _JSON: http://json.org/
Serialization
=============
The term `serialization` refers to the process of converting
Robot Framework or Python types to JSON or the other way around.
Basic types can be easily converted between the domains,
and the mapping is as follows:
============= =======
JSON Python
============= =======
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None
============= =======
About JSONPath
==============
Reading and writing values from/to JSON serializable objects is done
using `JSONPath`_. It's a syntax designed to quickly and easily refer to
specific elements in a JSON structure. The specific flavor used in this
library is based on `jsonpath-ng`_.
Compared to Python's normal dictionary access, JSONPath expressions can
target multiple elements through features such as conditionals and wildcards,
which can simplify many JSON-related operations. It's analogous to XPath
for XML structures.
.. _JSONPath: http://goessner.net/articles/JsonPath/
.. _jsonpath-ng: https://pypi.org/project/jsonpath-ng/#description
Syntax example
--------------
For this example consider the following structure:
.. code-block:: json
{
"clients": [
{
"name": "Johnny Example",
"email": "john@example.com",
"orders": [
{"address": "Streetroad 123", "price": 103.20},
{"address": "Streetroad 123", "price": 98.99}
]
},
{
"name": "Jane Example",
"email": "jane@example.com",
"orders": [
{"address": "Waypath 321", "price": 22.00},
{"address": "Streetroad 123", "price": 2330.01}
]
}
]
}
In the simplest case JSONPath can replace nested access:
.. code-block:: robotframework
*** Tasks ***
Nested access
# First order of first client, with direct dictionary access
${value}= Set variable ${json}["clients"][0]["orders"][0]
# JSONPath access
${value}= Get value from JSON ${json} $.clients[0].orders[0]
But the power comes from complicated expressions:
.. code-block:: robotframework
*** Tasks ***
Complicated expressions
# Find delivery addresses for all orders
${prices}= Get values from JSON $..address
# Find orders that cost over 100
${expensives}= Get values from JSON $..orders[?(@.price>100)]
Supported Expressions
---------------------
The supported syntax elements are:
======================= ===========
Element Description
======================= ===========
``$`` Root object/element
``@`` Current object/element inside expressions
``.`` or ``[]`` Child operator
``..`` Recursive descendant operator
````parent```` Parent operator, see `functions`_
``*`` Wilcard, any element
``,`` Select multiple fields
``[n]`` Array index
``[a:b:c]`` Array slice (start, end, step)
``[a,b]`` Union of indices or names
``[?()]`` Apply a filter expression
``()`` Script expression
``[\\field]`` Sort descending by ``field``, cannot be combined with
filters.
``[/field]`` Sort ascending by ``field``, cannot be combined with
filters.
````str()```` Convert value to string, see `functions`_
````sub()```` Regex substitution function, see `functions`_
````len```` Calculate value's length, see `functions`_
````split()```` String split function, see `functions`_
``+`` ``-`` ``*`` ``/`` Arithmetic functions, see `functions`_
======================= ===========
Functions
^^^^^^^^^
This library allows JSON path expressions to include certain functions
which can provide additional benefit to users. These functions are
generally encapsulated in backticks (`````). Some functions require
you to pass arguments similar to a Python function.
For example, let's say a JSON has nodes on the JSON path
``$.books[*].genres`` which are represented as strings of genres with
commas separating each genre. So for one book, this node might have a
value like ``horror,young-adult``. You can return a list of first genre
for each book by using the ``split`` function like so:
.. code-block:: robotframework
*** Task ***
Get genres
${genres}= Get values from JSON $.books[*].genres.```split(,, 0, -1)```
Each functions parameters are defined here:
=================================== =====
Function Usage
=================================== =====
``str()`` No parameters, but parenthesis are required
``sub(/regex/, repl)`` The regex pattern must be provided in *regex*
and the replacement value provided in *repl*
``len`` No parameters and no parenthesis
``split(char, segment, max_split)`` Separator character provided as *char*, which
index from the resulting array to be returns
provided as *segment*, and maximum number of
splits to perform provided as *max_split*,
``-1`` for all splits.
``parent`` No parameters, no parenthesis
=================================== =====
**Arithmetic Functions**
JSON Path can be written and combined to concatenate string values
or perform arithmetic functions on numerical values. Each JSONPath
expression used must return the same type, and when performing
such functions between returned lists, each list must be the same
length. An example is included in documentation for the keyword
``Get values from JSON``.
Additional Information
^^^^^^^^^^^^^^^^^^^^^^
There are a multitude of different script expressions
in addition to the elements listed above, which can
be seen in the `aforementioned article`__.
For further library usage examples, see the individual keywords.
__ JSONPath_
"""
# TODO: Add more logging about affected rows, at least on debug level
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self):
self.logger = logging.getLogger(__name__)
@keyword("Load JSON from file")
def load_json_from_file(self, filename: str, encoding="utf-8") -> JSONType:
"""Load JSON data from a file, and return it as JSON serializable object.
Depending on the input file the object can be either a dictionary,
a list, or a scalar value.
:param filename: path to input file
:param encoding: file character encoding
:return: JSON serializable object of the JSON file
Example:
.. code:: robotframework
*** Task ***
Load json
&{auth}= Load JSON from file auth.json
Log Current auth token: ${auth.token}
"""
self.logger.info("Loading JSON from file: %s", filename)
with open(filename, "r", encoding=encoding) as json_file:
return json.load(json_file)
@keyword("Save JSON to file")
def save_json_to_file(
self,
doc: JSONType,
filename: str,
indent: Optional[int] = None,
encoding: str = "utf-8",
) -> None:
"""Save a JSON serializable object or a string containing
a JSON value into a file.
:param doc: JSON serializable object or string
:param filename: path to output file
:param indent: if given this value is used for json file indent
:param encoding: file character encoding
Robot Framework Example:
.. code:: robotframework
*** Tasks ***
Save dictionary to file
${john}= Create dictionary name=John mail=john@example.com
Save JSON to file ${john} john.json
Save string to file
${mark}= Set variable {"name": "Mark", "mail": "mark@example.com"}
Save JSON to file ${mark} mark.json
Python Example:
.. code:: python
from RPA.JSON import JSON
# Save dictionary to file.
john = {"name": "John", "mail": "john@example.com"}
JSON().save_json_to_file(john, "john.json")
"""
self.logger.info("Saving JSON to file: %s", filename)
extra_args = {}
if indent:
extra_args["indent"] = indent
doc = self.convert_string_to_json(doc) if isinstance(doc, str) else doc
with open(filename, "w", encoding=encoding) as outfile:
json.dump(doc, outfile, **extra_args)
@keyword("Convert JSON to String")
def convert_json_to_string(self, doc: JSONType) -> str:
"""Convert a JSON serializable object to a string and return it.
:param doc: JSON serializable object
:return: string of the JSON serializable object
Robot Framework Example:
.. code:: robotframework
*** Task ***
Convert to string
${obj}= Create dictionary Key=Value
${json}= Convert JSON to string ${obj}
Should be equal ${json} {"Key": "Value"}
Python Example:
.. code:: python
from RPA.JSON import JSON
from robot.libraries.BuiltIn import BuiltIn
obj = {"Key": "Value"}
json = JSON().convert_json_to_string(obj)
BuiltIn().should_be_equal(json, '{"Key": "Value"}')
"""
return json.dumps(doc)
@keyword("Convert String to JSON")
def convert_string_to_json(self, doc: str) -> JSONType:
"""Convert a string to a JSON serializable object and return it.
:param doc: JSON string
:return: JSON serializable object of the string
Robot Framework Example:
.. code:: robotframework
*** Task ***
Convert to json
${json}= Set variable {"Key": "Value"}
&{obj}= Convert string to JSON ${json}
Should be equal ${obj.Key} Value
Python Example:
.. code:: python
from RPA.JSON import JSON
from robot.libraries.BuiltIn import BuiltIn
json = '{"Key": "Value"}'
obj = JSON().convert_string_to_json(json)
BuiltIn().should_be_equal(obj["Key"], "Value")
"""
return json.loads(doc)
@keyword("Add to JSON")
def add_to_json(self, doc: JSONType, expr: str, value: JSONType) -> JSONType:
"""Add items into a JSON serializable object and return the result.
If the target is a list, the values are appended to the end.
If the target is a dict, the keys are either added or updated.
:param doc: JSON serializable object
:param expr: JSONPath expression
:param value: values to either append or update
:return: JSON serializable object of the updated JSON
Robot Framework Example:
.. code:: robotframework
*** Task ***
Change the name value for all people
&{before}= Convert string to JSON {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
&{person}= Create dictionary Name=John
&{after}= Add to JSON ${before} $.People ${person}
Python Example:
.. code:: python
from RPA.JSON import JSON
# Change the name value for all people
js = JSON()
before = js.convert_string_to_json('{"People": [{"Name": "Mark"}, {"Name": "Jane"}]}')
person = {"Name": "John"}
after = js.add_to_json(before, "$.People", person)
print(after)
""" # noqa: E501
self.logger.info("Add to JSON with expression: %r", expr)
for match in parse(expr).find(doc):
if isinstance(match.value, dict):
match.value.update(value)
if isinstance(match.value, list):
match.value.append(value)
return doc
@keyword("Get value from JSON")
def get_value_from_json(
self, doc: JSONType, expr: str, default: Optional[Any] = None
) -> str:
"""Get a single value from a JSON serializable object that matches the given expression.
Raises a ValueError if there is more than one match.
Returns the given default argument (or None) if there
were no matches.
:param doc: JSON serializable object or string
:param expr: jsonpath expression
:param default: default value to return in the absence of a match
:return: string containing the match OR `default` if there are no matches
:raises ValueError: if more than one match is discovered
Short Robot Framework Example:
.. code:: robotframework
*** Task ***
Get the name value for the first person
&{people}= Convert string to JSON {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
${first}= Get value from JSON ${people} $.People[0].Name
Short Python Example:
.. code:: python
from RPA.JSON import JSON
# Get the name value for the second person.
people = {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
second = JSON().get_value_from_json(people, "$.People[1].Name")
print(second)
Extended Robot Framework Example:
.. code:: robotframework
*** Settings ***
Library RPA.JSON
Suite Setup Ingest JSON
*** Variables ***
${JSON_STRING} {
... "clients": [
... {
... "name": "Johnny Example",
... "email": "john@example.com",
... "orders": [
... {"address": "Streetroad 123", "state": "TX", "price": 103.20, "id":"guid-001"},
... {"address": "Streetroad 123", "state": "TX", "price": 98.99, "id":"guid-002"}
... ]
... },
... {
... "name": "Jane Example",
... "email": "jane@example.com",
... "orders": [
... {"address": "Waypath 321", "state": "WA", "price": 22.00, "id":"guid-003"},
... {"address": "Streetroad 123", "state": "TX", "price": 2330.01, "id":"guid-004"},
... {"address": "Waypath 321", "state": "WA", "price": 152.12, "id":"guid-005"}
... ]
... }
... ]
... }
${ID} guid-003
*** Tasks ***
Get email for specific order id
${email}= Get value from json ${JSON_DOC} $.clients[?(@..id=="${ID}")].email
Log \\nOUTPUT IS\\n ${email} console=${True}
Should be equal as strings ${email} jane@example.com
*** Keywords ***
Ingest JSON
${doc}= Convert string to json ${JSON_STRING}
Set suite variable ${JSON_DOC} ${doc}
""" # noqa: E501
self.logger.info("Get value from JSON with expression: %r", expr)
result = [match.value for match in parse(expr).find(doc)]
if len(result) > 1:
raise ValueError(
"Found {count} matches: {values}".format(
count=len(result), values=", ".join(str(r) for r in result)
)
)
return result[0] if result else default
@keyword("Get values from JSON")
def get_values_from_json(self, doc: JSONType, expr: str) -> list:
"""Get all values from a JSON serializable object that match the given expression.
:param doc: JSON serializable object or string
:param expr: JSONPath expression
:return: list of values that match
Short Robot Framework Example:
.. code:: robotframework
*** Task ***
Get all the names for all people
&{people}= Convert string to JSON {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
@{names}= Get values from JSON ${people} $.People[*].Name
Short Python Example:
.. code:: python
from RPA.JSON import JSON
# Get all the names for all people
people = {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
names = JSON().get_values_from_json(people, "$.People[*].Name")
print(second)
Extended Robot Framework Example:
.. code:: robotframework
*** Settings ***
Library RPA.JSON
Suite Setup Ingest JSON
*** Variables ***
${JSON_STRING} {
... "clients": [
... {
... "name": "Johnny Example",
... "email": "john@example.com",
... "orders": [
... {"address": "Streetroad 123", "state": "TX", "price": 103.20, "id":"guid-001"},
... {"address": "Streetroad 123", "state": "TX", "price": 98.99, "id":"guid-002"}
... ]
... },
... {
... "name": "Jane Example",
... "email": "jane@example.com",
... "orders": [
... {"address": "Waypath 321", "state": "WA", "price": 22.00, "id":"guid-003"},
... {"address": "Streetroad 123", "state": "TX", "price": 2330.01, "id":"guid-004"},
... {"address": "Waypath 321", "state": "WA", "price": 152.12, "id":"guid-005"}
... ]
... }
... ]
... }
${ID} guid-003
*** Tasks ***
Get All Prices and Order Ids
# Arithmetic operations only work when lists are of equal lengths and types.
${prices}= Get values from json
... ${JSON_DOC}
... $.clients[*].orders[*].id + " has price " + $.clients[*].orders[*].price.```str()```
Log \\nOUTPUT IS\\n ${prices} console=${True}
Should be equal as strings ${prices}
... ['guid-001 has price 103.2', 'guid-002 has price 98.99', 'guid-003 has price 22.0', 'guid-004 has price 2330.01', 'guid-005 has price 152.12']
Find Only Valid Emails With Regex
# The regex used in this example is simplistic and
# will not work with all email addresses
${emails}= Get values from json
... ${JSON_DOC}
... $.clients[?(@.email =~ "[a-zA-Z]+@[a-zA-Z]+\\.[a-zA-Z]+")].email
Log \\nOUTPUT IS\\n ${emails} console=${True}
Should be equal as strings ${emails} ['john@example.com', 'jane@example.com']
Find Orders From Texas Over 100
# The regex used in this example is simplistic and
# will not work with all email addresses
${orders}= Get values from json
... ${JSON_DOC}
... $.clients[*].orders[?(@.price > 100 & @.state == "TX")]
Log \\nOUTPUT IS\\n ${orders} console=${True}
Should be equal as strings ${orders}
... [{'address': 'Streetroad 123', 'state': 'TX', 'price': 103.2, 'id': 'guid-001'}, {'address': 'Streetroad 123', 'state': 'TX', 'price': 2330.01, 'id': 'guid-004'}]
*** Keywords ***
Ingest JSON
${doc}= Convert string to json ${JSON_STRING}
Set suite variable ${JSON_DOC} ${doc}
""" # noqa: E501
self.logger.info("Get values from JSON with expression: %r", expr)
return [match.value for match in parse(expr).find(doc)]
@keyword("Update value to JSON")
def update_value_to_json(
self, doc: JSONType, expr: str, value: JSONType
) -> JSONType:
"""Update existing values in a JSON serializable object and return the result.
Will change all values that match the expression.
:param doc: JSON or string
:param expr: JSONPath expression
:param value: New value for the matching item(s)
:return: JSON serializable object with updated results
Short Robot Framework Example:
.. code:: robotframework
*** Tasks ***
Change the name key for all people
&{before}= Convert string to JSON {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
&{after}= Update value to JSON ${before} $.People[*].Name JohnMalkovich
.. code:: python
from RPA.JSON import JSON
# Change the name key for all people
before = {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
after = JSON().update_value_to_json(before, "$.People[*].Name","JohnMalkovich")
print(after)
Extended Robot Framework Example:
.. code:: robotframework
*** Settings ***
Library RPA.JSON
Library Collections
Suite Setup Ingest JSON
*** Variables ***
${JSON_STRING} {
... "clients": [
... {
... "name": "Johnny Example",
... "email": "john@example.com",
... "id": "user-001",
... "orders": [
... {"address": "Streetroad 123", "state": "TX", "price": 103.20, "id":"guid-001"},
... {"address": "Streetroad 123", "state": "TX", "price": 98.99, "id":"guid-002"}
... ]
... },
... {
... "name": "Jane Example",
... "email": "jane@example.com",
... "id": "user-002",
... "orders": [
... {"address": "Waypath 321", "state": "WA", "price": 22.00, "id":"guid-003"},
... {"address": "Streetroad 123", "state": "TX", "price": 2330.01, "id":"guid-004"},
... {"address": "Waypath 321", "state": "WA", "price": 152.12, "id":"guid-005"}
... ]
... }
... ]
... }
${ID} guid-003
*** Tasks ***
Update user email
${updated_doc}= Update value to json
... ${JSON_DOC}
... $.clients[?(@.id=="user-001")].email
... johnny@example.com
Log \\nNEW JSON IS\\n ${updated_doc} console=${True}
${new_email}= Get value from json ${updated_doc} $.clients[?(@.id=="user-001")].email
Should be equal as strings ${new_email} johnny@example.com
Add additional charge to all prices in WA
# This example also shows how the update keyword changes the original JSON doc in memory.
${id_price}= Get values from json
... ${JSON_DOC}
... $.clients[*].orders[?(@.state=="WA")].id,price
FOR ${order_id} ${price} IN @{id_price}
Update value to json ${JSON_DOC} $.clients[*].orders[?(@.id=="${order_id}")].price ${{${price} * 1.06}}
END
Log \\nNEW JSON IS\\n ${JSON_DOC} console=${True}
${one_price}= Get value from json ${JSON_DOC} $..orders[?(@.id==${ID})].price
Should be equal as numbers ${one_price} 23.32
*** Keywords ***
Ingest JSON
${doc}= Convert string to json ${JSON_STRING}
Set suite variable ${JSON_DOC} ${doc}
""" # noqa: E501
self.logger.info("Update JSON with expression: %r", expr)
for match in parse(expr).find(doc):
path = match.path
if isinstance(path, Index):
match.context.value[match.path.index] = value
elif isinstance(path, Fields):
match.context.value[match.path.fields[0]] = value
return doc
@keyword("Delete from JSON")
def delete_from_json(self, doc: JSONType, expr: str) -> JSONType:
"""Delete values from a JSON serializable object and return the result.
Will delete all values that match the expression.
:param doc: JSON serializable object or string
:param expr: JSONPath expression
:return: JSON serializable object with values removed
Example:
.. code:: robotframework
*** Task ***
Delete all people
&{before}= Convert string to JSON {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
&{after}= Delete from JSON ${before} $.People[*]
.. code:: python
from RPA.JSON import JSON
# Delete all people
before = {"People": [{"Name": "Mark"}, {"Name": "Jane"}]}
after = JSON().delete_from_json(before, "$.People[*]")
print(after)
""" # noqa: E501
self.logger.info("Delete from JSON with expression: %r", expr)
return parse(expr).filter(lambda _: True, doc) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/JSON.py | 0.864368 | 0.777785 | JSON.py | pypi |
import logging
import math
import traceback
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple, Union
import requests
# pylint: disable=no-name-in-module
from hubspot import HubSpot as HubSpotApi
from hubspot.crm.associations.models import (
AssociatedId,
BatchInputPublicObjectId,
PublicObjectId,
)
from hubspot.crm.objects.models import (
BatchInputSimplePublicObjectBatchInput as UpdateBatchInput,
)
from hubspot.crm.objects.models import (
BatchInputSimplePublicObjectInput as CreateBatchInput,
)
from hubspot.crm.objects.models import (
BatchReadInputSimplePublicObjectId,
Filter,
FilterGroup,
)
from hubspot.crm.objects.models import PublicObjectSearchRequest as ObjectSearchRequest
from hubspot.crm.objects.models import SimplePublicObject
from hubspot.crm.objects.models import SimplePublicObjectBatchInput as UpdateObjectInput
from hubspot.crm.objects.models import SimplePublicObjectId
from hubspot.crm.objects.models import SimplePublicObjectInput as CreateObjectInput
from hubspot.crm.objects.models import SimplePublicObjectWithAssociations
from hubspot.crm.owners.models import PublicOwner
from hubspot.crm.pipelines.exceptions import ApiException as PipelineApiException
from hubspot.crm.pipelines.models import Pipeline
from hubspot.crm.schemas.exceptions import ApiException as SchemaApiException
from hubspot.crm.schemas.models import ObjectSchema
from robot.api.deco import keyword, library
from tenacity import (
before_sleep_log,
retry,
retry_if_exception,
stop_after_attempt,
wait_exponential,
)
from RPA.core.logger import deprecation
class HubSpotAuthenticationError(Exception):
"Error when authenticated HubSpot instance does not exist."
class HubSpotObjectTypeError(Exception):
"Error when the object type provided does not exist."
class HubSpotSearchParseError(Exception):
"Error when the natural word search engine cannot parse the provided words."
class HubSpotNoPipelineError(Exception):
"Error when there is no pipeline associated with an object."
class HubSpotRateLimitError(Exception):
"Error when the API's rate limits are exceeded."
class HubSpotBatchResponseError(Exception):
"Error when the entire batch response is nothing but errors."
class HubSpotBatchInputInvalidError(Exception):
"""Error when the provided batch input is invalid and cannot be sent
to the Hubspot API.
"""
class ExtendedFilter(Filter):
"""Extends the ``Filter`` class provided by ``hubspot-api-client``
to include the following additional attributes supported by
the REST API:
* ``values``
* ``high_value``
It also overloads the implementation of ``value`` to support the
existence of the other attributes.
"""
openapi_types = {
"value": "str",
"values": "list",
"high_value": "str",
"property_name": "str",
"operator": "str",
}
attribute_map = {
"value": "value",
"values": "values",
"high_value": "highValue",
"property_name": "propertyName",
"operator": "operator",
}
def __init__(
self,
value=None,
values=None,
high_value=None,
property_name=None,
operator=None,
local_vars_configuration=None,
):
if value and values:
raise ValueError(
"You cannot construct a Filter with both ``value`` and ``values``."
)
super().__init__(value, property_name, operator, local_vars_configuration)
self._values = None
self._high_value = None
if values is not None:
self.values = values
if high_value is not None:
self.high_value = high_value
@property
def values(self):
return self._values
@values.setter
def values(self, values):
self._values = values
if values is not None:
self.value = None
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
if value is not None:
self.values = None
@property
def high_value(self):
return self._high_value
@high_value.setter
def high_value(self, high_value):
self._high_value = high_value
if high_value is not None:
self.values = None
if self._value is None:
self._value = 0
def __eq__(self, other):
if not isinstance(other, ExtendedFilter):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
if not isinstance(other, ExtendedFilter):
return True
return self.to_dict() != other.to_dict()
class SearchLexer:
"""A class for analyzing a natural search list for ``RPA.Hubspot``"""
def __init__(
self, search_terms: List[str] = None, logger: logging.Logger = None
) -> None:
self._search_terms = search_terms
if not logger:
self.logger = logging.getLogger(__name__)
else:
self.logger = logger
def _split(self, words: List, oper: str):
self.logger.debug(f"Words to split on operator '{oper}': {words}")
size = len(words)
first_index_list = [i + 1 for i, v in enumerate(words) if v == oper]
second_index_list = [i for i, v in enumerate(words) if v == oper]
self.logger.debug(f"Index list is: {first_index_list}")
split_result = [
words[i:j]
for i, j in zip(
[0] + first_index_list,
second_index_list + ([size] if second_index_list[-1] != size else []),
)
]
self.logger.debug(f"Split result: {split_result}")
return split_result
def _process_and(self, words: List):
if words.count("AND") > 3:
raise HubSpotSearchParseError(
"No more than 3 logical 'AND' operators "
+ "can be used between each 'OR' operator."
)
search_filters = []
if "AND" in words:
word_filters = self._split(words, "AND")
self.logger.debug(f"Found these groups of words as Filters: {word_filters}")
for word_filter in word_filters:
search_filters.append(self._process_filter(word_filter))
else:
self.logger.debug(f"Found this group of words as Filter: {words}")
search_filters.append(self._process_filter(words))
return search_filters
def _process_filter(self, words: List):
self.logger.debug(f"Attempting to turn {words} into Filter object.")
if len(words) not in (2, 3):
raise HubSpotSearchParseError(
"The provided words cannot be parsed as a search object. "
+ f"The words {words} could not be parsed."
)
if words[1] in ("HAS_PROPERTY", "NOT_HAS_PROPERTY"):
search_filter = ExtendedFilter(property_name=words[0], operator=words[1])
elif words[1] in ("IN", "NOT_IN"):
search_filter = ExtendedFilter(
property_name=words[0], operator=words[1], values=words[2]
)
elif words[1] == "BETWEEN":
search_filter = ExtendedFilter(
property_name=words[0],
operator=words[1],
value=words[2][0],
high_value=words[2][1],
)
else:
search_filter = ExtendedFilter(
property_name=words[0], operator=words[1], value=words[2]
)
self.logger.debug(f"Resulting Filter object: {search_filter}")
return search_filter
def create_search_object(self, words: List[str] = None):
if not words:
if self._search_terms:
words = self._search_terms
else:
raise ValueError(
"Words must not be null if class was not "
+ "initialized with search_terms."
)
if words.count("OR") > 3:
raise HubSpotSearchParseError(
"No more than 3 logical 'OR' operators can be used."
)
filter_groups = []
if "OR" in words:
word_groups = self._split(words, "OR")
self.logger.debug(
f"Found these groups of words as FilterGroups: {word_groups}"
)
for word_group in word_groups:
filter_groups.append(FilterGroup(self._process_and(word_group)))
else:
self.logger.debug(f"Found this group of words as FilterGroup: {words}")
filter_groups.append(FilterGroup(self._process_and(words)))
return ObjectSearchRequest(filter_groups)
class BatchMode(Enum):
"""Enumeration that returns the appropriate class to create a single
object inside of a batch input list.
"""
UPDATE = "UPDATE"
CREATE = "CREATE"
INVALID = "INVALID"
class BatchInputFactory:
"""A factory class which can be used to build up a set of inputs
for a Hubspot Batch Input process and then used to generate the
final object to be passed to the Hubspot API client.
"""
def __init__(
self,
mode: BatchMode = BatchMode.INVALID,
object_type: Optional[str] = None,
inputs: Optional[List] = None,
) -> None:
self._mode = mode
self.object_type = object_type
self._inputs = inputs or []
def __len__(self) -> int:
return len(self.inputs)
@property
def mode(self) -> BatchMode:
"""The batch mode, either ``UPDATE`` or ``CREATE``."""
return self._mode
@mode.setter
def mode(self, mode: BatchMode):
if not isinstance(mode, BatchMode):
self._mode = BatchMode(mode)
@property
def inputs(self) -> Union[List[CreateObjectInput], List[UpdateObjectInput]]:
"""A list of inputs to be sent into the Batch API, returned type
depends on ``mode``. Can be set directly, but the ``add_input`` and
``extend_inputs`` methods are more useful.
"""
return self._inputs
@inputs.setter
def inputs(self, inputs: Union[List[CreateObjectInput], List[UpdateObjectInput]]):
if isinstance(inputs[0], CreateObjectInput):
self.mode = BatchMode.CREATE
elif isinstance(inputs[0], UpdateObjectInput):
self.mode = BatchMode.UPDATE
else:
raise TypeError(
"Expected a list of type "
"SimplePublicObjectInput or SimplePublicObjectBatchInput,"
f"but received type {type(inputs[0])}"
)
self._inputs = inputs
@inputs.deleter
def inputs(self):
self._inputs = []
def _prevent_mode_change_with_inputs(self, other_mode: BatchMode):
if (
self.mode is not other_mode
and self.mode is not BatchMode.INVALID
and len(self.inputs) > 0
):
raise ValueError(
f"This batch is in {str(self.mode)} mode and already has items, "
f"it is not possible to implicity switch modes to {str(other_mode)}"
)
def add_input(
self,
properties: Dict[str, str],
object_id: str = None,
):
"""Add the provided dictionary of Hubspot properties as an input
to this batch's ``inputs`` property. If ``object_id`` is provided, the
input will be considered an ``UPDATE`` mode input.
"""
if object_id:
self._prevent_mode_change_with_inputs(BatchMode.UPDATE)
new_input = UpdateObjectInput(properties, object_id)
if self.mode is BatchMode.INVALID:
self.mode = BatchMode.UPDATE
else:
self._prevent_mode_change_with_inputs(BatchMode.CREATE)
new_input = CreateObjectInput(properties)
if self.mode is BatchMode.INVALID:
self.mode = BatchMode.CREATE
self._inputs.append(new_input)
def extend_inputs(
self, properties: List[Dict[str, str]], ids: List[str] = None
) -> None:
"""Extends this batch's ``inputs`` based on the provided list of
``properties`` and ``ids``. If ``ids`` is provided, it will be
zipped with the provided ``properties``. ``UPDATE`` mode is assumed
in such a case.
"""
if ids:
self._prevent_mode_change_with_inputs(BatchMode.UPDATE)
new_inputs = [UpdateObjectInput(p, i) for p, i in zip(properties, ids)]
if self.mode is BatchMode.INVALID:
self.mode = BatchMode.UPDATE
else:
self._prevent_mode_change_with_inputs(BatchMode.CREATE)
new_inputs = [CreateObjectInput(p) for p in properties]
if self.mode is BatchMode.INVALID:
self.mode = BatchMode.CREATE
self._inputs.extend(new_inputs)
def create_hubspot_batch_object(
self, start: int = 0, end: int = None
) -> Union[CreateBatchInput, UpdateBatchInput]:
"""Generates either a BatchInputSimplePublicObjectInput or
BatchInputSimplePublicObjectBatchInput depending on whether this
factory is in ``CREATE`` or ``UPDATE`` mode. If ``start`` or ``end``
is provided, it will return a batch object including only a slice
of the current inputs (useful when total number of inputs is more
than 100, which requires batches to be batch due to API restrictions).
"""
if self.mode is BatchMode.CREATE:
return CreateBatchInput(self.inputs[start:end])
elif self.mode is BatchMode.UPDATE:
return UpdateBatchInput(self.inputs[start:end])
else:
raise HubSpotBatchInputInvalidError("Current batch has an INVALID mode.")
@library(scope="Global", doc_format="REST")
class Hubspot:
r"""*Hubspot* is a library for accessing HubSpot using REST API. It
extends `hubspot-api-client <https://pypi.org/project/hubspot-api-client/>`_.
Current features of this library focus on retrieving CRM object data
from HubSpot via API. For additional information, see
`Understanding the CRM <https://developers.hubspot.com/docs/api/crm/understanding-the-crm>`_.
Using Date Times When Searching
===============================
When using date times with the Hubspot API, you must provide
them as Unix-style epoch timestamps (with milliseconds), which can be obtained
using the ``DateTime`` library's ``Convert Date`` with the
argument ``result_format=epoch``. The resulting timestamp string
will be a float, but the API only accepts integers, so you must
multiply the resulting timestamp by 1,000 and then round it to
the nearest integar to include in API calls (i.e., the resulting
integer sent to the API must have 13 digits as of March 18, 2022).
**Robot framework example usage:**
.. code-block:: robotframework
*** Settings ***
Library DateTime
Library RPA.Hubspot
Task Setup Authorize Hubspot
*** Tasks ***
Search with date
${yesterday}= Get current date increment=-24h result_format=epoch
${yesterday_hs_ts}= Evaluate round(${yesterday} * 1000)
${deals}= Search for objects DEALS
... hs_lastmodifieddate GTE ${yesterday_hs_ts}
**Python example usage**
.. code-block:: python
from robot.libraries.DateTime import get_current_date, subtract_time_from_date
from RPA.Hubspot import Hubspot
from RPA.Robocorp.Vault import Vault
secrets = Vault().get_secret("hubspot")
hs = Hubspot(hubspot_apikey=secrets["api_key"])
yesterday = round(
subtract_time_from_date(get_current_date(), "24h", result_format="epoch") * 1000
)
deals = hs.search_for_objects("DEALS", "hs_lastmodifieddate", "GTE", yesterday)
print(deals)
.. _batch-inputs:
Batch Inputs
============
When retrieving information, the library automatically batches requests
that are provided as lists, see ``Get object`` keyword for an example,
but when wishing to create or update many objects, the library provides
a batching system.
In order to start a batch, you must first call the ``Create new batch``
keyword. This initializes a new batch to accept inputs. If a batch
already exists when you call this keyword, it will be lost and a new
blank one will be started.
Once the batch has been initialized, you can add inputs one at a time with
``Add input to batch`` or many at a time with ``Extend batch with inputs``.
In order to finally send the batch to HubSpot, you must call
``Execute batch``. The final keyword will return the created or updated
objects from HubSpot. New object IDs can be obtained from the ``id``
property, see the `SimplePublicObject`_ reference.
**Robot framework example:**
.. code-block:: robotframework
*** Settings ***
Library RPA.Hubspot
Library RPA.Robocorp.Vault
Task Setup Authorize Hubspot
*** Tasks ***
Create objects via batch
Create new batch
Add input to batch name=Nokia country=Finland
Add input to batch name=Google country=USA
${new_companies}= Execute batch
Log The first new company added has the new id ${{$new_companies[0].id}}
*** Keywords ***
Authorize Hubspot
${secrets}= Get secret hubspot
Auth with api key ${secrets}[API_KEY]
**Python example:**
**NOTE:** When executing a batch input in Python, you can directly import the
``BatchInputFactory`` class to use to create your batch input before
executing the batch.
.. code-block:: python
from RPA.Hubspot import Hubspot, BatchInputFactory, BatchMode
from RPA.Robocorp.Vault import RobocorpVault
vault = RobocorpVault()
secrets = vault.get_secret("hubspot")
hs = Hubspot(secrets["API_KEY"])
batch = BatchInputFactory(BatchMode.UPDATE, "company")
batch.extend_inputs(
[
{"name": "Nokia's New Name", "city": "Espoo"},
{"name": "Alphabet", "city": "Mountain View"},
],
["1001", "1002"],
)
hs.batch_input = batch
updated_companies = hs.execute_batch()
print(
"Companies have been updated:\\n" +
"\\n".join([str(c) for c in updated_companies])
)
Information Caching
===================
This library loads custom object schemas and pipelines into memory
the first time when keywords using them are called. These cached versions
are recalled unless the ``use_cache`` is set to ``False``, where available.
Custom Object Types
===================
All keywords that request a parameter of ``object_type`` can accept
custom object type names as long as they are properly configured in
HubSpot. The system will lookup the custom object ID using the
provided name against the configured name or one of the configured
labels (e.g., "singular" and "plural" types of the name).
HubSpot Object Reference
========================
This section describes the types of objects returned by this Library
and their associated attributes. These attributes can be accessed via
dot-notation as described in the `Attribute Access`_ section below.
Attribute Access
----------------
Keywords return native Python Hubspot objects, rather than common Robot
Framework types. These types have sets of defined attributes allowing
for dot-notation access of object properties. Properties (e.g.,
those configured in Hubspot settings for each object) will be
accessible in a Python dictionary attached to the ``properties`` attribute
of the returned object. See the `Attribute Definitions`_ section for
details of that associated attributes for all types returned by this
library.
Example usage retrieving the ``city`` property of a *Company* object:
**Robot framework example:**
.. code-block:: robotframework
*** Settings ***
Library RPA.Hubspot
Library RPA.Robocorp.Vault
Task Setup Authorize Hubspot
*** Variables ***
${ACCOUNT_NOKIA} 6818764598
*** Tasks ***
Obtain city information from Hubspot
${account}= Get object COMPANY ${ACCOUNT_NOKIA}
Log The city for account number ${ACCOUNT_NOKIA} is ${account.properties}[city]
*** Keywords ***
Authorize Hubspot
${secrets}= Get secret hubspot
Auth with api key ${secrets}[API_KEY]
**Python example:**
.. code-block:: python
from RPA.Hubspot import Hubspot
from RPA.Robocorp.Vault import RobocorpVault
vault = RobocorpVault()
secrets = vault.get_secret("hubspot")
hs = Hubspot(secrets["API_KEY"])
nokia_account_id = "6818764598"
account = hs.get_object("COMPANY", nokia_account_id)
print(f"The city for account number {nokia_account_id} is {account.properties['city']}")
Attribute Definitions
---------------------
This library can return various types of objects, whose attributes
are only accessible via dot-notation. The below reference describes
the attributes available on these objects.
SimplePublicObject
^^^^^^^^^^^^^^^^^^
An object in HubSpot. The object itself does not describe what type
it represents.
*id* : ``str``
The HubSpot ID of the object.
*properties* : ``Dict[str, str]``
A dictionary representing all returned properties associated
to this object. Properties must be accessed as via standard
dictionary subscription, e.g., ``properties["name"]``.
*created_at* : ``datetime``
The timestamp when this object was created in HubSpot.
*updated_at* : ``datetime``
The last modified timestamp for this object.
*archived* : ``bool``
Whether this object is archived.
*archived_at* : ``datetime``
The timestamp when this object was archived.
SimplePublicObjectWithAssociations
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
An object in HubSpot including associations to other objects. The
object itself does not describe what type it represents.
*id* : ``str``
The HubSpot ID of the object.
*properties* : ``Dict[str, str]``
A dictionary representing all returned properties associated
to this object. Properties must be accessed as via standard
dictionary subscription, e.g., ``properties["name"]``.
*created_at* : ``datetime``
The timestamp when this object was created in HubSpot.
*updated_at* : ``datetime``
The last modified timestamp for this object.
*archived* : ``bool``
Whether this object is archived.
*archived_at* : ``datetime``
The timestamp when this object was archived.
*associations* : ``Dict[str, CollectionResponseAssociatedId]``
A dictionary whose key will be the requested association type, e.g.,
``companies`` and associated value will be a container object
with all the associations. See `CollectionResponseAssociatedId`_.
AssociatedId
^^^^^^^^^^^^
The ID of an associated object, as well as the type of association.
*id* : ``str``
The ID of the associated HubSpot object.
*type* : ``str``
The type of association, e.g., ``deals_to_companies``.
CollectionResponseAssociatedId
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A container object for a collection of `AssociatedId`_ objects returned
by the API.
*results* : ``List[AssociatedId]``
The list of `AssociatedId`_ objects returned by the API.
*paging* : ``Paging``
Used by this library to assist with retreiving multi-page
API responses.
Pipeline
^^^^^^^^
A pipeline represents the steps objects travel through within HubSpot.
*id* : ``str``
The HubSpot ID for the pipeline. All accounts start with one
pipeline with the id ``default``.
*label* : ``str``
The human-readabel label for the pipeline.
*stages* : ``List[PipelineStage]``
A list of `PipelineStage`_ objects in the order the object would
follow through the pipeline.
*created_at* : ``datetime``
The timestamp when this pipeline was created in HubSpot.
*updated_at* : ``datetime``
The last modified timestamp for this pipeline.
*archived* : ``bool``
Whether this pipeline is archived.
*display_order* : ``int``
The place in the list of pipelines where this pipeline is shown
in the HubSpot UI.
PipelineStage
^^^^^^^^^^^^^
A pipeline stage is one of the various stages defined in a `Pipeline`_.
*id* : ``str``
The HubSpot ID of the stage.
*label* : ``str``
The human-readabel label for the stage.
*metadata* : ``Dict[str, str]``
A dictionary of additional data associated with ths stage, such
as ``probability``.
*created_at* : ``datetime``
The timestamp when this stage was created in HubSpot.
*updated_at* : ``datetime``
The last modified timestamp for this stage.
*archived* : ``bool``
Whether this stage is archived.
*archived_at* : ``datetime``
The timestamp when this stage was archived.
PublicOwner
^^^^^^^^^^^
An owner in HubSpot. Owners of companies and deals are responsible
for driving a sale to close or similar.
*id* : ``str``
The HubSpot ID of the owner.
*email* : ``str``
The owner's email address in HubSpot.
*first_name* : ``str``
The owner's first name.
*last_name* : ``str``
The owner's last name.
*user_id* : ``int``
The associated user ID if the owner is a HubSpot user.
*created_at* : ``datetime``
The timestamp when this owner was created in HubSpot.
*updated_at* : ``datetime``
The last modified timestamp for this owner.
*archived* : ``bool``
Whether this owner is archived.
*teams* : ``List[PublicTeam]``
A list of teams the owner is in. See `PublicTeam`_.
PublicTeam
^^^^^^^^^^
A team of owners in HubSpot
*id* : ``str``
The HubSpot ID of the Team.
*name* : ``str``
The Team's name.
*membership* : ``str``
One of ``PRIMARY``, ``SECONDARY``, or ``CHILD``.
""" # noqa: E501
BUILTIN_SINGULAR_MAP = {
"contacts": "contact",
"companies": "company",
"deals": "deal",
"feedback submissions": "feadback submission",
"line items": "line item",
"products": "product",
"tickets": "ticket",
"quotes": "quote",
"contact": "contact",
"company": "company",
"deal": "deal",
"feedback submission": "feadback submission",
"line item": "line item",
"product": "product",
"ticket": "ticket",
"quote": "quote",
}
BUILTIN_PLURAL_MAP = {
"contact": "contacts",
"company": "companies",
"deal": "deals",
"feedback submission": "feadback submissions",
"line item": "line items",
"product": "products",
"ticket": "tickets",
"quote": "quotes",
"contacts": "contacts",
"companies": "companies",
"deals": "deals",
"feedback submissions": "feadback submissions",
"line items": "line items",
"products": "products",
"tickets": "tickets",
"quotes": "quotes",
}
def __init__(
self, hubspot_apikey: str = None, hubspot_access_token: str = None
) -> None:
"""The library can be imported with the API key or Access
Token supplied, but this may preclude the ability to use
secrets from the Control Room Vault or similar credential
manager.
"""
self.logger = logging.getLogger(__name__)
if hubspot_apikey:
self.hs = HubSpotApi(api_key=hubspot_apikey)
elif hubspot_access_token:
self.hs = HubSpotApi(access_token=hubspot_access_token)
else:
self.hs = None
self._schemas = []
self._singular_map = {}
self._plural_map = {}
self._pipelines = {}
self._batch_input = None
def _require_authentication(self) -> None:
if self.hs is None:
raise HubSpotAuthenticationError("Authentication was not completed.")
def _require_token_authentication(self) -> None:
if self.hs.access_token is None:
raise HubSpotAuthenticationError(
"This endpoint requires a private app authorization token to use."
)
# pylint: disable=no-self-argument
def _is_rate_limit_error(error: Exception) -> bool:
return getattr(error, "status", None) == 429
# pylint: disable=no-self-argument,no-method-argument
def _before_sleep_log():
logger = logging.root
return before_sleep_log(logger, logging.DEBUG)
@property
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def schemas(self) -> List[ObjectSchema]:
self._require_authentication()
if len(self._schemas) == 0:
self.schemas = self.hs.crm.schemas.core_api.get_all()
return self._schemas
@schemas.setter
def schemas(self, results):
if hasattr(results, "results"):
results = results.results
if isinstance(results, list) and isinstance(results[0], ObjectSchema):
self._schemas = results
else:
raise TypeError(
"Invalid values for ``results``, must be list of ``ObjectSchema``."
)
def _get_custom_object_schema(self, name: str) -> Union[Dict, None]:
self._require_authentication()
for s in self.schemas:
if (
s.name == name.lower()
or s.labels.singular.lower() == name.lower()
or s.labels.plural.lower() == name.lower()
):
return s
else:
return None
def _get_custom_object_id(self, name: str) -> str:
self._require_authentication()
schema = self._get_custom_object_schema(self._validate_object_type(name))
return schema.object_type_id if schema else name
def _singularize_object(self, name: str) -> str:
if len(self._singular_map) == 0:
self._singular_map = self.BUILTIN_SINGULAR_MAP
labels = [s.labels for s in self.schemas]
self._singular_map.update(
{lbl.plural.lower(): lbl.singular.lower() for lbl in labels}
)
self._singular_map.update(
{lbl.singular.lower(): lbl.singular.lower() for lbl in labels}
)
self._singular_map.update(
{s.object_type_id: s.object_type_id for s in self.schemas}
)
return self._singular_map[self._validate_object_type(name)]
def _pluralize_object(self, name: str) -> str:
if len(self._plural_map) == 0:
self._plural_map = self.BUILTIN_PLURAL_MAP
labels = [s.labels for s in self.schemas]
self._plural_map.update(
{lbl.singular.lower(): lbl.plural.lower() for lbl in labels}
)
self._plural_map.update(
{lbl.plural.lower(): lbl.plural.lower() for lbl in labels}
)
self._plural_map.update(
{s.object_type_id: s.object_type_id for s in self.schemas}
)
return self._plural_map[self._validate_object_type(name)]
def _validate_object_type(self, name: str) -> str:
"""Validates the provided ``name`` against the built in list of
object types and the list of custom object type schemas. Returns
the validated custom object ID or name in lower case.
Raises ``HubSpotObjectTypeError`` if ``name`` cannot be validated.
"""
valid_names = list(self.BUILTIN_SINGULAR_MAP.keys())
valid_names.extend([s.object_type_id for s in self.schemas])
valid_names.extend([s.name for s in self.schemas])
valid_names.extend([s.labels.plural.lower() for s in self.schemas])
if name.lower() in valid_names:
return name.lower()
else:
raise HubSpotObjectTypeError(
f"Object type {name} does not exist. "
+ f"Current accepted names are:\n{valid_names}."
)
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def _get_next_search_page(
self,
object_type: str,
search_object: ObjectSearchRequest,
after: int = 0,
):
self.logger.debug(f"Current cursor is: {after}")
search_object.after = after
page = self.hs.crm.objects.search_api.do_search(
object_type, public_object_search_request=search_object
)
self.logger.debug(
f"{len(page.results)} received out of {page.total}. "
+ f"Next cursor is {page.next.after}"
if hasattr(page, "next")
else ""
)
return page
def _search_objects(
self,
object_type: str,
search_object: ObjectSearchRequest,
max_results: int = 1000,
) -> List[SimplePublicObject]:
self._require_authentication()
if max_results < 100:
search_object.limit = max_results
else:
search_object.limit = 100
self.logger.debug(f"Search to use is:\n{search_object}")
results = []
after = 0
while len(results) < max_results or max_results <= 0:
page = self._get_next_search_page(object_type, search_object, after)
results.extend(page.results)
if page.paging is None:
break
after = page.paging.next.after
self.logger.debug(f"Total results found: {len(results)}")
return results
@keyword
def auth_with_token(self, access_token: str) -> None:
"""Authorize to HubSpot with Private App access token. This
keyword verifies the provided credentials by retrieving the
custom object schema from the API.
Learn more about Private Apps:
https://developers.hubspot.com/docs/api/private-apps
:param access_token: The access token created for the Private App
in your HubSpot account.
"""
if self.hs is None or getattr(self.hs, "access_token", "") != access_token:
self.hs = HubSpotApi(access_token=access_token)
try:
self.schemas
except SchemaApiException as e:
if e.status == 401:
raise HubSpotAuthenticationError(
"Authentication was not successful."
) from e
else:
raise e
self.logger.info("Authentication to Hubspot CRM API with token succeeded.")
else:
self.logger.info("Already authenticated with access token.")
@keyword
def auth_with_api_key(self, api_key: str) -> None:
"""Deprecated! Use ``Auth With Token`` instead.
Authorize to HubSpot with an account-wide API key. This
keyword verifies the provided credentials by retrieving the
custom object schema from the API.
:param api_key: The API key for the account to authenticate to.
"""
deprecation("Use `Auth With Token` as HubSpot removed support for API keys.")
if self.hs is None or getattr(self.hs, "api_key", "") != api_key:
self.hs = HubSpotApi(api_key=api_key)
try:
self.schemas
except SchemaApiException as e:
if e.status == 401:
raise HubSpotAuthenticationError(
"Authentication was not successful."
) from e
else:
raise e
self.logger.info(
"Authentication to Hubspot CRM API with API key successful."
)
else:
self.logger.info("Already authenticated with API key.")
@keyword
def search_for_objects(
self,
object_type: str,
*natural_search,
search: Optional[List[Dict]] = None,
string_query: str = "",
properties: Optional[Union[str, List[str]]] = None,
max_results: int = 1000,
) -> List[SimplePublicObject]:
"""Returns a list of objects of the specified ``type`` based on the
provided ``search`` criteria. The following types are supported:
- COMPANIES
- CONTACTS
- DEALS
- FEEDBACK SUBMISSIONS
- PRODUCTS
- TICKETS
- LINE ITEMS
- QUOTES
- Custom objects, which can be provided as the name of the
object or the custom object ID in Hubspot.
Returns no more than ``max_results`` which defaults to 1,000 records.
Provide 0 for all results.
By default, search criteria can be passed as additional unlabeled
arguments to the keyword. They must be provided in order:
``property_name``, ``operator``, ``value``. Boolean operators ``AND`` and
``OR`` can be used, but if both are used, groups of criteria combined
with ``AND`` will be combined first, with each of those groups being
combined with ``OR`` second. You can only define a maximum of three
groups of filters combined with ``OR`` and each of those groups can
have no more than three filters combined with ``AND``.
You can use the following operators in your search:
+---------------------+-------------------------------------------+
| OPERATOR | DESCRIPTION |
+=====================+===========================================+
| LT | Less than |
+---------------------+-------------------------------------------+
| LTE | Less than or equal to |
+---------------------+-------------------------------------------+
| GT | Greater than |
+---------------------+-------------------------------------------+
| GTE | Greater than or equal to |
+---------------------+-------------------------------------------+
| EQ | Equal to |
+---------------------+-------------------------------------------+
| NEQ | Not equal to |
+---------------------+-------------------------------------------+
| BETWEEN | Within the specified range |
+---------------------+-------------------------------------------+
| IN | Included within the specified list |
+---------------------+-------------------------------------------+
| NOT_IN | Not included within the specified list |
+---------------------+-------------------------------------------+
| HAS_PROPERTY | Has a value for the specified property. |
| | When using this operator, or its opposite |
| | below, you cannot provide a value. |
+---------------------+-------------------------------------------+
| NOT_HAS_PROPERTY | Doesn't have a value for the specified |
| | property. |
+---------------------+-------------------------------------------+
| CONTAINS_TOKEN | Contains a token. |
+---------------------+-------------------------------------------+
| NOT_CONTAINS_TOKEN | Doesn't contain a token. |
+---------------------+-------------------------------------------+
Example search:
.. code-block:: robotframework
*** Settings ***
Library RPA.Hubspot
Library RPA.Robocorp.Vault
Task Setup Authorize Hubspot
*** Tasks ***
Obtain contacts with search
${contacts}= Search for objects CONTACTS
... firstname EQ Alice AND lastname NEQ Smith
... OR enum1 HAS_PROPERTY
${message}= Catenate These contacts will have the first name "Alice" but not the last name "Smith",
... or they will have a value in the proeprty "enum1": ${contacts}
Log ${message}
*** Keywords ***
Authorize Hubspot
${secrets}= Get secret hubspot
Auth with api key ${secrets}[API_KEY]
Object Searching
================
Alternatively, search criteria can be passed as a list of
dictionaries to the label-only parameter ``search``.
To include multiple filter criteria, you can group filters within
``filterGroups``:
- When multiple ``filters`` are present within a ``filterGroup``, they'll
be combined using a logical AND operator.
- When multiple ``filterGroups`` are included in the request body,
they'll be combined using a logical OR operator.
You can include a maximum of three filterGroups with up to three
filters in each group.
.. code-block:: python
from RPA.Hubspot import Hubspot
from RPA.Robocorp.Vault import RobocorpVault
vault = RobocorpVault()
secrets = vault.get_secret("hubspot")
hs = Hubspot(secrets["API_KEY"])
combination_search = [
{
"filters": [
{
"propertyName": "firstname",
"operator": "EQ",
"value": "Alice",
},
{
"propertyName": "lastname",
"operator": "NEQ",
"value": "Smith",
},
]
},
{"filters": [{"propertyName": "enum1", "operator": "HAS_PROPERTY"}]},
]
contacts = hs.search_for_objects("CONTACTS", search=combination_search)
print(
"These contacts will have the first name 'Alice' but not the "
+ "last name 'Smith', or they will have a value in the "
+ f"property 'enum1': {contacts}"
)
===============================
Controlling Returned Properties
===============================
You can retrieve additional properties for the objects by defining
them with ``properties``. Properties must be provided as a single
property as a string, or a list of properties as a list. If a
requested property does not exist, it will be ignored.
==================
Using Associations
==================
Associated objects can be used as search criteria by using the
pseudo-property ``associations.{object_type}``, where ``{object_type}``
is a valid object type, such as ``contact``, but this is not
supported when seaching custom objects.
=======================
Text-based Search Query
=======================
If you want to search all text-based fields with a simple string,
it can be provided via the optional label-only parameter
``string_query``. This cannot be used at the same time with
``search_object`` or ``natural_search`` parameters.
:param natural_search: all additional unlabeled parameters will
be parsed as a natural language search.
:param search: the search object to use as search criteria.
:param string_query: a string query can be provided instead of a
search object which is used as a text-based search in all default
searchable properties in Hubspot.
:param properties: a list of strings representing return properties
to be included in the returned data.
:return: A list of found HubSpot objects of type ``SimplePublicObject``.
""" # noqa: E501
self._require_authentication()
if string_query:
search_object = ObjectSearchRequest(query=string_query)
elif natural_search:
search_object = SearchLexer(
natural_search, self.logger
).create_search_object()
elif search:
search_object = ObjectSearchRequest(
[
FilterGroup(
[
Filter(f.get("value"), f["propertyName"], f["operator"])
for f in g["filters"]
]
)
for g in search
]
)
else:
search_object = ObjectSearchRequest()
search_object.properties = (
[properties] if isinstance(properties, str) else properties
)
return self._search_objects(
self._pluralize_object(self._get_custom_object_id(object_type)),
search_object,
max_results=max_results,
)
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def _list_associations(
self, object_type: str, object_id: str, to_object_type: str
) -> List[AssociatedId]:
self._require_authentication()
results = []
after = None
while True:
page = self.hs.crm.objects.associations_api.get_all(
self._validate_object_type(self._singularize_object(object_type)),
object_id,
self._validate_object_type(self._singularize_object(to_object_type)),
after=after,
limit=500,
)
results.extend(page.results)
if page.paging is None:
break
after = page.paging.next.after
return results
def _batch_batch_requests(
self, ids: List[str], max_batch_size: int = 100
) -> List[List[str]]:
"""Breaks batch inputs down to a max size for the API, Hubspot
batch input maxes out at 100 by default.
"""
output = []
for i in range(math.ceil(len(ids) / max_batch_size)):
bottom = i * max_batch_size
top = (i + 1) * max_batch_size
current_list = ids[bottom:top]
output.append(current_list)
return output
def _report_batch_errors(self, response: Any, submitted_length: int):
if getattr(response, "num_errors", None):
if response.num_errors >= submitted_length:
raise HubSpotBatchResponseError(
"Batch failed all items with the following errors:\n"
+ str(response.errors)
)
elif response.num_errors > 0:
self.logger.warning(
"Batch returned some errors:\n" + str(response.errors)
)
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def _list_associations_by_batch(
self, object_type: str, object_id: List[str], to_object_type: str
) -> Dict[str, List[AssociatedId]]:
self._require_authentication()
batched_ids = self._batch_batch_requests(object_id)
collected_responses = {}
for i, batch in enumerate(batched_ids):
self.logger.info(
f"Executing batch index {i} of {len(batched_ids)} batch requests."
)
self.logger.debug(f"Batch contents:\n{batch}")
batch_reader = BatchInputPublicObjectId(
inputs=[PublicObjectId(o) for o in batch]
)
response = self.hs.crm.associations.batch_api.read(
self._singularize_object(self._get_custom_object_id(object_type)),
self._singularize_object(self._get_custom_object_id(to_object_type)),
batch_input_public_object_id=batch_reader,
)
self._report_batch_errors(response, len(object_id))
self.logger.debug(
f"Full results received for batch index {i}:\n{response.results}"
)
# pylint: disable=protected-access
collected_responses.update({o._from.id: o.to for o in response.results})
return collected_responses
@keyword
def list_associations(
self, object_type: str, object_id: Union[str, List[str]], to_object_type: str
) -> Union[List[AssociatedId], Dict[str, List[AssociatedId]]]:
"""List associations of an object by type, you must define the ``object_type``
with its ``object_id``. You must also provide the associated objects with
``to_object_type``. The API will return a list of dictionaries with
the associated object ``id`` and association ``type`` (e.g.,
``contact_to_company``).
You may provide a list of object IDs, if you do, the return object is a
dictionary where the keys are the requested IDs and the value associated
to each key is a list of associated objects (like a single search).
:param object_type: The type of object for the object ID
provided, e.g. ``contact``.
:param object_id: The HubSpot ID for the object of type ``object_type``.
If you provide a list of object_ids, they will be searched via the
batch read API.
:param to_object_type: The type of object associations to return.
:return: A list of dictionaries representing the associated objects.
The associated objects are returned as ``AssociatedId`` objects.
"""
self._require_authentication()
if isinstance(object_id, list):
return self._list_associations_by_batch(
object_type, object_id, to_object_type
)
else:
return self._list_associations(object_type, object_id, to_object_type)
@keyword
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def set_association(
self,
object_type: str,
object_id: str,
to_object_type: str,
to_object_id: str,
association_type: str = None,
) -> SimplePublicObjectWithAssociations:
"""Sets an association between two Hubspot objects. You must define
the primary ``object_type`` and it's Hubspot ``object_id``, as well
as the Hubspot object it is to be associated with by using the
``to_object_type`` and ``to_object_id``. You may also define the
``association_type``, but if not, one will be inferred based
on the provided object types, for example, if ``object_type`` is
``company`` and ``to_object_type`` is ``contact``, the inferred
``association_type`` will be ``company_to_contact``.
Returns the object with it's associations.
:param object_type: The type of object for the object ID
provided, e.g. ``contact``.
:param object_id: The HubSpot ID for the object of type ``object_type``.
:param to_object_type: The type of object to associate the ``object_id``
to.
:param to_object_id: The HubSpot ID for the object to associate the
``object_id`` to.
:return: The object represented by the ``object_id`` with the
new association. The associations will be available on the
returned object's ``associations`` property.
"""
self._require_authentication()
if not association_type:
association_type = f"{object_type}_to_{to_object_type}"
return self.hs.crm.objects.associations_api.create(
self._validate_object_type(object_type),
object_id,
self._validate_object_type(to_object_type),
to_object_id,
association_type,
)
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def _get_object(
self,
object_type: str,
object_id: str,
id_property: Optional[str] = None,
properties: Optional[Union[str, List[str]]] = None,
associations: Optional[Union[str, List[str]]] = None,
) -> Union[SimplePublicObject, SimplePublicObjectWithAssociations]:
self._require_authentication()
return self.hs.crm.objects.basic_api.get_by_id(
self._validate_object_type(object_type),
object_id,
properties=properties,
associations=(
[self._validate_object_type(obj) for obj in associations]
if associations
else None
),
id_property=id_property,
)
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def _get_object_by_batch(
self,
object_type: str,
object_id: List[str],
id_property: Optional[str] = None,
properties: Optional[Union[str, List[str]]] = None,
) -> List[SimplePublicObject]:
self._require_authentication()
batched_ids = self._batch_batch_requests(object_id)
collected_responses = []
for i, batch in enumerate(batched_ids):
self.logger.debug(f"Executing batch index {i} of batch requests:\n{batch} ")
batch_reader = BatchReadInputSimplePublicObjectId(
properties=properties
if isinstance(properties, list) or properties is None
else [properties],
id_property=id_property,
inputs=[SimplePublicObjectId(o) for o in batch],
)
response = self.hs.crm.objects.batch_api.read(
self._singularize_object(self._get_custom_object_id(object_type)),
batch_read_input_simple_public_object_id=batch_reader,
)
self._report_batch_errors(response, len(object_id))
self.logger.debug(
f"Full results received for batch index {i}:\n{response.results}"
)
collected_responses.extend(response.results)
return collected_responses
@keyword
def get_object(
self,
object_type: str,
object_id: Union[str, List[str]],
id_property: Optional[str] = None,
properties: Optional[Union[str, List[str]]] = None,
associations: Optional[Union[str, List[str]]] = None,
) -> Union[
SimplePublicObject,
SimplePublicObjectWithAssociations,
List[SimplePublicObject],
]:
"""Reads objects of ``object_type`` from HubSpot with the
provided ``object_id``. The objects can be found using an
alternate ID by providing the name of that HubSpot property
which contains the unique identifier to ``id_property``. The ``object_type``
parameter automatically looks up custom object IDs based on the
provided name. If a list of object IDs is provided, the batch
API will be utilized, but in that case, ``associations`` cannot be
returned.
A list of property names can be provided to ``properties``
and they will be included in the returned object. Nonexistent
properties are ignored.
A list of object types can be provided to ``associations`` and all
object IDs associated to the returned object of that type will
be returned as well. Object types passed to this parameter are
also validated against built-in objects and custom object schemas.
:param object_type: The object type to be returned and that has
the ID indicated.
:param object_id: The ID of the object to be returned.
:param id_property: (Optional) Can be used to allow the API to
search the object database using an alternate property as the
unique ID.
:param properties: (Optional) A list of strings representing
property names to be included in the returned object.
Nonexistent properties are ignored.
:param associations: (Optional) A list of strings representing
object types to retrieve as associated object IDs.
:return: The requested object as a ``SimplePublicObject`` or
``SimplePublicObjectWithAssociations`` type. If a batch request
was made, it returns a list of ``SimplePublicObject``.
"""
self._require_authentication()
if isinstance(object_id, list):
return self._get_object_by_batch(
object_type, object_id, id_property, properties
)
else:
return self._get_object(
object_type, object_id, id_property, properties, associations
)
def _create_simple_input_object(
self, properties: Dict[str, Any]
) -> CreateObjectInput:
"""Creates a ``SimplePublicObjectInput`` from the provided
dictionary of properties. The dictionary must have keys that
equal Hubspot properties of the underlying object.
"""
if "properties" in properties.keys():
raise ValueError(
"A Hubspot object cannot have a property called 'properties'."
)
return CreateObjectInput(properties=properties)
@keyword
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def create_object(self, object_type, **properties) -> SimplePublicObject:
"""Creates a new Hubspot object of the provided ``object_type``
and with the provided properties in Hubspot. Read-only or
nonexistent properties are ignored. The ``object_type``
parameter automatically looks up custom object IDs based on the
provided name.
The Hubspot properties to be updated must be provided as additional
labeled paremeters to this keyword.
Returns the newly created object. The new object's ``id`` is available
via the property ``id``.
:param object_type: The object type to be created.
:param properties: All remaining labeled parameters passed into
this keyword will be used as the properties of the new
object. Read-only or nonexistent properties will be ignored.
"""
self._require_authentication()
return self.hs.crm.objects.basic_api.create(
self._validate_object_type(object_type),
self._create_simple_input_object(properties),
)
@keyword
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def update_object(
self,
object_type: str,
object_id: Union[str, List[str]],
id_property: Optional[str] = None,
**properties,
) -> SimplePublicObject:
"""Performs a partial update of an Object identified by
``object_type`` and ``object_id`` with the provided properties
in Hubspot. The objects can be found using an
alternate ID by providing the name of that HubSpot property
which contains the unique identifier to ``id_property``. The ``object_type``
parameter automatically looks up custom object IDs based on the
provided name.
The Hubspot properties to be updated must be provided as additional
labeled paremeters to this keyword.
Returns the newly created object. The new object's ``id`` is available
via the property ``id``.
:param object_type: The object type to be created.
:param object_id: The HubSpot ID of the object to be updated
:param properties: All remaining labeled parameters passed into
this keyword will be used as the properties of the new
object. Read-only or nonexistent properties will be ignored.
"""
self._require_authentication()
return self.hs.crm.objects.basic_api.update(
self._validate_object_type(object_type),
object_id,
self._create_simple_input_object(properties),
id_property=id_property,
)
@property
def batch_input(self) -> BatchInputFactory:
if self._batch_input is None:
self._batch_input = BatchInputFactory()
return self._batch_input
@batch_input.setter
def batch_input(
self,
batch_factory: BatchInputFactory,
):
self._batch_input = batch_factory
@batch_input.deleter
def batch_input(self):
self._batch_input = None
@keyword
def create_new_batch(self, object_type: str, mode: BatchMode) -> None:
"""Creates a new blank batch input for the provided ``object_type`` in
either the ``UPDATE`` or ``CREATE`` mode.
See `Batch Inputs`` for complete information on using the batch
input API.
:param object_type: The object type to be created or updated by
the batch.
:param mode: either ``UPDATE`` or ``CREATE``.
"""
self.batch_input = BatchInputFactory(
mode, self._singularize_object(object_type)
)
@keyword
def add_input_to_batch(self, object_id: str = None, **properties) -> None:
"""Add the provided free-named keyword arguments to the current
batch input. If creating an ``UPDATE`` batch, you must also provide
the Hubspot object ``id`` (an alternate ID property cannot be used).
The keyword will fail if an ID is provided to a batch that is
currently in CREATE mode and has any inputs already.
See `Batch Inputs`` for complete information on using the batch
input API.
:param properties: A dictionary of HubSpot properties to set to
the HubSpot object being created or updated.
:param id: The HubSpot ID of the object to be updated. If provided,
the batch is assumed to be in UPDATE mode. The keyword will
fail if an ID is provided to a batch that is currently in CREATE
mode and has any inputs already.
"""
self.batch_input.add_input(properties, object_id)
@keyword
def extend_batch_with_inputs(
self, properties: List[Dict[str, str]], ids: List[str] = None
) -> None:
"""Extends the current batch input with the provided lists of
Hubspot ``properties`` and Hubspot object ``ids``. The ``ids``
parameter must be provided when extending an ``UPDATE`` batch.
The two provided lists will be zipped together in the same order
as provided.
The keyword will fail if an ID is provided to a batch that is
currently in CREATE mode and has any inputs already.
See `Batch Inputs`` for complete information on using the batch
input API.
:param properties: A list of dictionaries of HubSpot properties to
set to the HubSpot objects being created or updated.
:param ids: The HubSpot IDs of the objects to be updated. If provided,
the batch is assumed to be in UPDATE mode. The keyword will
fail if an ID is provided to a batch that is currently in CREATE
mode and has any inputs already.
"""
self.batch_input.extend_inputs(properties, ids)
@keyword
def clear_current_batch(self) -> BatchInputFactory:
"""Returns the current batch and then clears it.
See `Batch Inputs`` for complete information on using the batch
input API.
"""
old_batch = self.batch_input
del self.batch_input
return old_batch
@keyword
def set_current_batch_input(self, batch_input: BatchInputFactory) -> None:
r"""Sets the current batch input to the provided one.
See `Batch Inputs`` for complete information on using the batch
input API.
:param batch_input: A batch object such as one returned from
the ``Get current batch`` keyword.
"""
self.batch_input = batch_input
@keyword
def get_current_batch(self) -> BatchInputFactory:
"""Returns the current batch.
See `Batch Inputs`` for complete information on using the batch
input API.
:return: The current batch input object.
"""
return self.batch_input
@keyword
def get_current_batch_inputs(self) -> List[Dict[str, Dict[str, str]]]:
"""Returns the inputs in the current batch. The returned list will
be a list of dictionaries each with either 1 or 2 keys depending
on if the batch is in ``CREATE`` or ``UPDATE`` mode. If in ``UPDATE``
mode, the dictionaries will have the keys ``properties`` and ``id``,
but if in ``CREATE`` mode, the dictionaries will only have the
``properties`` key.
See `Batch Inputs`` for complete information on using the batch
input API.
:return: A list of dictionaries representing the current inputs.
"""
return [i.to_dict() for i in self.batch_input.inputs]
def _batch_batch_inputs(
self, max_batch_size: int = 100
) -> Union[List[CreateBatchInput], List[UpdateBatchInput]]:
"""Creates multiple batch input objects each with a max number of
inputs equal to the ``max_batch_size`` which defaults to 100.
"""
output = []
for i in range(math.ceil(len(self.batch_input.inputs) / max_batch_size)):
bottom = i * max_batch_size
top = (i + 1) * max_batch_size
current_input_obj = self.batch_input.create_hubspot_batch_object(
bottom, top
)
output.append(current_input_obj)
return output
@keyword
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def execute_batch(self) -> List[SimplePublicObject]:
"""Sends the current batch input to the Hubspot API.
Keyword will only fail if all inputs resulted in error. Partial
failures are reported as warnings.
See `Batch Inputs`` for complete information on using the batch
input API.
:return: The updated or created objects as a list of
``SimplePublicObject`` types.
"""
self._require_authentication()
if len(self.batch_input.inputs) > 0:
input_objects = self._batch_batch_inputs()
collected_results = []
for i, input_obj in enumerate(input_objects):
self.logger.info(
f"Executing batch index {i} of {len(input_objects)} batch requests."
)
self.logger.debug(f"Batch contents:\n{input_obj}")
if self.batch_input.mode is BatchMode.CREATE:
response = self.hs.crm.objects.batch_api.create(
self.batch_input.object_type,
input_obj,
)
elif self.batch_input.mode is BatchMode.UPDATE:
response = self.hs.crm.objects.batch_api.update(
self.batch_input.object_type,
input_obj,
)
else:
raise HubSpotBatchInputInvalidError(
f"Batch Input cannot be sent, "
f"current batch input mode is '{self.batch_input.mode}'"
)
self._report_batch_errors(response, len(self.batch_input))
self.logger.debug(
f"Full results received for batch index {i}:\n{response.results}"
)
collected_results.extend(response.results)
else:
raise HubSpotBatchInputInvalidError(
"Batch Input cannot be sent, current batch has no inputs."
)
return collected_results
@property
def pipelines(self) -> Dict[str, List[Pipeline]]:
return self._pipelines
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def _set_pipelines(self, object_type: str, archived: bool = False):
self._require_authentication()
valid_object_type = self._validate_object_type(object_type)
self._pipelines[valid_object_type] = (
self.hs.crm.pipelines.pipelines_api.get_all(
valid_object_type, archived=archived
)
).results
def _get_cached_pipeline(self, object_type, pipeline_id):
return next(
(
p
for p in self.pipelines.get(object_type, [])
if pipeline_id in (p.id, p.label)
),
None,
)
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def _get_set_a_pipeline(self, object_type, pipeline_id, use_cache=True):
self._require_authentication()
valid_object_type = self._validate_object_type(object_type)
if (
self._get_cached_pipeline(valid_object_type, pipeline_id) is None
or not use_cache
):
try:
response = self.hs.crm.pipelines.pipelines_api.get_by_id(
valid_object_type, pipeline_id
)
if self.pipelines.get(valid_object_type) is not list:
self._pipelines[valid_object_type] = []
self._pipelines[valid_object_type].extend([response])
except PipelineApiException:
self._set_pipelines(valid_object_type)
return self._get_cached_pipeline(valid_object_type, pipeline_id)
def _get_pipelines(
self, object_type, pipeline_id=None, archived=False, use_cache=True
):
self._require_authentication()
valid_object_type = self._validate_object_type(object_type)
if self.pipelines.get(valid_object_type) is None or not use_cache:
if pipeline_id is None:
self._set_pipelines(valid_object_type, archived)
else:
self._get_set_a_pipeline(object_type, pipeline_id, use_cache=False)
return (
self._get_set_a_pipeline(object_type, pipeline_id, use_cache)
if pipeline_id
else self.pipelines[valid_object_type]
)
@keyword
def list_pipelines(
self, object_type: str, archived: bool = False, use_cache: bool = True
) -> List[Pipeline]:
"""Returns a list of all pipelines configured in Hubspot for the
provided ``object_type``. By default only active, unarchived pipelines
are returned.
This keyword caches results for future use, to refresh results from
Hupspot, set ``use_cache`` to ``False``.
:param object_type: The object type to be returned and that has
the ID indicated. Custom objects will be validated against the
schema.
:param archived: (Optional) Setting this to ``True`` will return
archived pipelines as well.
:param use_cache: (Optional) Setting this to ``False`` will force
the system to recache the pipelines from Hubspot.
:return: A list of ``Pipeline`` objects representing the pipelines
associated with the provided ``object_type``.
"""
self._require_authentication()
return self._get_pipelines(
self._validate_object_type(object_type),
archived=archived,
use_cache=use_cache,
)
@keyword
def get_pipeline(
self, object_type: str, pipeline_id: str, use_cache: bool = True
) -> Pipeline:
"""Returns the ``object_type`` pipeline identified by ``pipeline_id``.
The provided ``pipeline_id`` can be provided as the label (case sensitive)
or API ID code.
The ``Pipeline`` object returned includes a ``stages`` property, which
is a list of ``PipelineStage`` objects. The ``stages`` of the pipeline
represent the discreet steps an object travels through within the pipeline.
The order of the steps is determined by the ``display_order`` property.
These properties can be accessessed with dot notation and generator
comprehension; however, these are advanced Python concepts, so
it is generally easier to use the keyword ``Get Pipeline Stages`` to
get an ordered dictionary of the stages from first to last.
**Example**
.. code-block:: robotframework
*** Tasks ***
Get Step One
${pipeline}= Get pipeline DEALS default
${step_one}= Evaluate
... next((s.label for s in $pipeline.stages if s.display_order == 0))
This keyword caches results for future use, to refresh results from
Hupspot, set ``use_cache`` to ``False``.
:param object_type: The object type to be returned and that has
the ID indicated. Custom objects will be validated against the
schema.
:param pipeline_id: The numerical pipeline ID or the pipeline
label visibal in the HubSpot UI (case sensitive).
:param use_cache: (Optional) Setting this to ``False`` will force
the system to recache the pipelines from Hubspot.
:return: The ``Pipeline`` object requested.
""" # noqa: E501
self._require_authentication()
return self._get_pipelines(
self._validate_object_type(object_type),
pipeline_id=pipeline_id,
use_cache=use_cache,
)
@keyword
def get_pipeline_stages(
self,
object_type: str,
pipeline_id: str,
label_as_key: bool = True,
use_cache: bool = True,
) -> Dict[str, Dict]:
"""Returns a dictionary representing the stages available in the
requested pipeline. Only pipelines for ``object_type`` are searched
using the ``pipeline_id`` as the label or Hubspot API identifier code.
By default, the keys of the returned dictionary represent the labels
of the stages, in order from first to last stage. You can have the
keyword return the numerical API ID as the key instead by setting
``label_as_key`` to ``False``.
Each item's value is a dictionary with three keys: ``id``, ``label``
and ``metadata``. The ``id`` is the numerical API ID associated with
the stage and ``label`` is the name of that stage. The
``metadata`` is a dictionary of metadata associated with that stage
(e.g., ``isClosed`` and ``probability`` for "deals" pipelines) that
is unique per pipeline.
**Example**
.. code-block:: robotframework
*** Settings ***
Library RPA.Hubspot
Library RPA.Robocorp.Vault
Task Setup Authorize Hubspot
*** Tasks ***
Use pipeline stages
${stages}= Get pipeline stages DEALS Default
${closed_won_stage_id}= Set variable ${stages}[Closed Won][id]
${deals}= Search for objects DEALS
... dealstage EQ ${closed_won_stage_id}
Log Deals that have been won: ${deals}
*** Keywords ***
Authorize Hubspot
${secrets}= Get secret hubspot
Auth with api key ${secrets}[API_KEY]
This keyword caches results for future use, to refresh results from
Hupspot, set ``use_cache`` to ``False``.
:param object_type: The object type to be returned and that has
the ID indicated. Custom objects will be validated against the
schema.
:param pipeline_id: The numerical pipeline ID or the pipeline
label visibal in the HubSpot UI (case sensitive).
:param label_as_key: (Optional) Defaults to ``True``. Setting this
to ``False`` will cause the returned dictionary to key off of ``id``
instead of ``label``.
:param use_cache: (Optional) Setting this to ``False`` will force
the system to recache the pipelines from Hubspot.
:return: A dictionary representing the pipeline stages and associated
data.
"""
self._require_authentication()
stages = self.get_pipeline(object_type, pipeline_id, use_cache).stages
stages.sort(key=lambda s: (s.display_order, s.label))
if label_as_key:
return {
s.label: {"id": s.id, "label": s.label, "metadata": dict(s.metadata)}
for s in stages
}
else:
return {
s.id: {"id": s.id, "label": s.label, "metadata": dict(s.metadata)}
for s in stages
}
@keyword
def get_current_stage_of_object(
self,
object_type: str,
object_id: str,
id_property: Optional[str] = None,
label_as_key: bool = True,
use_cache: bool = True,
) -> Tuple[str, Dict]:
"""Returns the current pipeline stage for the object as a tuple of
the stage label and that stage's associated metadata as a dictionary.
If you want the label to be returned as the numerical API ID, set
``label_as_key`` to False.
If the object type does not have an applied pipeline, the keyword
will fail.
This keyword caches results for future use, to refresh results from
Hupspot, set ``use_cache`` to ``False``.
:param object_type: The object type to be returned and that has
the ID indicated. Custom objects will be validated against the
schema.
:param object_id: The ID of the object to be returned.
:param id_property: (Optional) Can be used to allow the API to
search the object database using an alternate property as the
unique ID.
:param label_as_key: (Optional) Defaults to ``True``. Setting this
to ``False`` will cause the returned dictionary to key off of ``id``
instead of ``label``.
:param use_cache: (Optional) Setting this to ``False`` will force
the system to recache the pipelines from Hubspot.
:return: A tuple where index 0 is the label or ID of the object's
current stage and index 1 is associated data.
"""
self._require_authentication()
hs_object = self.get_object(object_type, object_id, id_property)
if hs_object.properties.get("pipeline"):
pipeline_stages = self.get_pipeline_stages(
object_type,
hs_object.properties["pipeline"],
label_as_key=False,
use_cache=use_cache,
)
stage_key = hs_object.properties.get(
"dealstage", hs_object.properties.get("hs_pipeline_stage")
)
stage_label = (
pipeline_stages[stage_key]["label"]
if label_as_key
else pipeline_stages[stage_key]
)
return (stage_label, pipeline_stages[stage_key])
else:
raise HubSpotNoPipelineError(
f"The {object_type} object type with ID "
+ f"'{object_id}' is not in a pipeline."
)
@keyword
def get_user(self, user_id: str = "", user_email: str = "") -> Dict:
"""Returns a dictionary with the keys ``id`` and ``email`` based on the
provided ``user_id`` or ``user_email``. If both are provided, this
keyword will prefer the ``user_id``.
.. note:: This keyword searches system users, not the CRM
owners database.
"""
self._require_token_authentication()
if user_id:
url = f"https://api.hubapi.com/settings/v3/users/{user_id}"
params = None
else:
url = f"https://api.hubapi.com/settings/v3/users/{user_email}"
params = {"idProperty": "EMAIL"}
headers = {
"accept": "application/json",
"Authorization": f"Bearer {self.hs.access_token}",
}
response = requests.request("GET", url, headers=headers, params=params)
response.raise_for_status()
self.logger.debug(
f"Response is:\nStatus: {response.status_code} {response.reason}\n"
+ f"Content: {response.json()}"
)
return response.json()
@keyword
@retry(
retry=retry_if_exception(_is_rate_limit_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=2, min=0.1),
before_sleep=_before_sleep_log(),
)
def get_owner_by_id(
self, owner_id: str = "", owner_email: str = "", user_id: str = ""
) -> PublicOwner:
r"""Returns an owner object with details about a HubSpot user denoted
as an owner of another HubSpot object, such as a contact or company.
You may provide the identifier as ``owner_id``, ``owner_email``, or
``user_id``. The ``owner_id`` will correspond to fields from the
CRM API while the ``user_id`` will correspond to the user
provisioning API (see keyword ``Get User``).
The owner object has the following attributes (accessible via
dot notation):
If more than one of these IDs are provided, the keyword prefers
the ``owner_id``, then ``owner_email``, then the ``user_id``.
:param owner_id: The owner's HubSpot ID.
:param owner_email: The email address registered to the owner.
:param user_id: The owner's associated HubSpot user ID.
:return: The requested ``PublicOwner`` object.
"""
self._require_authentication()
if owner_id:
id_property = "id"
elif owner_email:
id_property = "email"
elif user_id:
id_property = "userId"
else:
raise ValueError("All arguments cannot be empty.")
return self.hs.crm.owners.owners_api.get_by_id(
owner_id, id_property=id_property
)
@keyword
def get_owner_of_object(
self,
hs_object: Union[SimplePublicObject, SimplePublicObjectWithAssociations, Dict],
owner_property: str = None,
) -> PublicOwner:
r"""Looks up the owner of a given Hubspot object, the provided object
should be from this library or it should be a dictionary with an
``hubspot_owner_id`` key. If the object has no owner, this keyword
returns None. See keyword ``Get owner by ID`` for information about
the returned object.
You can use an alternate property as the owner ID property by providing
it with argument ``owner_property``. If that property does not exist
this keyword will try the default ``hubspot_owner_id`` property, instead.
:param object: A HubSpot object, best if the object was obtained
via another keyword such as ``Get owner by ID``
:param owner_property: An alternate property of the provided
object to use as the field containing the Owner to be looked up.
:return: The ``PublicOwner`` of the provided object.
"""
self._require_authentication()
try:
if owner_property:
owner_id = getattr(
hs_object.properties,
owner_property,
hs_object.properties.get(
owner_property, hs_object.properties["hubspot_owner_id"]
),
)
else:
owner_id = getattr(
hs_object.properties,
"hubspot_owner_id",
hs_object.properties["hubspot_owner_id"],
)
except AttributeError:
self.logger.debug(
"AttributeError caught while attempting to retrieve "
+ "owner information from object."
+ f"\nObject details: {hs_object}."
+ f"\nError details:\n{traceback.format_exc()}"
)
return None
return self.get_owner_by_id(owner_id) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Hubspot.py | 0.82755 | 0.182626 | Hubspot.py | pypi |
import base64
import copy
import json
import logging
import re
import string
import sys
from functools import partial
from pathlib import Path
import graphviz
from graphviz import ExecutableNotFound
from robot.errors import PassExecution
from robot.libraries.BuiltIn import BuiltIn
from RPA.Robocorp.utils import get_output_dir
class SchemaError(Exception):
"""Error raised when violating schema."""
class Graph:
"""Task execution graph.
Helper class which is used to store executed tasks and
transitions between them, and render the relationships
in a digraph.
Creates a dot-notation file and rendered graph using graphviz.
:param suite: Current suite running model
"""
# Default render format
FORMAT = "svg"
# Default attributes
GRAPH = {
"rankdir": "LR",
}
NODE = {
"shape": "box",
"style": "rounded,filled",
"margin": "0.15,0.1",
"height": "0",
"fontname": "Helvetica, Arial, sans-serif",
"fontsize": "12",
}
# Start / end nodes
TERMINATOR = {
"shape": "oval",
"style": "filled",
"color": "#cccccc",
"fillcolor": "#eeeeee",
"fontcolor": "#0f0f0f",
}
# Node background/font colors
COLORS = {
"none": {"color": "#eeeeee", "fontcolor": "#0f0f0f"},
"fail": {"color": "#d9534f", "fontcolor": "#ffffff"},
"pass": {"color": "#5cb85c", "fontcolor": "#ffffff"},
"warn": {"color": "#ec971f", "fontcolor": "#ffffff"},
}
def __init__(self, suite):
#: Current suite
self.suite = suite
#: Task data by name
self.tasks = {}
#: Transition pairs between tasks
self.edges = set()
#: Current running task
self.current = None
#: Flag for successful end of process
self.is_end = False
self._parse_tasks(suite.tests)
def _parse_tasks(self, tasks):
"""Parse tasks (nodes) and assign unique labels."""
for position, task in enumerate(tasks):
label = self._create_label(position)
self.tasks[task.name] = {
"name": task.name,
"label": label,
"result": "none",
"doc": task.doc or task.name,
}
@staticmethod
def _create_label(position):
"""Generate label for node, e.g. A, B, ..., AA, AB, AC, ..."""
letters = string.ascii_uppercase
label = ""
while True:
position, index = divmod(position, len(letters))
label = letters[index] + label
if not position:
return label
position -= 1
def _create_graph(self, strip=True):
"""Create graphviz graph from current execution state."""
graph = graphviz.Digraph(
name=self.suite.name,
format=self.FORMAT,
graph_attr=self.GRAPH,
node_attr=self.NODE,
)
# Start/end nodes
graph.node("Start", **self.TERMINATOR)
if self.is_end:
graph.node("End", **self.TERMINATOR)
# Task nodes
for task in self.tasks.values():
result = task.get("result", "none")
if not (result == "none" and strip):
colors = self.COLORS[result]
graph.node(task["label"], task["name"], tooltip=task["doc"], **colors)
# Edges
for src, dst in self.edges:
src = src if src == "Start" else self.tasks[src]["label"]
dst = dst if dst == "End" else self.tasks[dst]["label"]
graph.edge(src, dst)
return graph
def render_to_file(self, path, strip=True):
"""Render graphviz graph to given file."""
path = Path(path)
graph = self._create_graph(strip)
return graph.render(filename=path.name, directory=path.parent)
def render_to_bytes(self, strip=True):
"""Render graphviz graph to in-memory bytes object."""
graph = self._create_graph(strip)
return graph.pipe()
def set_next(self, task):
"""Add transition between previous and next task."""
previous, self.current = self.current, task.name
if not previous:
assert not self.edges, "Edges exist without previous task"
previous = "Start"
assert not self.is_end, f"Attempting to add task after end: {self.current}"
assert self.current in self.tasks, f"Unknown task: {self.current}"
pair = (previous, self.current)
if pair not in self.edges:
self.edges.add(pair)
def set_result(self, result):
"""Set execution result for current task."""
assert not self.is_end, "End already set"
task = self.tasks[self.current]
task["result"] = str(result).lower()
def set_end(self):
"""Add final edge to End node."""
assert not self.is_end, "End already set"
self.edges.add((self.current, "End"))
self.is_end = True
class Schema:
"""Task execution schema.
A library for validating transitions betweens tasks,
and evaluating possible schema-defined actions when
these transitions are triggered.
:param schema: content of schema JSON file
:param names: names of tasks in the current suite
"""
def __init__(self, schema, names):
#: Schema properties by task name
self.tasks = {}
#: Aliases for tasks
self.aliases = {}
#: First task in execution
self.start = None
#: Allowed end task(s)
self.end = []
self._parse_schema(schema, names)
def _parse_schema(self, schema, names):
"""Parse schema file and validate contents.
:param schema: content of schema file
:param tasks: tasks in suite execution
"""
# First pass: Parse names and aliases
for name, properties in schema.get("tasks", {}).items():
assert name in names, f"Unknown task name: {name}"
assert name not in self.tasks, f"Duplicate task name: {name}"
# Flag for first task in the execution
if properties.get("start", False):
assert self.start is None, "Duplicate start task"
self.start = name
# Flag for allowed end task
if properties.get("end", False):
self.end.append(name)
# Optional task alias
alias = properties.get("alias")
if alias:
assert alias not in self.aliases, f"Duplicate alias: {alias}"
self.aliases[alias] = name
self.tasks[name] = properties
# Second pass: Parse references to other tasks
for name, properties in self.tasks.items():
# Whitelist of allowed next tasks
if "next" in properties:
properties["next"] = [
self.resolve_reference(task) for task in properties["next"]
]
# Actions for resolving the next task
if "actions" in properties:
properties["actions"] = [
self._create_action(action) for action in properties["actions"]
]
# No start defined in schema, fallback to first in suite
if not self.start:
self.start = names[0]
def _create_action(self, action):
"""Convert action definition in schema to callable."""
assert "task" in action, "Next task undefined for action"
task = self.resolve_reference(action["task"])
callbacks = {
"exception": self._action_exception,
"condition": self._action_condition,
"status": self._action_status,
}
operator = set(callbacks) & set(action)
assert operator, f"Unknown action definition: {action}"
assert len(operator) == 1, f"Multiple conditions in action: {action}"
operator = operator.pop()
callback = callbacks[operator]
callback = partial(callback, action[operator])
return callback, task
def _action_exception(self, pattern, result):
"""Schema action: catch exception if it matches message pattern."""
if result.passed:
return False
if not re.match(pattern, result.message):
return False
result.message = f"Transition: message = {pattern}"
result.status = result.PASS
return True
def _action_condition(self, condition, result):
"""Schema action: evaluate Robot Framework expression."""
if not result.passed:
return False
if not BuiltIn().evaluate(condition):
return False
result.message = f"Transition: {condition}"
return True
def _action_status(self, status, result):
"""Schema action: compare test result to expected."""
if result.status.upper() != status.upper():
return False
result.message = f"Transition: status == {status}"
result.status = result.PASS
return True
def resolve_reference(self, name):
"""Convert task reference to original name."""
if name in self.tasks:
return name
elif name in self.aliases:
return self.aliases[name]
else:
raise ValueError(f"Unknown task or alias: {name}")
def validate(self, src, dst):
"""Validate transition between two tasks."""
assert src in self.tasks, f"Unknown source task: {src}"
# Optional end task validation
if dst == "end":
if self.end and src not in self.end:
raise SchemaError("Unexpected end task")
return
if dst not in self.tasks:
raise SchemaError(f"Destination '{dst}' not in schema")
if "next" in self.tasks[src] and dst not in self.tasks[src]["next"]:
raise SchemaError(f"Invalid transition '{src}' -> '{dst}'")
def evaluate_actions(self, src, result):
"""Evaluate all actions for the source task,
and return any potential triggered destination tasks.
"""
actions = self.tasks[src].get("actions", [])
# Evaluate all callbacks
for action, task in actions:
if action(result):
return task
# No conditions matched
return None
class Tasks:
"""`Tasks` is a library for controlling task execution during a Robot Framework run.
It allows conditional branching between tasks, loops and jumps, and optionally
validating the execution through a schema file. It can also be used to
visualize the tasks as a graph.
.. _model:
**Execution model**
In a typical Robot Framework run, tasks are ordered linearly in a file and
they're executed in definition order. Events that happen during
the execution can not affect the order and only have the option to fail the task
or continue as defined.
Using the `Tasks` library, it's possible to change this model according
to different states or inputs. The execution will start by running a single
start task from the suite, and then according to user-defined keywords or
schema rules select the next task. Any task which is defined in the same file
can be used, and the same task can also be used multiple times during a single
execution.
.. _execution-example:
Example:
As an example, the following Robot Framework file describes a process where
a task would have to be executed multiple times before a condition is reached.
In a real-world scenario, these tasks would be more complicated, instead of just
incrementing numbers.
.. code-block:: robotframework
*** Settings ***
Library RPA.Tasks
*** Variables ***
${CURRENT} ${1}
${TARGET} ${5}
*** Tasks ***
Check loop condition
Log I'm trying to count to ${TARGET}
Set next task if ${CURRENT} >= ${TARGET}
... Target reached
... Increment current number
This will not run
Fail This should never run
Increment current number
Set suite variable ${CURRENT} ${CURRENT + 1}
Log Number is now ${CURRENT}
Jump to task Check loop condition
Target reached
Log Those are some good numbers!
The execution for this example would go as follows:
1. It starts from ``Check loop condition``, as it's the first task in the file.
2. During the first task, the keyword ``Set next task if`` is called, which queues
up the next task according to a condition.
3. In the initial state, we have not reached the target number, and will next run
the task ``Increment current number``.
4. The second task executes normally and in the end jumps back to the first
task using the keyword ``Jump to task``.
5. The above sequence is repeated until the condition is met, and we move to
the final task of the file. This final task does not schedule further tasks
and the execution ends.
You can also note the task ``This will not run``, which as the name implies
is never executed, as no other task schedules or jumps to it.
The console log from the above execution shows how the same task is executed
multiple times:
.. code-block:: console
==============================================================================
Incrementing Process
==============================================================================
#1 Check loop condition | PASS |
Transition: Set by keyword
------------------------------------------------------------------------------
#2 Increment current number | PASS |
Transition: Set by keyword
------------------------------------------------------------------------------
#3 Check loop condition | PASS |
Transition: Set by keyword
------------------------------------------------------------------------------
#4 Increment current number | PASS |
Transition: Set by keyword
------------------------------------------------------------------------------
#5 Check loop condition | PASS |
Transition: Set by keyword
------------------------------------------------------------------------------
#6 Increment current number | PASS |
Transition: Set by keyword
------------------------------------------------------------------------------
#7 Check loop condition | PASS |
Transition: Set by keyword
------------------------------------------------------------------------------
#8 Increment current number | PASS |
Transition: Set by keyword
------------------------------------------------------------------------------
#9 Check loop condition | PASS |
Transition: Set by keyword
------------------------------------------------------------------------------
#10 Target reached | PASS |
------------------------------------------------------------------------------
Incrementing Process:: [/graph_incrementing_process.svg] | PASS |
10 critical tasks, 10 passed, 0 failed
10 tasks total, 10 passed, 0 failed
==============================================================================
.. _graph:
**Graph**
A common way to document a process is through a directed graph. These graphs
are usually drawn manually and describe the expected higher level steps.
The actual implementation itself follows a different path through a graph,
depending on inputs or implementation details. This library visualizes this
execution graph using the `Graphviz <https://graphviz.org>`_ tool.
After the execution is finished, it will create a
`DOT <https://en.wikipedia.org/wiki/DOT_(graph_description_language)>`_ file
and render it as an image. This image will automatically be appended
to the suite's documentation field.
**Requirements**
Drawing the graph requires a working installation of
`Graphviz <https://graphviz.org>`_. This can be installed through their
website or by using `Conda <https://docs.conda.io/>`_.
This requirement is optional for the functioning of this library, and will
display a warning if the tool is not available. The visualization
can be entirely disabled with the ``graph`` argument during library
initialization.
.. _schema:
**Schema**
There is an option to define a schema file for the suite, which is written in JSON.
This file will be used to validate the actual execution and fail it if an unexpected
transition between tasks happens. It can also define rules for selecting the next
task, which allows separating the task and process definitions.
Example:
The execution-example shown previously used keywords to control
the execution. This can also be done using the following schema:
.. code-block:: json
{
"tasks": {
"Check loop condition": {
"alias": "check",
"start": true,
"next": [
"increment",
"target"
],
"actions": [
{
"condition": "$CURRENT >= $TARGET",
"task": "target"
},
{
"condition": "$CURRENT < $TARGET",
"task": "increment"
}
]
},
"Increment current number": {
"alias": "increment",
"next": [
"check"
],
"actions": [
{
"status": "PASS",
"task": "check"
}
]
},
"Target reached": {
"alias": "target",
"end": true,
"next": []
}
}
}
This has the added benefit of protecting against implementation errors,
as the library will validate the start and end tasks, and transitions between
different tasks.
After this schema has been taken into use, the aforementioned example
will reduce to the following:
.. code-block:: robotframework
*** Settings ***
Library RPA.Tasks schema=counter-schema.json
*** Variables ***
${CURRENT} ${1}
${TARGET} ${5}
*** Tasks ***
Check loop condition
Log I'm trying to count to ${TARGET}
This will not run
Fail This should never run
Increment current number
Set suite variable ${CURRENT} ${CURRENT + 1}
Log Number is now ${CURRENT}
Target reached
Log Those are some good numbers!
**Format**
The current format is JSON with the following structure:
.. code-block:: javascript
{
"tasks": {
[name: string]: {
"alias": string,
"start": boolean,
"end": boolean,
"next": string[],
"actions": action[],
}
}
}
Each schema is a map of tasks with various properties. The keys must
match the task names in the Robot Framework file definition. All properties
inside the task are optional.
The available properties and their uses:
- *alias*: Define a short name for the task, which can be used as a reference
inside the schema.
- *start*: Start task for execution. There can be only one task with this
enabled. If not defined, will default to first task in the file.
- *end*: Valid end task for execution. There can be multiple tasks with this
enabled. Fails the execution if this is defined for any task and the
execution stops in a non-end task.
- *next*: List of valid tasks to transition to from this task. Supports
alias definitions.
- *actions*: List of actions that are executed at the end of the task.
See section below for details.
The types of actions:
- *exception*: Set the next task if a matching exception occurs.
Matches the exception message as regex.
- *condition*: Set the next task if a conditional expression is true.
Allows using Robot Framework variables.
- *status*: Set the next task if the current task's result matches,
e.g. PASS or FAIL.
Examples of actions:
.. code-block:: json
[
{"exception": ".*ValueError.*", "task": "Invalid input values"},
{"condition": "$ATTEMPTS > 10", "task": "Too many attempts"},
{"status": "PASS", "task": "Success state"}
]
""" # noqa: E501
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
ROBOT_LISTENER_API_VERSION = 3
def __init__(
self, execution_limit=1024, schema=None, graph=True, graph_inline=True
):
"""There are a few arguments for controlling the Tasks library.
:param execution_limit: Maximum number of tasks to run in suite,
used to prevent infinite loops
:param schema: Path to optional schema file
:param graph: Render execution result as graph using graphviz
:param graph_inline: Inline graph into log, instead of saving as file
"""
self.ROBOT_LIBRARY_LISTENER = self
#: Current task execution count
self.count = 0
#: Maximum task execution
self.limit = int(execution_limit)
#: Current suite running model
self.suite = None
#: Original task running models
self.tasks = []
#: Current running task
self.current = None
#: Next scheduled task
self.next = None
#: Task execution schema
self.schema = None
self.schema_path = schema
#: Task execution graph
self.graph = None
self.graph_options = {"enabled": graph, "inline": graph_inline}
def _load_schema(self):
"""Load schema from file, if defined."""
self.schema = None
if not self.schema_path:
return
with open(self.schema_path, encoding="utf-8") as fd:
data = json.load(fd)
names = [task.name for task in self.tasks]
self.schema = Schema(data, names)
def _task_by_name(self, name):
"""Find task execution object by shortname."""
for task in self.tasks:
if task.name == name:
return task
raise ValueError(f"Task not found: {name}")
def _find_next_task(self, result):
"""Resolve the next task based on the previous result."""
# TODO: Move all result object modifying here
task = None
try:
if self.next:
task = self.next
result.message = "Transition: Set by keyword"
elif self.schema:
task = self.schema.evaluate_actions(self.current.name, result)
task = self._task_by_name(task) if task else None
if self.schema:
name = task.name if task else "end"
self.schema.validate(self.current.name, name)
except SchemaError as err:
logging.error(err)
result.status = result.FAIL
finally:
self.next = None
return task, result
def _append_task(self, task):
"""Append new copy of task to execution queue."""
self.count += 1
# Ensure we don't edit original model
name = "#{:<3} {}".format(self.count, task.name)
copied = task.copy(name=name)
self.suite.tests.append(copied)
self.current = task
# Show transition between tasks
self.graph.set_next(task)
def _start_suite(self, data, result):
"""Robot listener method, called on suite start.
Copies original tasks to be used as source for scheduling.
"""
del result
self.count = 0
self.next = None
self.suite = data
self.tasks = copy.deepcopy(self.suite.tests)
self.graph = Graph(self.suite)
self.suite.tests.clear()
try:
self._load_schema()
except Exception as exc: # pylint: disable=broad-except
logging.error("Schema parsing failed: %s", exc)
sys.exit(1)
if self.schema:
self._append_task(self._task_by_name(self.schema.start))
else:
self._append_task(self.tasks[0])
def _end_suite(self, data, result):
"""Render graph of suite execution to the documentation field."""
del result
if not self.graph_options.get("enabled", True):
return
try:
if self.graph_options.get("inline", True):
# Render as inline data URI
data = self.graph.render_to_bytes()
src = "data:image/svg+xml;base64,{}".format(
base64.b64encode(data).decode("utf-8")
)
else:
# Render to file
dirname = get_output_dir()
filename = "graph_{}".format(data.name.lower().replace(" ", "_"))
path = Path(dirname, filename)
src = self.graph.render_to_file(str(path))
BuiltIn().set_suite_documentation(f"[{src}|Graph]", append=True)
except ExecutableNotFound as err:
logging.warning("Graphviz executable not found: %s", err)
def _end_test(self, data, result):
"""Robot listener method, called on test end.
Rewrites next executable task, if overriden by keywords.
Appends incrementing number to prevent task naming conflicts.
"""
del data
# Schema actions override status, store original result for graph
status = result.status
task, result = self._find_next_task(result)
if status != result.PASS:
self.graph.set_result("fail")
else:
self.graph.set_result("pass")
if not task:
self.graph.set_end()
else:
self._append_task(task)
def set_next_task(self, name):
"""Set the next task to be executed.
Should be a task in the same suite.
:param name: Name of next task
"""
task = self._task_by_name(name)
if self.next:
logging.warning(
"Overwriting scheduled task '%s' with '%s'", self.next.name, task.name
)
logging.info("Scheduling task: %s", task.name)
assert self.count < self.limit, "Reached task execution limit"
if self.schema:
self.schema.validate(self.current.name, task.name)
self.next = task
def set_next_task_if(self, condition, name, default=None):
"""Set the next task according to the condition.
If no default is given, does not modify execution order.
:param condition: Condition expression to evaluate
:param name: Name of next task, if successful
:param default: Name of next task, if unsuccessful
"""
is_true = (
BuiltIn().evaluate(condition)
if isinstance(condition, str)
else bool(condition)
)
logging.info("Condition: %s -> %s", condition, is_true)
task = name if is_true else default
if task:
self.set_next_task(task)
def jump_to_task(self, name):
"""Jump directly to given task, skipping the rest of the task
execution. If run inside a teardown, also skips the rest of the
teardown sequence.
"""
self.set_next_task(name)
raise PassExecution(f"Jumping to: {self.next}")
def jump_to_task_if(self, condition, name, default=None):
"""Jump directly to given task according to the condition."""
self.set_next_task_if(condition, name, default)
if self.next:
raise PassExecution(f"Jumping to: {self.next}")
def set_next_task_if_keyword_fails(self, task, keyword, *args):
"""Executes given keyword and sets the next task if it fails."""
success = BuiltIn().run_keyword_and_return_status(keyword, *args)
if not success:
self.set_next_task(task)
def set_next_task_if_keyword_succeeds(self, task, keyword, *args):
"""Executes given keyword and sets the next task if it succeeds."""
success = BuiltIn().run_keyword_and_return_status(keyword, *args)
if success:
self.set_next_task(task)
def jump_to_task_if_keyword_fails(self, task, keyword, *args):
"""Executes given keyword and jumps to given task if it fails."""
success = BuiltIn().run_keyword_and_return_status(keyword, *args)
if not success:
self.jump_to_task(task)
def jump_to_task_if_keyword_succeeds(self, task, keyword, *args):
"""Executes given keyword and jumps to given task if it succeeds."""
success = BuiltIn().run_keyword_and_return_status(keyword, *args)
if success:
self.jump_to_task(task) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Tasks.py | 0.699049 | 0.343589 | Tasks.py | pypi |
import json
import logging
import sys
from collections import OrderedDict
from typing import Any, Union, Dict
import requests
from simple_salesforce import Salesforce as SimpleSalesforce
from simple_salesforce import SFType
from RPA.Tables import Table, Tables
class SalesforceAuthenticationError(Exception):
"Error when authenticated Salesforce instance does not exist."
class SalesforceDataNotAnDictionary(Exception):
"Error when parameter is not dictionary as expected."
class SalesforceDomainChangeError(Exception):
"Error when changing domains while a session is active."
class Salesforce:
"""`Salesforce` is a library for accessing Salesforce using REST API.
The library extends `simple-salesforce library`_.
More information available at `Salesforce REST API Developer Guide`_.
.. _Salesforce REST API Developer Guide:
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_what_is_rest_api.htm
.. _simple-salesforce library:
https://github.com/simple-salesforce/simple-salesforce
**Dataloader**
The keyword `execute_dataloader_import` can be used to mimic
`Salesforce Dataloader`_ import behaviour.
`input_object` can be given in different formats. Below is an example where
input is in `RPA.Table` format in **method a** and list format in **method b**.
.. _Salesforce Dataloader:
https://developer.salesforce.com/docs/atlas.en-us.dataLoader.meta/dataLoader/data_loader.htm
.. code-block:: robotframework
*** Settings ***
Library RPA.Salesforce
Library RPA.Database
Task Setup Authorize Salesforce
*** Tasks ***
# Method a
${orders}= Database Query Result As Table
... SELECT * FROM incoming_orders
${status}= Execute Dataloader Insert
... ${orders} ${mapping_dict} Tilaus__c
# Method b
${status}= Execute Dataloader Insert
... ${WORKDIR}${/}orders.json ${mapping_dict} Tilaus__c
Example file **orders.json**
.. code-block:: json
[
{
"asiakas": "0015I000002jBLIQA2"
},
{
"asiakas": "0015I000002jBLDQA2"
},
]
`mapping_object` describes how the input data fields are mapped into Salesforce
object attributes. In the example, the mapping defines that `asiakas` attribute in the
input object is mapped into `Tilaaja__c` attribute of `Tilaus__c` custom Salesforce object.
.. code-block:: json
{
"Tilaus__c": {
"asiakas": "Tilaaja__c"
},
}
Object type could be, for example, `Tilaus__c`.
**Salesforce object operations**
Following operations can be used to manage Salesforce objects:
* Get Salesforce Object By Id
* Create Salesforce Object
* Update Salesforce Object
* Upsert Salesforce Object
* Delete Salesforce Object
* Get Salesforce Object Metadata
* Describe Salesforce Object
There are two ways to set the Salesforce domain. You can set the domain at time of
library import or using the `Set Domain` keyword.
There are several ways to declare a domain at time of library import:
.. code-block:: robotframework
*** Settings ***
Library RPA.Salesforce sandbox=${TRUE}
Or using the domain to your Salesforce My domain:
.. code-block:: robotframework
*** Settings ***
Library RPA.Salesforce domain="robocorp"
The domain can also be set using the keyword `Set Domain`:
.. code-block:: robotframework
*** Settings ***
Library RPA.Salesforce
*** Tasks ***
# Sets the domain for a sandbox environment
Set Domain sandbox
# Sets the domain to a Salseforce My domain
Set Domain robocorp
# Sets to domain to the default of 'login'
Set Domain
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.Salesforce
Task Setup Authorize Salesforce
*** Variables ***
${ACCOUNT_NOKIA} 0015I000002jBLDQA2
*** Tasks ***
Change account details in Salesforce
&{account}= Get Salesforce Object By Id Account ${ACCOUNT_NOKIA}
&{update_obj}= Create Dictionary Name=Nokia Ltd BillingStreet=Nokia bulevard 1
${result}= Update Salesforce Object Account ${ACCOUNT_NOKIA} ${update_obj}
*** Keywords ***
Authorize Salesforce
${secrets}= Get Secret salesforce
Auth With Token
... username=${secrets}[USERNAME]
... password=${secrets}[PASSWORD]
... api_token=${secrets}[API_TOKEN]
**Python**
.. code-block:: python
import pprint
from RPA.Salesforce import Salesforce
from RPA.Robocorp.Vault import FileSecrets
pp = pprint.PrettyPrinter(indent=4)
filesecrets = FileSecrets("secrets.json")
secrets = filesecrets.get_secret("salesforce")
sf = Salesforce()
sf.auth_with_token(
username=secrets["USERNAME"],
password=secrets["PASSWORD"],
api_token=secrets["API_TOKEN"],
)
nokia_account_id = "0015I000002jBLDQA2"
account = sf.get_salesforce_object_by_id("Account", nokia_account_id)
pp.pprint(account)
billing_information = {
"BillingStreet": "Nokia Bulevard 1",
"BillingCity": "Espoo",
"BillingPostalCode": "01210",
"BillingCountry": "Finland",
}
result = sf.update_salesforce_object("Account", nokia_account_id, billing_information)
print(f"Update result: {result}")
""" # noqa: E501
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
account = {"Name": None, "Id": None}
def __init__(self, sandbox: bool = False, domain: str = "login") -> None:
self.logger = logging.getLogger(__name__)
self.sf = None
self.set_domain("sandbox" if sandbox else domain)
self.session = None
self.pricebook_name = None
self.dataloader_success = []
self.dataloader_errors = []
def _require_authentication(self) -> None:
if self.sf is None:
raise SalesforceAuthenticationError("Authentication is not completed")
def _require_no_session(self) -> None:
if self.session_id or self.instance:
raise SalesforceDomainChangeError(
"Domains cannot be changed while a session is active"
)
@property
def session_id(self):
return self.sf.session_id if self.sf else None
@property
def instance(self):
return self.sf.sf_instance if self.sf else None
def set_domain(self, domain: str = "login") -> None:
"""Used to set the domain the `Auth With Token` keyword will use. To set
the domain to 'test' or if using a sandbox environment use "sandbox" as the
domain. If you have a Salsesforce My domain you may also input that name. If
the `domain` argument is not used the default domain is "login".
:param domain: "sandbox" or the name of the Salesforce My domain;
if no argument provided defaults to "login"
"""
self._require_no_session()
self.domain = "test" if domain.lower() == "sandbox" else domain
def get_domain(self) -> str:
"""Used to determine the current domain that has been set
:returns: string of the currently set domain
"""
return self.domain
def auth_with_token(self, username: str, password: str, api_token: str) -> None:
"""Authorize to Salesforce with security token, username
and password creating instance.
:param username: Salesforce API username
:param password: Salesforce API password
:param api_token: Salesforce API security token
"""
self.session = requests.Session()
self.sf = SimpleSalesforce(
username=username,
password=password,
security_token=api_token,
domain=self.domain,
session=self.session,
)
self.logger.debug("Salesforce session id: %s", self.session_id)
def auth_with_connected_app(
self,
username: str,
password: str,
api_token: str,
consumer_key: str,
consumer_secret: str,
embed_api_token: bool = False,
) -> None:
"""Authorize to Salesforce with security token, username,
password, connected app key, and connected app secret
creating instance.
:param username: Salesforce API username
:param password: Salesforce API password
:param api_token: Salesforce API security token
:param consumer_key: Salesforce connected app client ID
:param consumer_secret: Salesforce connected app client secret
:param embed_api_token: Embed API token to password (default: False)
**Python**
.. code-block:: python
from RPA.Salesforce import Salesforce
from RPA.Robocorp.Vault import Vault
SF = Salesforce(domain="robocorp-testing-stuff.develop.my")
VAULT = Vault()
secrets = VAULT.get_secret("salesforce")
SF.auth_with_connected_app(
username=secrets["USERNAME"],
password=secrets["PASSWORD"],
api_token=secrets["API_TOKEN"],
consumer_key=secrets["CONSUMER_KEY"],
consumer_secret=secrets["CONSUMER_SECRET"],
)
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.Salesforce domain=robocop-testing-stuff.develop.my
Library RPA.Robocorp.Vault
*** Tasks ***
Authenticate to Salesforce using connected app
${secrets}= Get Secret salesforce
Auth with connected app
... username=${secrets}[USERNAME]
... password=${secrets}[PASSWORD]
... api_token=${secrets}[API_TOKEN]
... consumer_key=${secrets}[CONSUMER_KEY]
... consumer_secret=${secrets}[CONSUMER_SECRET]
"""
self.session = requests.Session()
request_data = {
"username": username,
"password": f"{password}{api_token}" if embed_api_token else password,
"client_id": consumer_key,
"client_secret": consumer_secret,
"grant_type": "password",
}
response = requests.post(
f"https://{self.domain}.salesforce.com/services/oauth2/token",
headers={"Content-Type": "application/x-www-form-urlencoded"},
data=request_data,
)
try:
response.raise_for_status()
result = response.json()
if result.get("access_token"):
self.sf = SimpleSalesforce(
instance_url=result["instance_url"],
session_id=result["access_token"],
domain=self.domain,
session=self.session,
)
self.logger.debug("Salesforce session id: %s", self.session_id)
else:
error_message = (
"Could not get access token\n"
f"Details: {response.status_code} {response.text}"
)
raise SalesforceAuthenticationError(error_message)
except requests.exceptions.HTTPError as err:
error_message = (
f"{str(err)}\nDetails: {response.status_code} {response.text}"
)
raise SalesforceAuthenticationError(error_message) from err
def execute_apex(
self, apex: str, apex_data: Dict = None, apex_method: str = "POST", **kwargs
):
"""Execute APEX operation.
The APEX classes can be added via Salesforce Developer console
(from menu: File > New > Apex Class).
Permissions for the APEX classes can be set via Salesforce Setup
(Apex Classes -> Security).
:param apex: endpoint of the APEX operation
:param apex_data: data to be sent to the APEX operation
:param apex_method: operation method
:param kwargs: additional arguments to be passed to the APEX request
:return: result of the APEX operation
**Python**
.. code-block:: python
from RPA.Salesforce import Salesforce
SF = Salesforce(domain="robocorp-testing-stuff.develop.my")
# authenticate to Salesforce
SF.execute_apex(apex="MyClass", apex_data={"data": "value"})
result = SF.execute_apex(
apex="getAccount/?id=0017R00002xmXB1QAM",
apex_method="GET")
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.Salesforce domain=robocop-testing-stuff.develop.my
*** Tasks ***
Executing APEX operations
# Authenticate to Salesforce
&{apex_data}= Create Dictionary data=value
${result}= Execute APEX MyClass apex_data=${apex_data}
${result}= Execute APEX
... apex=getAccount/?id=0017R00002xmXB1QAM
... apex_method=GET
"""
return self.sf.apexecute(apex, method=apex_method, data=apex_data, **kwargs)
def _get_values(self, node, prefix=None, data=None):
if data is None:
data = []
if prefix is None:
prefix = []
if isinstance(node, OrderedDict):
for k, v in node.items():
if k != "attributes":
prefix.append(k)
self._get_values(v, prefix, data)
prefix = prefix[:-1]
else:
data.append((sys.intern(".".join(prefix)), node))
return data
def _generate_table_from_SFDC_API_query(
self, result: dict, start: int = 0, limit: int = 0
) -> Table:
records = (
result["records"][start:]
if limit == 0
else result["records"][start : start + limit]
)
if len(records) == 0:
return Tables().create_table()
cols = [col for col, _ in self._get_values(records[0])]
table = Tables().create_table(columns=cols)
for row in records:
values = self._get_values(row)
table.append_row(row=dict(values))
return table
def salesforce_query(
self, sql_string: str, as_table: bool = False
) -> Union[dict, Table]:
"""Perform SQL query and return result as `dict` or `Table`.
:param sql_string: SQL clause to perform.
:param as_table: Set to `True` if the result should be of `RPA.Tables.Table`
type. (dictionary is returned by default)
:returns: Result of the SQL query.
"""
self._require_authentication()
result: dict = self.sf.query_all(sql_string)
if not as_table:
return result
return self._generate_table_from_SFDC_API_query(result)
def salesforce_query_result_as_table(self, sql_string: str) -> Table:
"""Shorthand for ``Salesforce Query ${sql_string} as_table=${True}``.
:param sql_string: SQL clause to perform.
:returns: Result of the SQL query as `RPA.Tables.Table`.
"""
return self.salesforce_query(sql_string, as_table=True)
def set_account(self, account_name: str = "", account_id: str = "") -> bool:
"""Set account name and id by giving either parameter.
Can be used together with keywords:
- get_opportunity_id
- create_new_opportunity
:param account_name: string, defaults to ""
:param account_id: string, defaults to ""
:return: True if account was found from Salesforce, else False
"""
result = self.salesforce_query(
f"SELECT Id, Name FROM Account WHERE Name = '{account_name}' "
f"or Id = '{account_id}'"
)
if result["totalSize"] == 1:
self.account["Id"] = result["records"][0]["Id"]
self.account["Name"] = result["records"][0]["Name"]
self.logger.debug("Found account: %s", self.account)
return True
else:
self.account = {"Name": None, "Id": None}
return False
def get_pricebook_entries(self) -> dict:
"""Get all pricebook entries.
:return: query result
"""
return self.salesforce_query("SELECT Id, Name FROM Pricebook2")
def get_opportunity_id(self, opportunity_name: str) -> Any:
"""Get ID of an Opportunity linked to set account.
:param opportunity_name: opportunity to query
:return: Id of the opportunity or False
"""
sql_query = (
f"SELECT Id, AccountId FROM Opportunity WHERE Name = '{opportunity_name}'"
)
if self.account["Id"] is not None:
sql_query += " AND AccountId = '%s'" % self.account["Id"]
result = self.salesforce_query(sql_query)
if result["totalSize"] == 1:
return result["records"][0]["Id"]
return False
def get_pricebook_id(self, pricebook_name: str) -> Any:
"""Get ID of a pricelist.
Returns False if unique Id is not found.
:param pricebook_name: pricelist to query
:return: Id of the pricelist or False
"""
result = self.salesforce_query(
f"SELECT Id FROM Pricebook2 WHERE Name = '{pricebook_name}'"
)
if result["totalSize"] == 1:
return result["records"][0]["Id"]
return False
def get_products_in_pricelist(self, pricebook_name: str) -> dict:
"""Get all products in a pricelist.
:param pricebook_name: pricelist to query
:return: products in dictionary
"""
result = self.salesforce_query(
f"SELECT PriceBook2.Name, Product2.Id, Product2.Name, UnitPrice, Name "
f"FROM PricebookEntry WHERE PriceBook2.Name = '{pricebook_name}'"
)
products = {}
for item in result["records"]:
product_name = item["Product2"]["Name"]
pricebook_entry_id = item["attributes"]["url"].split("/")[-1]
product_unitprice = item["UnitPrice"]
products[product_name] = {
"pricebook_entry_id": pricebook_entry_id,
"unit_price": product_unitprice,
}
return products
def set_pricebook(self, pricebook_name: str) -> None:
"""Sets Pricebook to be used in Salesforce operations.
:param pricebook_name: pricelist to use
"""
self.pricebook_name = pricebook_name
def add_product_into_opportunity(
self,
product_name: str,
quantity: int,
opportunity_id: str = None,
pricebook_name: str = None,
custom_total_price: float = None,
) -> bool:
"""Add Salesforce Product into Opportunity.
:param product_name: type of the product in the Pricelist
:param quantity: number of products to add
:param opportunity_id: identifier of Opportunity, default None
:param pricebook_name: name of the pricelist, default None
:param custom_total_price: price that overrides quantity and product price,
default None
:return: True is operation is successful or False
"""
self._require_authentication()
if opportunity_id is None:
return False
if pricebook_name:
products = self.get_products_in_pricelist(pricebook_name)
else:
products = self.get_products_in_pricelist(self.pricebook_name)
sfobject = SFType("OpportunityLineItem", self.session_id, self.instance)
if product_name in products.keys():
data_object = {
"OpportunityId": opportunity_id,
"PricebookEntryId": products[product_name]["pricebook_entry_id"],
"Quantity": int(quantity),
"TotalPrice": int(quantity) * products[product_name]["unit_price"],
}
if custom_total_price:
data_object["TotalPrice"] = float(custom_total_price)
result = sfobject.create(data_object)
if result and bool(result["success"]):
return True
return False
def create_new_opportunity(
self,
close_date: str,
opportunity_name: str,
stage_name: str = "Closed Won",
account_name: str = None,
) -> Any:
"""Create Salesforce Opportunity object.
:param close_date: closing date for the Opportunity, format 'YYYY-MM-DD'
:param opportunity_name: as string
:param stage_name: needs to be one of the defined stages,
defaults to "Closed Won"
:param account_name: by default uses previously set account, defaults to None
:return: created opportunity or False
"""
self._require_authentication()
# "2020-04-03"
if account_name:
self.set_account(account_name=account_name)
if self.account["Id"] is None:
return False
sfobject = SFType("Opportunity", self.session_id, self.instance)
result = sfobject.create(
{
"CloseDate": close_date,
"Name": opportunity_name,
"StageName": stage_name,
"Type": "Initial Subscription",
"AccountId": self.account["Id"],
}
)
self.logger.debug("create new opportunity: %s", result)
return result.get("id") or False
def read_dictionary_from_file(self, mapping_file: str) -> dict:
"""Read dictionary from file.
:param mapping_file: path to the file
:return: file content as dictionary
"""
mapping = None
with open(mapping_file, "r", encoding="utf-8") as mf:
mapping = json.loads(mf.read())
return mapping
def _get_input_iterable(self, input_object):
input_iterable = {}
if isinstance(input_object, dict):
input_iterable = input_object.items
elif isinstance(input_object, Table):
input_iterable = input_object.iter_dicts
elif isinstance(input_object, list):
input_table = Table(input_object)
input_iterable = input_table.iter_dicts
else:
input_dict = self.read_dictionary_from_file(input_object)
if isinstance(input_dict, list):
input_table = Table(input_dict)
input_iterable = input_table.iter_dicts
else:
input_iterable = input_dict
return input_iterable
def execute_dataloader_insert(
self, input_object: Any, mapping_object: Any, object_type: str
) -> bool:
"""Keyword mimics Salesforce Dataloader 'insert' behaviour by taking
in a `input_object`representing dictionary of data to input into Salesforce,
a `mapping_object` representing dictionary mapping the input keys into
Salesforce keys, an `object_type` representing Salesforce object which
Datahandler will handle with `operation` type.
Stores operation successes into `Salesforce.dataloader_success` array.
Stores operation errors into `Salesforce.dataloader_errors`.
These can be retrieved with keywords `get_dataloader_success_table` and
`get_dataloader_error_table` which return corresponding data as
`RPA.Table`.
:param input_object: filepath or list of dictionaries
:param mapping_object: filepath or dictionary
:param object_type: Salesforce object type
:return: True if operation is successful
"""
self._require_authentication()
if not isinstance(mapping_object, (dict, Table)):
mapping_dict = self.read_dictionary_from_file(mapping_object)
else:
mapping_dict = mapping_object
input_iterable = self._get_input_iterable(input_object)
sfobject = SFType(object_type, self.session_id, self.instance)
self.dataloader_success = []
self.dataloader_errors = []
for item in input_iterable():
data_object = {}
for key, value in mapping_dict[object_type].items():
data_object[value] = item[key]
result = sfobject.create(data_object)
if result["success"]:
data_status = {"result_id": result["id"]}
self.dataloader_success.append({**data_status, **item})
else:
data_status = {"message": "failed"}
self.dataloader_errors.append({**data_status, **item})
return True
def get_dataloader_success_table(self) -> Table:
"Return Dataloader success entries as `RPA.Table`"
return Table(self.dataloader_success)
def get_dataloader_error_table(self) -> Table:
"Return Dataloader error entries as `RPA.Table`"
return Table(self.dataloader_errors)
def get_salesforce_object_by_id(self, object_type: str, object_id: str) -> dict:
"""Get Salesforce object by id and type.
:param object_type: Salesforce object type
:param object_id: Salesforce object id
:return: dictionary of object attributes
"""
self._require_authentication()
sfobject = SFType(object_type, self.session_id, self.instance)
return sfobject.get(object_id)
def create_salesforce_object(self, object_type: str, object_data: Any) -> dict:
"""Create Salesforce object by type and data.
:param object_type: Salesforce object type
:param object_data: Salesforce object data
:raises SalesforceDataNotAnDictionary: when `object_data` is not dictionary
:return: resulting object as dictionary
"""
self._require_authentication()
if not isinstance(object_data, dict):
raise SalesforceDataNotAnDictionary(object_data)
salesforce_object = SFType(object_type, self.session_id, self.instance)
result = salesforce_object.create(object_data)
return dict(result)
def update_salesforce_object(
self, object_type: str, object_id: str, object_data: Any
) -> bool:
"""Update Salesfoce object by type, id and data.
:param object_type: Salesforce object type
:param object_id: Salesforce object id
:param object_data: Salesforce object data
:raises SalesforceDataNotAnDictionary: when `object_data` is not dictionary
:return: True if successful
"""
self._require_authentication()
if not isinstance(object_data, dict):
raise SalesforceDataNotAnDictionary(object_data)
salesforce_object = SFType(object_type, self.session_id, self.instance)
result_code = salesforce_object.update(object_id, object_data)
return result_code == 204
def upsert_salesforce_object(
self, object_type: str, object_id: str, object_data: Any
) -> bool:
"""Upsert Salesfoce object by type, id and data.
:param object_type: Salesforce object type
:param object_id: Salesforce object id
:param object_data: Salesforce object data
:raises SalesforceDataNotAnDictionary: when `object_data` is not dictionary
:return: True if successful
"""
self._require_authentication()
if not isinstance(object_data, dict):
raise SalesforceDataNotAnDictionary(object_data)
salesforce_object = SFType(object_type, self.session_id, self.instance)
result_code = salesforce_object.upsert(object_id, object_data)
return result_code == 204
def delete_salesforce_object(self, object_type: str, object_id: str) -> bool:
"""Delete Salesfoce object by type and id.
:param object_type: Salesforce object type
:param object_id: Salesforce object id
:return: True if successful
"""
self._require_authentication()
salesforce_object = SFType(object_type, self.session_id, self.instance)
result_code = salesforce_object.delete(object_id)
return result_code == 204
def get_salesforce_object_metadata(self, object_type: str) -> dict:
"""Get Salesfoce object metadata by type.
:param object_type: Salesforce object type
:return: object metadata as dictionary
"""
self._require_authentication()
salesforce_object = SFType(object_type, self.session_id, self.instance)
return dict(salesforce_object.metadata())
def describe_salesforce_object(self, object_type: str) -> dict:
"""Get Salesfoce object description by type.
:param object_type: Salesforce object type
:return: object description as dictionary
"""
self._require_authentication()
salesforce_object = SFType(object_type, self.session_id, self.instance)
return dict(salesforce_object.describe()) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Salesforce.py | 0.716417 | 0.425009 | Salesforce.py | pypi |
import logging
from notifiers import notify
class Notifier:
"""`Notifier` is a library interfacting with different notification providers.
**Supported providers**
- email
- gmail
- pushover
- slack
- telegram
- twilio
**Providers not supported yet via specific keywords**
- gitter
- join
- mailgun
- pagerduty
- popcornnotify
- pushbullet
- simplepush
- statuspage
- zulip
There is a keyword ``Generic Notify`` which can be used
to call above services, for example.
.. code-block:: robotframework
Generic Notify
provider_name=gitter
message=Hello from Robot
token=TOKEN
room_id=ID_OF_THE_GITTER_ROOM
Parameters for different providers can be read from the
**Notifiers** documents (link below).
Read more at https://notifiers.readthedocs.io/en/latest/
**About kwargs**
The `**kwargs` is a term for any extra named parameters, which
can be included in the same way as already named arguments,
e.g. ``Notify Email`` could be called with `subject=my email subject`
which will be passed through `**kwargs`.
Notifier documentation contains information about all possible
arguments that different providers support.
**Robot Framework**
.. code-block:: robotframework
&{account}= Create Dictionary
... host=smtp.office365.com
... username=ACCOUNT_USERNAME
... password=ACCOUNT_PASSWORD
Notify Email
... to=RECIPIENT_EMAIL
... from_=SENDER_ADDRESS # passed via kwargs
... subject=Hello from the Robot # passed via kwargs
... message=Hello from the Robot
... &{account} # passed via kwargs
.. code-block:: python
notifier = Notifier()
account = {
"host": "smtp.office365.com",
"username": "EMAIL_USERNAME",
"password": "EMAIL_PASSWORD"
}
notifier.email_notify(
to="RECIPIENT_EMAIL",
from_="SENDER_EMAIL",
subject="Hello from the Python Robot",
message="Hello from the Python RObot",
**account
)
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.Notifier
*** Variables ***
${SLACK_WEBHOOK} https://hooks.slack.com/services/WEBHOOKDETAILS
${CHANNEL} notification-channel
*** Tasks ***
Lets notify
Notify Slack message from robot channel=${CHANNEL} webhook_url=${SLACK_WEBHOOK}
**Python**
.. code-block:: python
from RPA.Notifier import Notifier
library = Notifier()
slack_attachments = [
{
"title": "attachment 1",
"fallback": "liverpool logo",
"image_url": "https://upload.wikimedia.org/wikipedia/fi/thumb/c/cd/Liverpool_FC-n_logo.svg/1200px-Liverpool_FC-n_logo.svg.png",
}
]
library.notify_slack(
message='message for the Slack',
channel="notification-channel",
webhook_url=slack_webhook_url,
attachments=slack_attachments,
)
""" # noqa: E501
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self):
self.logger = logging.getLogger(__name__)
def notify_pushover(
self, message: str = None, user: str = None, token: str = None, **kwargs
) -> bool:
"""Notify using Pushover provider
:param message: notification message
:param user: target user for the notification
:param token: service token
:param kwargs: see library documentation
:return: True if notification was successful, False if not
"""
arguments = {
"provider_name": "pushover",
"message": message,
"user": user,
"token": token,
}
notify_arguments = {**arguments, **kwargs}
response = notify(**notify_arguments)
return self._handle_response(response)
def notify_slack(
self,
message: str = None,
channel: str = None,
webhook_url: str = None,
**kwargs,
) -> bool:
"""Notify using Slack provider
:param message: notification message
:param channel: target channel for the notification
:param webhook_url: Slack webhook url
:param kwargs: see library documentation
:return: True if notification was successful, False if not
"""
arguments = {
"provider_name": "slack",
"message": message,
"webhook_url": webhook_url,
"channel": channel,
}
notify_arguments = {**arguments, **kwargs}
response = notify(**notify_arguments)
return self._handle_response(response)
def notify_telegram(
self,
message: str = None,
chat_id: str = None,
token: str = None,
**kwargs,
) -> bool:
"""Notify using Telegram provider
:param message: notification message
:param chat_id: target chat id for the notification
:param token: service token
:param kwargs: see library documentation
:return: True if notification was successful, False if not
"""
arguments = {
"provider_name": "telegram",
"message": message,
"chat_id": chat_id,
"token": token,
}
notify_arguments = {**arguments, **kwargs}
response = notify(**notify_arguments)
return self._handle_response(response)
def notify_gmail(
self,
message: str = None,
to: str = None,
username: str = None,
password: str = None,
**kwargs,
) -> bool:
"""Notify using Gmail provider
:param message: notification message
:param to: target of email message
:param username: GMail account username
:param password: GMail account password
:param kwargs: see library documentation
:return: True if notification was successful, False if not
"""
arguments = {
"provider_name": "gmail",
"message": message,
"to": to,
"username": username,
"password": password,
}
notify_arguments = {**arguments, **kwargs}
response = notify(**notify_arguments)
return self._handle_response(response)
def notify_email(
self,
message: str = None,
to: str = None,
username: str = None,
password: str = None,
host: str = None,
port: int = 587,
tls: bool = True,
**kwargs,
) -> bool:
"""Notify using email provider
:param message: notification message
:param to: target of email message
:param username: email account username
:param password: email account password
:param host: email SMTP host name
:param port: email SMTP host port number
:param tls: should TLS be used (default True)
:param kwargs: see library documentation
:return: True if notification was successful, False if not
Example.
.. code:: robotframework
# Notify with Outlook account
Notify Email
... message=Message from the Robot
... to=RECIPIENT_EMAIL_ADDRESS
... username=OUTLOOK_USERNAME
... password=OUTLOOK_PASSWORD
... host=smtp.office365.com
... subject=Subject of the Message
"""
arguments = {
"provider_name": "email",
"message": message,
"to": to,
"username": username,
"password": password,
"host": host,
"port": port,
"tls": tls,
}
notify_arguments = {**arguments, **kwargs}
response = notify(**notify_arguments)
return self._handle_response(response)
def notify_twilio(
self,
message: str = None,
number_from: str = None,
number_to: str = None,
account_sid: str = None,
token: str = None,
**kwargs,
) -> bool:
"""Notify using Twilio provider
:param message: notification message
:param number_from: number where the message comes from
:param number_to: number where the messages goes to
:param account_sid: Twilio account SID
:param token: Twilio account token
:param kwargs: see library documentation
:return: True if notification was successful, False if not
"""
arguments = {
"provider_name": "twilio",
"message": message,
"from_": number_from,
"to": number_to,
"account_sid": account_sid,
"auth_token": token,
}
notify_arguments = {**arguments, **kwargs}
response = notify(**notify_arguments)
return self._handle_response(response)
def generic_notify(self, provider_name: str, **kwargs):
"""Generic keyword to use with any notifier provider.
:param provider_name: name of the notifier service
:param kwargs: see library documentation
:return: True if notification was successful, False if not
"""
notify_arguments = {"provider_name": provider_name, **kwargs}
response = notify(**notify_arguments)
return self._handle_response(response)
def _handle_response(self, response) -> bool:
if response.status == "Success":
self.logger.info("Notify %s resulted in Success", response.provider)
return True
else:
self.logger.error("Notify errors: %s", response.errors)
return False | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Notifier.py | 0.80213 | 0.31563 | Notifier.py | pypi |
from dataclasses import dataclass
import datetime
import logging
from robot.libraries.BuiltIn import (
BuiltIn,
RobotNotRunningError,
)
import tweepy
from tweepy.error import TweepError
from RPA.core.helpers import required_env, required_param
from RPA.core.notebook import notebook_json
from RPA.RobotLogListener import RobotLogListener
try:
BuiltIn().import_library("RPA.RobotLogListener")
except RobotNotRunningError:
pass
@dataclass
class Tweet:
"""Represents Tweet"""
created_at: datetime.datetime
id: int
tweet_id_str: str
text: str
in_reply_to_screen_name: str
lang: str
name: str
screen_name: str
hashtags: list
is_truncated: bool = False
favorite_count: int = 0
retweeted: bool = False
retweet_count: int = 0
class Twitter:
"""`Twitter` is a library for accessing Twitter using developer API.
The library extends `tweepy`_ library.
Authorization credentials can be given as parameters for ``authorize`` keyword
or keyword can read them in as environment variables:
- `TWITTER_CONSUMER_KEY`
- `TWITTER_CONSUMER_SECRET`
- `TWITTER_ACCESS_TOKEN`
- `TWITTER_ACCESS_TOKEN_SECRET`
Library usage requires Twitter developer credentials.
Those can be requested from `Twitter developer site`_
.. _tweepy:
http://docs.tweepy.org/en/latest/index.html
.. _Twitter developer site:
https://developer.twitter.com/
**Examples**
.. code-block:: robotframework
*** Settings ***
Library RPA.Twitter
*** Tasks ***
Get user tweets and like them
[Setup] Authorize
@{tweets}= Get User Tweets username=niinisto count=5
FOR ${tweet} IN @{tweets}
Like ${tweet}
END
.. code-block:: python
from RPA.Twitter import Twitter
library = Twitter()
library.authorize()
tweets = library.get_user_tweets(username="niinisto", count=5)
for tw in tweets:
library.like(tw)
tweets = library.text_search_tweets(query="corona trump")
for tw in tweets:
print(tw.text)
user = library.get_user_profile("niinisto")
library.follow(user)
library.tweet("first tweet")
me = library.get_me()
print(me)
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self) -> None:
self.logger = logging.getLogger(__name__)
self._auth = None
self.api = None
self._me = None
listener = RobotLogListener()
listener.register_protected_keywords("authorize")
listener.only_info_level(
[
"get_me",
"get_user_tweets",
"text_search_tweets",
"get_user_profile",
"tweet",
"like",
"unlike",
]
)
def authorize(
self,
consumer_key: str = None,
consumer_secret: str = None,
access_token: str = None,
access_token_secret: str = None,
) -> None:
"""Authorize to Twitter API
:param consumer_key: app consumer key
:param consumer_secret: app consumer secret
:param access_token: user access token
:param access_token_secret: user access token secret
"""
if consumer_key is None:
consumer_key = required_env("TWITTER_CONSUMER_KEY")
if consumer_secret is None:
consumer_secret = required_env("TWITTER_CONSUMER_SECRET")
if access_token is None:
access_token = required_env("TWITTER_ACCESS_TOKEN")
if access_token_secret is None:
access_token_secret = required_env("TWITTER_ACCESS_TOKEN_SECRET")
self._auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
self._auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(self._auth, wait_on_rate_limit=True)
try:
self.api.verify_credentials()
self.logger.info("Twitter authentication success")
self._me = self.api.me()
except TweepError as e:
self.logger.error("Error during Twitter authentication: %s", str(e))
raise TweepError from e
def get_me(self) -> dict:
"""Get Twitter profile of authenticated user
:return: user profile as dictionary or `None`
"""
data = self._me._json if self._me else None # pylint: disable=W0212
notebook_json(data)
return data
def get_user_tweets(self, username: str = None, count: int = 100) -> list:
"""Get user tweets
:param username: whose tweets to get
:param count: maximum number of tweets, defaults to 100
:return: list of user tweets
"""
required_param(username, "get_user_tweets")
tweets = []
try:
# Pulling individual tweets from query
for tweet in self.api.user_timeline(id=username, count=count):
# Adding to list that contains all tweets
tw = Tweet(
created_at=tweet.created_at,
id=tweet.id,
tweet_id_str=tweet.id_str,
text=tweet.text,
in_reply_to_screen_name=tweet.in_reply_to_screen_name,
lang=tweet.lang,
name=tweet.user.name,
screen_name=tweet.user.screen_name,
hashtags=[ht["text"] for ht in tweet.entities["hashtags"]],
is_truncated=tweet.truncated,
favorite_count=tweet.favorite_count,
retweeted=tweet.retweeted,
retweet_count=tweet.retweet_count,
)
tweets.append(tw)
except TweepError as e:
self.logger.warning("Twitter timeline failed: %s", str(e))
return tweets
def text_search_tweets(
self,
query: str = None,
count: int = 100,
geocode: str = None,
lang: str = None,
locale: str = None,
result_type: str = "mixed",
until: str = None,
since_id: str = None,
max_id: str = None,
) -> list:
"""Search tweets defined by search query
Results types:
- mixed : include both popular and real time results in the response
- recent : return only the most recent results in the response
- popular : return only the most popular results in the response
:param query: search query string of 500 characters maximum,
including operators
:param count: maximum number of tweets, defaults to 100
:param geocode: tweets by users located within a given
radius of the given latitude/longitude
:param lang: language code of tweets
:param locale: language of the query you are sending
:param result_type: type of search results you would prefer to receive,
default "mixed"
:param until: tweets created before the given date
:param since_id: Returns only statuses with an ID greater than
:param max_id: only statuses with an ID less than
:return: list of matching tweets
"""
required_param(query, "text_search_tweets")
tweets = []
try:
# Pulling individual tweets from query
for tweet in self.api.search(
q=query,
count=count,
geocode=geocode,
lang=lang,
locale=locale,
result_type=result_type,
until=until,
since_id=since_id,
max_id=max_id,
):
tw = Tweet(
created_at=tweet.created_at,
id=tweet.id,
tweet_id_str=tweet.id_str,
text=tweet.text,
in_reply_to_screen_name=tweet.in_reply_to_screen_name,
lang=tweet.lang,
name=tweet.user.name,
screen_name=tweet.user.screen_name,
hashtags=[ht["text"] for ht in tweet.entities["hashtags"]],
is_truncated=tweet.truncated,
favorite_count=tweet.favorite_count,
retweeted=tweet.retweeted,
retweet_count=tweet.retweet_count,
)
tweets.append(tw)
except TweepError as e:
self.logger.warning("Twitter search failed: %s", str(e))
return tweets
def get_user_profile(self, username: str = None) -> dict:
"""Get user's Twitter profile
:param username: whose profile to get
:return: profile as dictionary
"""
required_param(username, "get_user_profile")
try:
profile = self.api.get_user(username)
data = profile._json # pylint: disable=W0212
notebook_json(data)
return data
except TweepError:
return None
def tweet(self, content: str = None) -> None:
"""Make a tweet with content
:param content: text for the status update
"""
required_param(content, "tweet")
self.api.update_status(content)
def like(self, tweet: Tweet = None) -> bool:
"""Like a tweet
:param tweet: as a class `Tweet`
:return: `True` if Tweet was liked, `False` if not
"""
required_param(tweet, "like")
try:
self.api.create_favorite(tweet.id)
return True
except TweepError:
self.logger.warning(
'Could not like tweet "%s" by user "%s"',
tweet.text,
tweet.screen_name,
)
return False
def unlike(self, tweet: Tweet = None) -> bool:
"""Unlike a tweet
:param tweet: as a class `Tweet`
:return: `True` if Tweet was unliked, `False` if not
"""
required_param(tweet, "unlike")
try:
self.api.destroy_favorite(tweet.id)
return True
except TweepError:
self.logger.warning(
'Could not unlike tweet "%s" by user "%s"',
tweet.text,
tweet.screen_name,
)
return False
def follow(self, user: str = None) -> bool:
"""Follow Twitter user
:param user: screen name of the user
:return: `True` if user was followed, `False` if not
"""
required_param(user, "follow")
try:
self.api.create_friendship(user)
return True
except TweepError:
self.logger.warning("Could not follow user: %s", user)
return False
def unfollow(self, user: str = None) -> bool:
"""Unfollow Twitter user
:param user: screen name of the user
:return: `True` if user was followed, `False` if not
"""
required_param(user, "unfollow")
try:
self.api.destroy_friendship(user)
return True
except TweepError:
self.logger.warning("Could not unfollow user: %s", user)
return False | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Twitter.py | 0.73173 | 0.197251 | Twitter.py | pypi |
from datetime import datetime
from fnmatch import fnmatch
import logging
import os
import os.path
from pathlib import Path
import tarfile
from typing import Union, List
import zipfile
def convert_date(timestamp):
if isinstance(timestamp, tuple):
d = datetime(
year=timestamp[0],
month=timestamp[1],
day=timestamp[2],
hour=timestamp[3],
minute=timestamp[4],
second=timestamp[5],
)
else:
d = datetime.utcfromtimestamp(timestamp)
formatted_date = d.strftime("%d.%m.%Y %H:%M:%S")
return formatted_date
def list_files_in_directory(folder, recursive=False, include=None, exclude=None):
filelist = []
for rootdir, _, files in os.walk(folder):
for file in files:
archive_absolute = os.path.join(rootdir, file)
archive_relative = rootdir.replace(folder, "")
archive_relative = os.path.join(archive_relative, file)
if include and not fnmatch(archive_relative, include):
continue
if exclude and fnmatch(archive_relative, exclude):
continue
filelist.append((archive_absolute, archive_relative))
if not recursive:
break
return filelist
class Archive:
"""`Archive` is a library for operating with ZIP and TAR packages.
**Examples**
.. code-block:: robotframework
*** Settings ***
Library RPA.Archive
*** Tasks ***
Creating a ZIP archive
Archive Folder With ZIP ${CURDIR}${/}tasks tasks.zip recursive=True include=*.robot exclude=/.*
@{files} List Archive tasks.zip
FOR ${file} IN ${files}
Log ${file}
END
Add To Archive .${/}..${/}missing.robot tasks.zip
&{info} Get Archive Info
.. code-block:: python
from RPA.Archive import Archive
lib = Archive()
lib.archive_folder_with_tar('./tasks', 'tasks.tar', recursive=True)
files = lib.list_archive('tasks.tar')
for file in files:
print(file)
""" # noqa: E501
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self):
self.logger = logging.getLogger(__name__)
def archive_folder_with_zip(
self,
folder: str,
archive_name: str,
recursive: bool = False,
include: str = None,
exclude: str = None,
compression: str = "stored",
) -> None:
# pylint: disable=C0301
"""Create a zip archive of a folder
:param folder: name of the folder to archive
:param archive_name: filename of the archive
:param recursive: should sub directories be included, default is False
:param include: define file pattern to include in the package, default is None which means all files are included
:param exclude: define file pattern to exclude from the package, default is None
:param compression: type of package compression method, default is "stored"
:return: None
This keyword creates an ZIP archive of a local folder. By default subdirectories are not
included, but they can be included using the `recursive` argument.
To include only certain files, like TXT files, the argument `include` can be used.
Similarly to exclude certain files, like dotfiles, the argument `exclude` can be used.
Compression methods:
- stored, default
- deflated
- bzip2
- lzma
Example:
.. code-block:: robotframework
Archive Folder With Zip ${CURDIR}${/}documents mydocs.zip
Archive Folder With Zip ${CURDIR}${/}tasks robottasks.zip include=*.robot
Archive Folder With Zip ${CURDIR}${/}tasks no_dotfiles.zip exclude=/.*
Archive Folder With Zip ${CURDIR}${/}documents documents.zip recursive=True
Archive Folder With Zip ${CURDIR} packagelzma.zip compression=lzma
Archive Folder With Zip ${CURDIR} bzipped.zip compression=bzip2
.. code-block:: python
from RPA.Archive import Archive
lib = Archive()
lib.archive_folder_with_zip('./documents', 'mydocs.zip')
lib.archive_folder_with_zip('./tasks', 'robottasks.zip', include='*.robot')
lib.archive_folder_with_zip('./tasks', 'no_dotfiles.zip', exclude='/.*')
lib.archive_folder_with_zip('./documents', 'documents.zip', recursive=True)
lib.archive_folder_with_zip('./', 'packagelzma.zip', compression='lzma')
lib.archive_folder_with_zip('./', 'bzipped.zip', compression='bzip2')
""" # noqa: E501
if compression == "stored":
comp_method = zipfile.ZIP_STORED
elif compression == "deflated":
comp_method = zipfile.ZIP_DEFLATED
elif compression == "bzip2":
comp_method = zipfile.ZIP_BZIP2
elif compression == "lzma":
comp_method = zipfile.ZIP_LZMA
else:
raise ValueError("Unknown compression method")
filelist = list_files_in_directory(folder, recursive, include, exclude)
if len(filelist) == 0:
raise ValueError("No files found to archive")
with zipfile.ZipFile(
file=archive_name,
mode="w",
compression=comp_method,
) as archive:
for archive_absolute, archive_relative in filelist:
archive.write(archive_absolute, arcname=archive_relative)
def archive_folder_with_tar(
self,
folder: str,
archive_name: str,
recursive: bool = False,
include: str = None,
exclude: str = None,
) -> None:
"""Create a tar/tar.gz archive of a folder
:param folder: name of the folder to archive
:param archive_name: filename of the archive
:param recursive: should sub directories be included, default is False
:param include: define file pattern to include in the package, default is None which means all files are included
:param exclude: define file pattern to exclude from the package, default is None
:return: None
This keyword creates an TAR or TAR.GZ archive of a local folder. Type of archive
is determined by the file extension. By default subdirectories are not
included, but they can included using `recursive` argument.
To include only certain files, like TXT files, the argument `include` can be used.
Similarly to exclude certain file, like dotfiles, the argument `exclude` can be used.
Example:
.. code-block:: robotframework
Archive Folder With TAR ${CURDIR}${/}documents documents.tar
Archive Folder With TAR ${CURDIR}${/}tasks tasks.tar.gz include=*.robot
Archive Folder With TAR ${CURDIR}${/}tasks tasks.tar exclude=/.*
Archive Folder With TAR ${CURDIR}${/}documents documents.tar recursive=True
""" # noqa: E501
filelist = list_files_in_directory(folder, recursive, include, exclude)
if len(filelist) == 0:
raise ValueError("No files found to archive")
with tarfile.TarFile(archive_name, "w") as archive:
for archive_absolute, archive_relative in filelist:
archive.add(archive_absolute, arcname=archive_relative)
def add_to_archive(
self,
files: Union[List, str],
archive_name: str,
folder: str = None,
) -> None:
"""Add file(s) to the archive
:param files: name of the file, or list of files, to add
:param archive_name: filename of the archive
:param folder: name of the folder where the file will be added, relative path within the archive
:return: None
This keyword adds a file or list of files into an existing archive. Files
can be added to archive structure with relative path using argument `folder`.
Example:
.. code-block:: robotframework
Add To Archive extrafile.txt myfiles.zip
Add To Archive stat.png archive.tar.gz images
@{files} Create List filename1.txt filename2.txt
Add To Archive ${files} files.tar
""" # noqa: E501
files_to_add = []
if isinstance(files, list):
for filename in files:
file_relative = Path(filename).name
if folder:
file_relative = folder + os.path.sep + file_relative
files_to_add.append((filename, file_relative))
else:
file_relative = Path(files).name
if folder:
file_relative = folder + os.path.sep + file_relative
files_to_add.append((files, file_relative))
if zipfile.is_zipfile(archive_name):
with zipfile.ZipFile(archive_name, "a") as zip_archive:
for filename, file_relative in files_to_add:
zip_archive.write(filename, arcname=file_relative)
elif tarfile.is_tarfile(archive_name):
with tarfile.TarFile(archive_name, "a") as tar_archive:
for file_absolute, file_relative in files_to_add:
tar_archive.add(file_absolute, arcname=file_relative)
def list_archive(self, archive_name: str) -> list:
"""List files in an archive
:param archive_name: filename of the archive
:return: dictionary variable containing the keys name, size, mtime, modified
Returns list of files, where each file in a list is a dictionary
with following attributes:
- name
- size
- mtime
- last modification time in format `%d.%m.%Y %H:%M:%S`
Example:
.. code-block:: robotframework
@{files} List Archive myfiles.zip
FOR ${file} IN ${files}
Log ${file}[filename]
Log ${file}[size]
Log ${file}[mtime]
END
"""
filelist = []
if zipfile.is_zipfile(archive_name):
with zipfile.ZipFile(archive_name, "r") as f:
members = f.infolist()
for memb in members:
filelist.append(
{
"filename": memb.filename,
"size": memb.file_size,
"mtime": memb.date_time,
"modified": convert_date(memb.date_time),
}
)
elif tarfile.is_tarfile(archive_name):
with tarfile.TarFile(archive_name, "r") as f:
members = f.getmembers()
for memb in members:
filelist.append(
{
"name": memb.name,
"size": memb.size,
"mtime": memb.mtime,
"modified": convert_date(memb.mtime),
}
)
return filelist
def get_archive_info(self, archive_name: str) -> dict:
"""Get information about the archive
:param archive_name: filename of the archive
:return: dictionary variable containing the keys filename, filemode, size, mtime, modified
Returns following file attributes in a dictionary:
- filename
- filemode
- size
- mtime
- last modification time in format `%d.%m.%Y %H:%M:%S`
Example:
.. code-block:: robotframework
&{archiveinfo} Get Archive Info myfiles.zip
""" # noqa: E501
archive_info = None
st = os.stat(archive_name)
if zipfile.is_zipfile(archive_name):
with zipfile.ZipFile(archive_name, "r") as f:
archive_info = {
"filename": f.filename,
"mode": f.mode,
"size": st.st_size,
"mtime": st.st_mtime,
"modified": convert_date(st.st_mtime),
}
elif tarfile.is_tarfile(archive_name):
with tarfile.TarFile(archive_name, "r") as f:
archive_info = {
"filename": f.name,
"mode": f.mode,
"size": st.st_size,
"mtime": st.st_mtime,
"modified": convert_date(st.st_mtime),
}
return archive_info
def extract_archive(
self, archive_name: str, path: str = None, members: Union[List, str] = None
) -> None:
"""Extract files from archive into local directory
:param archive_name: filename of the archive
:param path: filepath to extract file into, default is current working directory
:param members: list of files to extract from archive, by default
all files in archive are extracted
:return: None
This keyword supports extracting files from zip, tar and tar.gz archives.
By default file is extracted into current working directory, but `path` argument
can be set to define extraction path.
Example:
.. code-block:: robotframework
Extract Archive myfiles.zip ${CURDIR}${/}extracted
@{files} Create List filename1.txt filename2.txt
Extract Archive archive.tar C:${/}myfiles${/} ${files}
""" # noqa: E501
root = Path(path) if path else Path.cwd()
if members and not isinstance(members, list):
members = [members]
if zipfile.is_zipfile(archive_name):
with zipfile.ZipFile(archive_name, "r") as f:
if members:
f.extractall(path=root, members=members)
else:
f.extractall(path=root)
elif tarfile.is_tarfile(archive_name):
members = map(tarfile.TarInfo, members) if members else None
with tarfile.open(archive_name, "r") as f:
if members:
f.extractall(path=root, members=members)
else:
f.extractall(path=root)
def extract_file_from_archive(
self, filename: str, archive_name: str, path: str = None
) -> None: # pylint: disable=C0301
"""Extract a file from archive into local directory
:param filename: name of the file to extract
:param archive_name: filename of the archive
:param path: filepath to extract file into,
default is current working directory
:return: None
This keyword supports extracting a file from zip, tar and tar.gz archives.
By default file is extracted into current working directory,
but `path` argument can be set to define extraction path.
Example:
.. code-block:: robotframework
Extract File From Archive extrafile.txt myfiles.zip
Extract File From Archive background.png images.tar.gz ${CURDIR}${/}extracted
""" # noqa: E501
root = Path(path) if path else Path.cwd()
if zipfile.is_zipfile(archive_name):
with zipfile.ZipFile(archive_name, "r") as outfile:
outfile.extract(filename, root)
elif tarfile.is_tarfile(archive_name):
with tarfile.open(archive_name, "r") as outfile:
outfile.extract(filename, root) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Archive.py | 0.629091 | 0.185726 | Archive.py | pypi |
import base64
from enum import Enum, auto
from pathlib import Path
from typing import Optional, Union
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
from RPA.RobotLogListener import RobotLogListener
from RPA.Robocorp.Vault import Vault
try:
BuiltIn().import_library("RPA.RobotLogListener")
except RobotNotRunningError:
pass
class Hash(Enum):
"""Supported hashing algorithms."""
MD5 = auto()
SHA1 = auto()
SHA224 = auto()
SHA256 = auto()
SHA384 = auto()
SHA3_224 = auto()
SHA3_256 = auto()
SHA3_384 = auto()
SHA3_512 = auto()
SHA512 = auto()
SHA512_224 = auto()
SHA512_256 = auto()
def to_hash_context(element: Hash) -> hashes.HashContext:
"""Convert hash enum value to hash context instance."""
method = getattr(hashes, str(element.name))
return hashes.Hash(method(), backend=default_backend())
class Crypto:
"""Library for common encryption and hashing operations.
It uses the `Fernet <https://github.com/fernet/spec/blob/master/Spec.md>`_
format for encryption. More specifically, it uses AES in
CBC mode with a 128-bit key for encryption and HMAC with SHA256 for
authentication.
To use the encryption features, generate a key with the command line
utility ``rpa-crypto`` or with the keyword ``Generate Key``. Store
the key in a secure place, such as Robocorp Vault, and load it within
the execution before calling encryption/decryption keywords.
**Example usage with Robocorp Vault**
Create an encryption key with the CLI utility:
.. code-block:: console
> rpa-crypto key
rGx1edA07yz7uD08ChiPSunn8vaauRxw0pAbsal9zjM=
Store the key in Robocorp Vault, in this case with the name ``EncryptionKey``.
Load the key from the vault before encryption operations:
.. code-block:: robotframework
Use encryption key from vault EncryptionKey
${encrypted}= Encrypt file orders.xlsx
Add work item file ${encrypted} name=Orders
In another task, this same key can be used to decrypt the file:
.. code-block:: robotframework
Use encryption key from vault EncryptionKey
${encrypted}= Get work item file Orders
${orders}= Decrypt file ${encrypted}
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self):
self._vault = Vault()
self._key = None
listener = RobotLogListener()
listener.register_protected_keywords(
["RPA.Crypto.generate_key", "RPA.Crypto.use_encryption_key"]
)
def generate_key(self) -> str:
"""Generate a Fernet encryption key as base64 string.
:return: Generated key as a string
This key can be used for encryption/decryption operations
with this library.
*NOTE:* Store the generated key in a secure place!
If the key is lost, the encrypted data can not be recovered.
If anyone else gains access to it, they can decrypt your data.
"""
return Fernet.generate_key().decode("utf-8")
def use_encryption_key(self, key: str) -> None:
"""Set key for all following encryption/decryption operations.
:param key: Encryption key as base64 string
Assumes the given key has been generated previously using
either the keyword ``Generate Key`` or with the matching command
line utility.
Example:
.. code-block:: robotframework
${key}= Read file encryption.key
Use encryption key ${key}
"""
self._key = Fernet(key)
def use_encryption_key_from_vault(
self, name: str, key: Optional[str] = None
) -> None:
"""Load an encryption key from Robocorp Vault.
:param name: Name of secret in Vault
:param key: Name of encryption key in secret
If the secret only has one value, the key argument is optional.
Example:
.. code-block:: robotframework
# Secret with one value
Use encryption key from vault Encryption
# Secret with multiple values
Use encryption key from vault name=Encryption key=CryptoKey
"""
secret = self._vault.get_secret(name)
if key:
value = secret[key]
elif len(secret) == 1:
value = list(secret.values())[0]
elif len(secret) == 0:
raise ValueError(f"Secret '{name}' has no values")
else:
options = ", ".join(str(k) for k in secret.keys())
raise ValueError(f"Secret '{name}' has multiple values: {options}")
self.use_encryption_key(value)
def hash_string(self, text: str, method: Hash = Hash.SHA1, encoding="utf-8") -> str:
"""Calculate a hash from a string, in base64 format.
:param text: String to hash
:param method: Used hashing method
:param encoding: Used text encoding
:return: Hash digest of the string
Example:
.. code-block:: robotframework
${digest}= Hash string A value that will be hashed
Should be equal ${digest} uSlyRHlbu8NzY29YMZhDUpdErP4=
"""
if isinstance(text, str):
text = text.encode(encoding)
context = to_hash_context(method)
context.update(text)
digest = context.finalize()
return base64.b64encode(digest).decode("utf-8")
def hash_file(self, path: str, method: Hash = Hash.SHA1) -> str:
"""Calculate a hash from a file, in base64 format.
:param path: Path to file
:param method: The used hashing method
:return: Hash digest of the file
Example:
.. code-block:: robotframework
${digest}= Hash file orders.xlsx method=MD5
Should not be equal ${digest} uSlyRHlbu8NzY29YMZhDUpdErP4=
"""
context = to_hash_context(method)
with open(path, "rb") as infile:
while True:
chunk = infile.read(65536)
if not chunk:
break
context.update(chunk)
digest = context.finalize()
return base64.b64encode(digest).decode("utf-8")
def encrypt_string(self, text: Union[bytes, str], encoding: str = "utf-8") -> bytes:
"""Encrypt a string.
:param text: Source text to encrypt
:param encoding: Used text encoding
:return: Token of the encrypted string in bytes
Example:
.. code-block:: robotframework
Use encryption key ${key}
${token}= Encrypt string This is a secret, don't share it
"""
if not self._key:
raise ValueError("No encryption key set")
if isinstance(text, str):
text = text.encode(encoding)
token = self._key.encrypt(text)
return token
def decrypt_string(
self, data: Union[bytes, str], encoding: str = "utf-8"
) -> Union[str, bytes]:
"""Decrypt a string.
:param data: Encrypted data as base64 string
:param encoding: Original encoding of string
:return: Decrypted string or raw bytes, if None given as encoding
Returns the decrypted string that is parsed with the given encoding,
or if the encoding is ``None`` the raw bytes are returned.
Example:
.. code-block:: robotframework
Use encryption key ${key}
${text}= Decrypt string ${token}
Log Secret string is: ${text}
"""
if not self._key:
raise ValueError("No encryption key set")
if isinstance(data, str):
data = data.encode("utf-8")
try:
text = self._key.decrypt(data)
except InvalidToken as err:
raise ValueError(
"Failed to decrypt string (malformed content or invalid signature)"
) from err
if encoding is not None:
text = text.decode(encoding)
return text
def encrypt_file(self, path: str, output: Optional[str] = None) -> str:
"""Encrypt a file.
:param path: Path to source input file
:param output: Path to encrypted output file
:return: Path to the encrypted file
If no output path is given, it will generate one from the input path.
The resulting output path is returned.
Example:
.. code-block:: robotframework
Use encryption key ${key}
${path}= Encrypt file orders.xlsx
Log Path to encrypted file is: ${path}
"""
path = Path(path)
if not self._key:
raise ValueError("No encryption key set")
if output:
output = Path(output)
else:
output = path.parent / (path.name + ".enc")
with open(path, "rb") as infile:
data = infile.read()
token = self._key.encrypt(data)
with open(output, "wb") as outfile:
outfile.write(token)
return str(output)
def decrypt_file(self, path: str, output: Optional[str] = None) -> str:
"""Decrypt a file.
:param path: Path to encrypted input file
:param output: Path to decrypted output file
:return: Path to the decrypted file
If no output path is given, it will generate one from the input path.
The resulting output path is returned.
Example:
.. code-block:: robotframework
Use encryption key ${key}
${path}= Decrypt file orders.xlsx.enc
Log Path to decrypted file is: ${path}
"""
path = Path(path)
if not self._key:
raise ValueError("No encryption key set")
if output:
output = Path(output)
elif path.name.endswith(".enc"):
output = path.parent / path.name[: -len(".enc")]
else:
parts = (path.stem, "dec", path.suffix[1:])
output = path.parent / ".".join(part for part in parts if part.strip())
try:
with open(path, "rb") as infile:
token = infile.read()
data = self._key.decrypt(token)
except InvalidToken as err:
raise ValueError(
"Failed to decrypt file (malformed content or invalid signature)"
) from err
with open(output, "wb") as outfile:
outfile.write(data)
return str(output) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Crypto.py | 0.929244 | 0.293863 | Crypto.py | pypi |
from datetime import date as datetime_date
import logging
from typing import Union, List, Dict, Optional
import pendulum as pdl
from pendulum.parsing.exceptions import ParserError
from pendulum.datetime import DateTime as PendulumDateTime
from robot.api.deco import keyword, library
import holidays
parsing_error_message = """Could not parse date '%s'.
You can use `Create Time` keyword to construct valid
calendar object by giving date and time as string in corresponding
date format. See https://pendulum.eustace.io/docs/#tokens for
valid tokens for the date format.
"""
DTFormat = Union[str, datetime_date, PendulumDateTime]
@library(scope="GLOBAL", doc_format="REST")
class Calendar:
"""Library for handling different operations for date and time
handling especially in business days and holiday contexts.
Utilizing `pendulum <https://pypi.org/project/pendulum/>`_ and
`holidays <https://pypi.org/project/holidays/>`_ packages.
Library is by default using days from Monday to Friday as business
days, but that can be changed by giving list of weekdays to
``Set Business Days`` keyword. A weekday is given as a integer, the
0 for Sunday and 6 for Saturday.
Common country holidays are respected when getting next and previous
business days, but custom holidays can be added into consideration
using keyword ``Add Custom Holidays`` keyword.
Some dates containing for example month names are in English (en), but
the locale of the library can be changed with keyword ``Set Locale`` or
for specific keyword if that has a ``locale`` parameter.
"""
def __init__(self) -> None:
self.logger = logging.getLogger(__name__)
self.BUSINESS_DAYS = [1, 2, 3, 4, 5] # Monday - Friday
self.custom_holidays = holidays.HolidayBase()
@keyword
def set_locale(self, locale_name: str) -> str:
"""Set locale globally for the library
:param locale_name: name of the locale
:return: name of the previous locale
Python example.
.. code-block:: python
library = Calendar()
library.set_locale("es")
now = library.time_now(return_format="dddd DD MMMM YYYY")
# now == "jueves 09 marzo 2023"
library.set_locale("en")
now = library.time_now(return_format="dddd DD MMMM YYYY")
# now == "Thursday 09 March 2023"
Robot Framework example.
.. code-block:: robotframework
Set Locale es
${now}= Time Now return_format=dddd DD MMMM YYYY
# ${now} == "jueves 09 marzo 2023"
Set Locale en
${now}= Time Now return_format=dddd DD MMMM YYYY
# ${now} == "Thursday 09 March 2023"
"""
previous = pdl.get_locale()
pdl.set_locale(locale_name)
return previous
@keyword
def reset_custom_holidays(self) -> None:
"""Reset custom holiday list into empty list."""
self.custom_holidays = holidays.HolidayBase()
@keyword
def add_custom_holidays(self, days: Union[DTFormat, List[DTFormat]]) -> List:
"""Add a day or list of days which are considered as holidays
in addition to country specific holidays when calculating
:param days: string or list of dates to consider as holidays
:return: list of current custom holidays
Python example.
.. code-block:: python
library = Calendar()
custom_holidays = library.add_custom_holidays("2023-03-08")
# custom_holidays == ["2023-03-08"]
custom_holidays = library.add_custom_holidays([
"2023-03-09", "2023-03-10"
])
# custom_holidays == ["2023-03-08", "2023-03-09", "2023-03-10"]
Robot Framework example.
.. code-block:: robotframework
@{custom_holidays}= Add Custom Holidays 2023-03-08
# ${custom_holidays} == ["2023-03-08"]
@{more_holidays}= Create List 2023-03-09 2023-03-10
@{custom_holidays}= Add Custom Holidays ${more_holidays}
# ${custom_holidays} == ["2023-03-08", "2023-03-09", "2023-03-10"]
"""
if isinstance(days, str):
self.custom_holidays.append(days.split(","))
else:
self.custom_holidays.append(days)
return self.custom_holidays
@keyword
def set_business_days(self, days: List[int]) -> List:
"""Set weekdays which are considered as business days
for calculating previous and next business day.
:param days: list of integers denoting weekdays
:return: previous list of weekdays
Python example.
.. code-block:: python
# set 4 day work week
previous = Calendar().set_business_days([1,2,3,4])
# previous == [1,2,3,4,5]
Robot Framework example.
.. code-block:: robotframework
@{4days}= Create List 1 2 3 4
@{previous}= Set Business Days ${days}
# ${previous} == [1,2,3,4,5]
"""
previous = self.BUSINESS_DAYS
self.BUSINESS_DAYS = days
return previous
@keyword
def time_difference(
self,
start_date: Union[DTFormat, str],
end_date: Union[DTFormat, str],
start_timezone: Optional[str] = None,
end_timezone: Optional[str] = None,
) -> Dict:
"""Compare 2 dates and get the time difference.
Returned dictionary contains following properties:
- end_date_is_later, `True` if end_date is more recent
than start_date, otherwise `False`
- years, time difference in years
- months, time difference in months
- days, time difference in days
- hours, time difference in hours (in addition to the days)
- minutes, time difference in minutes (in addition to the hours)
- seconds, time difference in seconds (in addition to the minutes)
:param start_date: starting date for the comparison
:param end_date: ending date for the comparison
:param start_timezone: timezone for the starting date, defaults to None
:param end_timezone: timezone for the ending date, defaults to None
:return: dictionary containing comparison result
Python example.
.. code-block:: python
diff = Calendar().time_difference(
"1975-05-22T18:00:00",
"1975-05-22T22:45:30"
)
# diff['end_date_is_later'] == True
# diff['days'] == 0
# diff['hours'] == 4
# diff['minutes'] == 45
# diff['seconds'] == 30
Robot Framework example.
.. code-block:: robotframework
&{diff}= Time Difference 1975-05-22T18:00:00 1975-05-22T22:45:30
# ${diff}[end_date_is_later] == True
# ${diff}[days] == 0
# ${diff}[hours] == 4
# ${diff}[minutes] == 45
# ${diff}[seconds] == 30
"""
if isinstance(start_date, str):
start_d = self._parse_datetime_string_to_pendulum_datetime(
start_date, timezone=start_timezone
)
else:
start_d = start_date
if isinstance(end_date, str):
end_d = self._parse_datetime_string_to_pendulum_datetime(
end_date, timezone=end_timezone
)
else:
end_d = end_date
diff = end_d - start_d
modifier_for_seconds = 1 if diff.seconds >= 0 else -1
return {
"end_date_is_later": end_d > start_d,
"years": diff.years,
"months": diff.months,
"days": diff.days,
"hours": diff.hours,
"minutes": diff.minutes,
"seconds": diff.seconds
if abs(diff.seconds) <= 60
else abs(diff.seconds) % 60 * modifier_for_seconds,
}
@keyword
def create_time(
self,
date_string: str,
date_format_in: Optional[str] = None,
timezone: Optional[str] = None,
date_format_out: Optional[str] = None,
) -> Union[PendulumDateTime, str]:
"""This keyword tries to construct valid calendar
instance from given date string and its expected date
format.
See https://pendulum.eustace.io/docs/#tokens for
valid tokens for the date format. Tokens are
used to form correct date and time format.
:param date_string: for example. "22 May 19"
:param date_format_in: for example. "DD MMM YY"
:param timezone: default timezone is "UTC"
:param date_format_out: for example. "DD-MM-YY"
:return: set datetime as an object or string
if `date_format_out` has been set
Python example.
.. code-block:: python
date = Calendar().create_time(
"22 May 19",
"DD MMM YY"
)
Robot Framework example.
.. code-block:: robotframework
${date}= Create Time
... 22 May 19
... DD MMM YY
"""
result = None
if date_format_in:
result = pdl.from_format(date_string, date_format_in, tz=timezone)
else:
result = self._parse_datetime_string_to_pendulum_datetime(
date_string, timezone=timezone
)
return result.format(date_format_out) if date_format_out else result
@keyword
def time_now(
self,
timezone: Optional[str] = None,
return_format: str = "YYYY-MM-DD",
) -> PendulumDateTime:
"""Return current date and time
:param timezone: optional, for example. "America/Boston"
:param return_format: dates can be formatted for the resulting
list, defaults to "YYYY-MM-DD"
:return: current datetime as an object
Python example.
.. code-block:: python
now = Calendar().time_now("Europe/Helsinki")
Robot Framework example.
.. code-block:: robotframework
${now}= Time Now Europe/Helsinki
"""
now = pdl.now(tz=timezone)
if return_format:
now = now.format(return_format)
return now
def _parse_datetime_string_to_pendulum_datetime(
self, date_string: DTFormat, timezone: str = None
):
arguments = {"text": date_string, "strict": False}
if timezone:
arguments["tz"] = timezone
try:
result = pdl.parse(**arguments)
return result
except ParserError as err:
raise ValueError(parsing_error_message % date_string) from err
@keyword
def time_difference_in_months(
self,
start_date: DTFormat,
end_date: DTFormat,
start_timezone: Optional[str] = None,
end_timezone: Optional[str] = None,
):
"""Return time difference of dates in months.
:param start_date: the start date
:param end_date: the end date
:param start_timezone: timezone for the start date,
defaults to None
:param end_timezone: timezone for the end date,
defaults to None
:return: difference in months
Python example.
.. code-block:: python
diff = Calendar().time_difference_in_months(
"2022-05-21T22:00:00",
"2023-08-21T22:00:00"
)
# diff == 15
Robot Framework example.
.. code-block:: robotframework
${diff}= Time Difference In Months
... 2022-05-21T22:00:00
... 2023-08-21T22:00:00
# ${diff} == 15
"""
start_date_dt = self.create_time(start_date, timezone=start_timezone)
end_date_dt = self.create_time(end_date, timezone=end_timezone)
return end_date_dt.diff(start_date_dt).in_months()
@keyword
def time_difference_in_days(
self,
start_date: DTFormat,
end_date: DTFormat,
start_timezone: Optional[str] = None,
end_timezone: Optional[str] = None,
):
"""Return the time difference of dates in days.
:param start_date: the start date
:param end_date: the end date
:param start_timezone: timezone for the start date,
defaults to None
:param end_timezone: timezone for the end date,
defaults to None
:return: difference in days
Python example.
.. code-block:: python
diff = Calendar().time_difference_in_days(
"2023-05-21",
"2023-05-29"
)
# diff == 8
Robot Framework example.
.. code-block:: robotframework
${diff}= Time Difference In Days
... 2023-05-21
... 2023-05-29
# ${diff} == 8
"""
start_date_dt = self.create_time(start_date, timezone=start_timezone)
end_date_dt = self.create_time(end_date, timezone=end_timezone)
return end_date_dt.diff(start_date_dt).in_days()
@keyword
def time_difference_in_hours(
self,
start_date: DTFormat,
end_date: DTFormat,
start_timezone: Optional[str] = None,
end_timezone: Optional[str] = None,
):
"""Return the time difference of dates in hours.
:param start_date: the start date
:param end_date: the end date
:param start_timezone: timezone for the start date,
defaults to None
:param end_timezone: timezone for the end date,
defaults to None
:return: difference in hours
Python example.
.. code-block:: python
diff = Calendar().time_difference_in_hours(
"2023-08-21T22:00:00",
"2023-08-22T04:00:00"
)
# diff == 6
Robot Framework example.
.. code-block:: robotframework
${diff}= Time Difference In Hours
... 2023-08-21T22:00:00
... 2023-08-22T04:00:00
# ${diff} == 6
"""
start_date_dt = self.create_time(start_date, timezone=start_timezone)
end_date_dt = self.create_time(end_date, timezone=end_timezone)
return end_date_dt.diff(start_date_dt).in_hours()
@keyword
def time_difference_in_minutes(
self,
start_date: DTFormat,
end_date: DTFormat,
start_timezone: Optional[str] = None,
end_timezone: Optional[str] = None,
):
"""Return the time difference of dates in minutes.
:param start_date: the start date
:param end_date: the end date
:param start_timezone: timezone for the start date,
defaults to None
:param end_timezone: timezone for the end date,
defaults to None
:return: difference in minutes
Python example.
.. code-block:: python
diff = Calendar().time_difference_in_minutes(
"12:30",
"16:35"
)
# diff == 245
Robot Framework example.
.. code-block:: robotframework
${diff}= Time Difference In Minutes
... 12:30
... 16:35
# ${diff} == 245
"""
start_date_dt = self.create_time(start_date, timezone=start_timezone)
end_date_dt = self.create_time(end_date, timezone=end_timezone)
return end_date_dt.diff(start_date_dt).in_minutes()
@keyword
def time_difference_between_timezones(
self,
start_timezone: str,
end_timezone: str,
):
"""Return the hour difference between timezones.
:param start_timezone: first timezone
:param end_timezone: second timezone
:return: hour difference between the timezones
Python example.
.. code-block:: python
diff = Calendar().time_difference_between_timezones(
"America/New_York",
"Europe/Helsinki"
)
# diff == 7
Robot Framework example.
.. code-block:: robotframework
${diff}= Time Difference Between Timezones
... America/New_York
... Europe/Helsinki
# ${diff} == 7
"""
start_date_dt = pdl.datetime(2023, 1, 1, tz=start_timezone)
end_date_dt = pdl.datetime(2023, 1, 1, tz=end_timezone)
return end_date_dt.diff(start_date_dt).in_hours()
@keyword
def return_previous_business_day(
self,
date: DTFormat,
country: Optional[str] = None,
return_format: str = "YYYY-MM-DD",
locale: Optional[str] = None,
):
"""Return the previous business day.
:param date: day of origin
:param country: country code, default `None`
:param return_format: dates can be formatted for the resulting
list, defaults to "YYYY-MM-DD"
:param locale: name of the locale
:return: the previous business day from day of origin
Python example.
.. code-block:: python
prev_business = Calendar().return_previous_business_day("2023-01-09", "FI")
# prev == "2023-01-05"
Robot Framework example.
.. code-block:: robotframework
${previous_business}= Return Previous Business Day 2023-01-09 FI
# ${previous_business} == "2023-01-05"
"""
return self._return_business_day(date, country, return_format, locale, -1)
@keyword
def return_next_business_day(
self,
date: DTFormat,
country: Optional[str] = None,
return_format: str = "YYYY-MM-DD",
locale: Optional[str] = None,
):
"""Return the next business day.
:param date: day of origin
:param country: country code, default `None`
:param return_format: dates can be formatted for the resulting
list, defaults to "YYYY-MM-DD"
:param locale: name of the locale
:return: the next business day from day of origin
Python example.
.. code-block:: python
next_business = Calendar().return_next_business_day("2023-01-05", "FI")
# next_business == "2023-01-09"
Robot Framework example.
.. code-block:: robotframework
${next_business}= Return Next Business Day 2023-01-05 FI
# ${next_business} == "2023-01-09"
"""
return self._return_business_day(date, country, return_format, locale, 1)
def _return_business_day(
self,
given_date: DTFormat,
country: Optional[str] = None,
return_format: Optional[str] = None,
locale: Optional[str] = None,
direction: int = -1,
):
if isinstance(given_date, str):
given_dt = pdl.parse(given_date, strict=False)
else:
given_dt = given_date
previous_dt = given_dt
years = [given_dt.year - 1, given_dt.year, given_dt.year + 1]
holiday_list = self.return_holidays(years, country)
while True:
is_business_day = False
previous_dt = previous_dt.add(days=direction)
prev_day = pdl.date(previous_dt.year, previous_dt.month, previous_dt.day)
if previous_dt.day_of_week in self.BUSINESS_DAYS:
is_business_day = True
if country and is_business_day:
is_business_day = prev_day not in holiday_list
if is_business_day:
break
if return_format:
return previous_dt.format(fmt=return_format, locale=locale)
else:
return previous_dt
@keyword
def return_holidays(
self, years: Union[int, List[int]], country: Optional[str] = None
) -> Dict:
"""Return holidays for a country. If country is not given
then only custom holidays are returned.
:param years: single year or list of years to list holidays for
:param country: country code, default `None`
:return: holidays in a dictionary, the key is the date and the
value is name of the holiday
Python example.
.. code-block:: python
holidays = Calendar().return_holidays(2023, "FI")
for date, holiday_name in holidays.items():
print(f"{date} is {holiday_name}")
Robot Framework example.
.. code-block:: robotframework
&{holidays}= Return Holidays 2023 FI
FOR ${date} IN @{holidays.keys()}
Log To Console ${date} is ${holidays}[${date}]
END
"""
if country:
holiday_list = holidays.country_holidays(country=country, years=years)
else:
holiday_list = holidays.HolidayBase(years=years)
# add custom holidays
holiday_list += self.custom_holidays
return holiday_list
@keyword
def first_business_day_of_the_month(
self, date: DTFormat, country: Optional[str] = None
):
"""Return first business day of the month.
If `country` is not given then holidays are not considered.
:param date: date describing the month
:param country: country code, default `None`
:return: first business of the month
Python example.
.. code-block:: python
first_day = Calendar().first_business_day_of_the_month("2024-06-01")
# first_day == "2024-06-03"
Robot Framework example.
.. code-block:: robotframework
${first_day}= First Business Day of the Month 2024-06-01
# ${first_day} == "2024-06-03"
"""
result = None
if isinstance(date, str):
given_dt = pdl.parse(date, strict=False)
else:
given_dt = date
year, current_month = given_dt.year, given_dt.month
day = 2
for _ in range(32):
day_to_check = pdl.date(year, current_month, day)
result = self.return_previous_business_day(
day_to_check, country=country, return_format=None
)
if result.month == current_month:
break
else:
day += 1
return result
@keyword
def last_business_day_of_the_month(
self, date: DTFormat, country: Optional[str] = None
):
"""Return last business day of the month.
If `country` is not given then holidays are not considered.
:param date: date describing the month
:param country: country code, default `None`
:return: last business day of the month
Python example.
.. code-block:: python
last_day = Calendar().last_business_day_of_the_month("2023-12-01")
# last_day == "2023-12-29"
Robot Framework example.
.. code-block:: robotframework
${last_day}= Last Business Day of the Month 2023-12-01
# ${last_day} == "2023-12-29"
"""
result = None
if isinstance(date, str):
given_dt = pdl.parse(date, strict=False)
else:
given_dt = date
year, current_month = given_dt.year, given_dt.month
day = 1
for _ in range(32):
try:
if day == 1:
next_month = given_dt.set(day=1).add(months=1)
day_to_check = pdl.date(next_month.year, next_month.month, day)
day = 31
else:
day_to_check = pdl.date(year, current_month, day)
result = self.return_previous_business_day(
day_to_check, country=country, return_format=None
)
if result.month == current_month:
break
else:
day -= 1
except ValueError:
day -= 1
return result
@keyword
def sort_list_of_dates(
self,
dates: List[DTFormat],
return_format: Optional[str] = None,
reverse: bool = False,
) -> List:
"""Sort list of dates.
:param dates: list of dates to sort
:param return_format: dates can be formatted for the resulting
list
:param reverse: `True` return latest to oldest, defaults to `False`,
which means order from oldest to latest
:return: list of sorted dates
Python example.
.. code-block:: python
datelist = [
"2023-07-02 12:02:31",
"2023-07-03 12:02:35",
"2023-07-03 12:02:31"
]
sorted = Calendar().sort_list_of_dates(datelist)
# sorted[0] == "2023-07-03 12:02:35"
# sorted[-1] == "2023-07-02 12:02:31"
sorted = Calendar().sort_list_of_dates(datelist, reverse=True)
# sorted[0] == "2023-07-02 12:02:31"
# sorted[-1] == "2023-07-03 12:02:35"
Robot Framework example.
.. code-block:: robotframework
@{datelist}= Create List
... 2023-07-02 12:02:31
... 2023-07-03 12:02:35
... 2023-07-03 12:02:31
${sorted}= Sort List Of Dates ${datelist}
# ${sorted}[0] == "2023-07-03 12:02:35"
# ${sorted}[-1] == "2023-07-02 12:02:31"
${sorted}= Sort List Of Dates ${datelist} reverse=True
# ${sorted}[0] == "2023-07-02 12:02:31"
# ${sorted}[-1] == "2023-07-03 12:02:35"
"""
dt_list = [self.create_time(date) for date in dates]
result = sorted(dt_list, reverse=reverse)
return [d.format(return_format) for d in result] if return_format else result
@keyword(name="Compare Times ${time1} < ${time2}")
def _rfw_compare_time_before(self, time1: DTFormat, time2: DTFormat):
"""Compares given times and returns `True` if `time2`
is more recent than `time1`.
:param time1: first time for comparison
:param time2: second time for comparison
:return: `True` if `time2` is more recent than `time1`
Robot Framework example.
.. code-block:: robotframework
${recent}= Compare Times 2023-03-09 15:50 < 2023-03-09 15:59
IF ${recent}
Log 2023-03-09 15:59 is more recent
END
"""
return self.compare_times(time1, time2)
@keyword(name="Compare Times ${time1} > ${time2}")
def _rfw_compare_time_after(self, time1: DTFormat, time2: DTFormat):
"""Compares given times and returns `True` if `time1`
is more recent than `time2`.
:param time1: first time for comparison
:param time2: second time for comparison
:return: `True` if `time1` is more recent than `time2`
Robot Framework example.
.. code-block:: robotframework
${recent}= Compare Times 2023-03-09 15:59 > 2023-03-09 15:58
IF ${recent}
Log 2023-03-09 15:59 is more recent
END
"""
return not self.compare_times(time1, time2)
@keyword
def compare_times(self, time1: DTFormat, time2: DTFormat):
"""Compares given times and returns `True` if `time2`
is more recent than `time1`.
:param time1: first time for comparison
:param time2: second time for comparison
:return: `True` if `time2` is more recent than `time1`
Python example.
.. code-block:: python
recent = Calendar().compare_times("2023-03-09 13:02", "2023-03-09 13:47")
if recent:
print("2023-03-09 13:47 is more recent")
Robot Framework example.
.. code-block:: robotframework
${recent}= Compare Times 2023-03-09 13:02 2023-03-09 13:47
IF ${recent}
Log 2023-03-09 13:47 is more recent
END
"""
diff = self.time_difference(time1, time2)
return diff["end_date_is_later"]
@keyword
def get_iso_calendar(self, date: DTFormat):
"""Get ISO calendar information for the given date.
:parameter date: input date
:return: ISO calendar object containing year, week number and weekday.
Python example.
.. code-block:: python
iso_cal = Calendar().get_iso_calendar("2023-03-09")
print(iso_cal.year)
print(iso_cal.week)
print(iso_cal.weekday)
Robot Framework example.
.. code-block:: robotframework
${iso_cal}= Get ISO Calendar 2023-03-09
${iso_year}= Set Variable ${iso_cal.year}
${iso_week}= Set Variable ${iso_cal.week}
${iso_weekday}= Set Variable ${iso_cal.weekday}
"""
if isinstance(date, str):
given_dt = pdl.parse(date, strict=False)
else:
given_dt = date
return given_dt.isocalendar()
@keyword
def is_the_date_business_day(
self, date: DTFormat, country: Optional[str] = None
) -> bool:
"""Is the date a business day in a country.
If `country` is not given then holidays are not considered.
:param date: input date
:param country: country code, default `None`
:return: `True` if the day is a business day, `False` if not
Python example.
.. code-block:: python
for day in range(1,32):
date = f"2023-1-{day}"
is_business_day = Calendar().is_the_date_business_day(date, "FI")
if is_business_day:
print(f'It is time for the work on {date}')
else:
print(f'It is time to relax on {date}')
Robot Framework example.
.. code-block:: robotframework
FOR ${day} IN RANGE 1 32
${date}= Set Variable 2023-1-${day}
${is_business_day}= Is the date business day ${date} FI
IF ${is_business_day}
Log To Console It is time for the work on ${date}
ELSE
Log To Console It is time to relax on ${date}
END
END
"""
if isinstance(date, str):
given_dt = pdl.parse(date, strict=False)
else:
given_dt = date
holiday_list = self.return_holidays(given_dt.year, country)
is_business_day = False
if given_dt.day_of_week in self.BUSINESS_DAYS:
is_business_day = True
if country and is_business_day:
is_business_day = given_dt not in holiday_list
return is_business_day
@keyword(name="Is the ${date} Business Day in ${country}")
def _rfw_is_the_day_business_day(self, date: DTFormat, country: str):
"""Is the date a business day in a country.
:param date_in: input date
:param country: country code
:return: `True` if the day is a business day, `False` if not
Robot Framework example.
.. code-block:: robotframework
${is_business_day}= Is the 2023-01-02 business day in FI
IF ${is_business_day}
Log To Console It is time for the work
ELSE
Log To Console It is time to relax
END
"""
return self.is_the_date_business_day(date, country)
@keyword
def is_the_date_holiday(self, date: DTFormat, country: Optional[str] = None):
"""Is the date a holiday in a country.
If `country` is not given then checks only if date is in custom holiday list.
:param date_in: input date
:param country: country code, default `None`
:return: `True` if the day is a holiday, `False` if not
Python example.
.. code-block:: python
is_holiday = Calendar().is_the_date_holiday("2022-12-26", "FI")
if is_holiday:
print('Time to relax')
else:
print('Time for the work')
Robot Framework example.
.. code-block:: robotframework
${is_holiday}= Is the date holiday 2022-12-26 FI
IF ${is_holiday}
Log Time to relax
ELSE
Log Time for the work
END
"""
if isinstance(date, str):
given_dt = pdl.parse(date, strict=False)
else:
given_dt = date
holiday_list = self.return_holidays(given_dt.year, country)
return given_dt in holiday_list
@keyword(name="Is the ${date} Holiday in ${country}")
def _rfw_is_the_day_holiday(self, date: DTFormat, country: str):
"""Is the date a holiday in a country.
:param date_in: input date
:param country: country code
:return: `True` if the day is a holiday, `False` if not
Robot Framework example.
.. code-block:: robotframework
${is_it}= Is the 2022-12-26 holiday in FI
IF ${is_holiday}
Log Time to relax
ELSE
Log Time for the work
END
"""
return self.is_the_date_holiday(date, country) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Calendar.py | 0.910124 | 0.398202 | Calendar.py | pypi |
import copy
import csv
import logging
import re
from collections import OrderedDict, namedtuple
from enum import Enum
from itertools import groupby, zip_longest
from keyword import iskeyword
from numbers import Number
from operator import itemgetter
from typing import (
Any,
Callable,
Dict,
Generator,
Iterable,
List,
NamedTuple,
Optional,
Tuple,
Union,
)
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn
from RPA.core.notebook import notebook_print, notebook_table
from RPA.core.types import is_dict_like, is_list_like, is_namedtuple
Index = Union[int, str]
Column = Union[int, str]
Row = Union[Dict, List, Tuple, NamedTuple, set]
Data = Optional[Union[Dict[Column, Row], List[Row], "Table"]]
CellCondition = Callable[[Any], bool]
RowCondition = Callable[[Union[Index, Row]], bool]
def return_table_as_raw_list(table, heading=False):
raw_list = []
if heading:
raw_list.append(table.columns)
for index in table.index:
row = []
for column in table.columns:
row.append(table.get_cell(index, column))
raw_list.append(row)
return raw_list
def to_list(obj: Any, size: int = 1):
"""Convert (possibly scalar) value to list of `size`."""
if not is_list_like(obj):
return [obj] * int(size)
else:
return obj
def to_identifier(val: Any):
"""Convert string to valid identifier"""
val = str(val).strip()
# Replaces spaces, dashes, and slashes to underscores
val = re.sub(r"[\s\-/\\]", "_", val)
# Remove remaining invalid characters
val = re.sub(r"[^0-9a-zA-Z_]", "", val)
# Identifier can't start with digits
val = re.sub(r"^[^a-zA-Z_]+", "", val)
if not val or iskeyword(val):
raise ValueError(f"Unable to convert to identifier: {val}")
return val
def to_condition(operator: str, value: Any) -> CellCondition:
"""Convert string operator into callable condition function."""
operator = str(operator).lower().strip()
condition = {
">": lambda x: x is not None and x > value,
"<": lambda x: x is not None and x < value,
">=": lambda x: x is not None and x >= value,
"<=": lambda x: x is not None and x <= value,
"==": lambda x: x == value,
"!=": lambda x: x != value,
"is": lambda x: x is value,
"not is": lambda x: x is not value,
"contains": lambda x: x is not None and value in x,
"not contains": lambda x: x is not None and value not in x,
"in": lambda x: x in value,
"not in": lambda x: x not in value,
}.get(operator)
if not condition:
raise ValueError(f"Unknown operator: {operator}")
return condition
def if_none(value: Any, default: Any):
"""Return default if value is None."""
return value if value is not None else default
def uniq(seq: Iterable):
"""Return list of unique values while preserving order.
Values must be hashable.
"""
seen, result = {}, []
for item in seq:
if item in seen:
continue
seen[item] = None
result.append(item)
return result
class Dialect(Enum):
"""CSV dialect"""
Excel = "excel"
ExcelTab = "excel-tab"
Unix = "unix"
class Table:
"""Container class for tabular data.
Supported data formats:
- empty: None values populated according to columns/index
- list: list of data Rows
- dict: Dictionary of columns as keys and Rows as values
- table: An existing Table
Row: a namedtuple, dictionary, list or a tuple
:param data: Values for table, see "Supported data formats"
:param columns: Names for columns, should match data dimensions
"""
def __init__(self, data: Data = None, columns: Optional[List[str]] = None):
self._data = []
self._columns = []
# Use public setter to validate data
if columns is not None:
self.columns = list(columns)
if not data:
self._init_empty()
elif isinstance(data, Table):
self._init_table(data)
elif is_dict_like(data):
self._init_dict(data)
elif is_list_like(data):
self._init_list(data)
else:
raise TypeError("Not a valid input format")
if columns:
self._sort_columns(columns)
self._validate_self()
def _init_empty(self):
"""Initialize table with empty data."""
self._data = []
def _init_table(self, table: "Table"):
"""Initialize table with another table."""
if not self.columns:
self.columns = table.columns
self._data = table.data
def _init_list(self, data: List[Any]):
"""Initialize table from list-like container."""
# Assume data is homogenous in regard to row type
obj = data[0]
column_names = self._column_name_getter(obj)
column_values = self._column_value_getter(obj)
# Map of source to destination column
column_map = {}
# Do not update columns if predefined
add_columns = not bool(self._columns)
for obj in data:
row = [None] * len(self._columns)
for column_src in column_names(obj):
# Check if column has been added with different name
column_dst = column_map.get(column_src, column_src)
# Dictionaries and namedtuples can
# contain unknown columns
if column_dst not in self._columns:
if not add_columns:
continue
col = self._add_column(column_dst)
# Store map of source column name to created name
column_dst = self._columns[col]
column_map[column_src] = column_dst
while len(row) < len(self._columns):
row.append(None)
col = self.column_location(column_dst)
row[col] = column_values(obj, column_src)
self._data.append(row)
def _init_dict(self, data: Dict[Column, Row]):
"""Initialize table from dict-like container."""
if not self._columns:
self._columns = list(data.keys())
# Filter values by defined columns
columns = (
to_list(values)
for column, values in data.items()
if column in self._columns
)
# Convert columns to rows
self._data = [list(row) for row in zip_longest(*columns)]
def __repr__(self):
return "Table(columns={}, rows={})".format(self.columns, self.size)
def __len__(self):
return self.size
def __iter__(self):
return self.iter_dicts(with_index=False)
def __eq__(self, other: Any):
if not isinstance(other, Table):
return False
return self._columns == other._columns and self._data == other._data
@property
def data(self):
return self._data.copy()
@property
def size(self) -> int:
return len(self._data)
@property
def dimensions(self):
return self.size, len(self._columns)
@property
def index(self):
return list(range(self.size))
@property
def columns(self):
return self._columns.copy()
@columns.setter
def columns(self, names):
"""Rename columns with given values."""
self._validate_columns(names)
self._columns = list(names)
def _validate_columns(self, names):
"""Validate that given column names can be used."""
if not is_list_like(names):
raise ValueError("Columns should be list-like")
if len(set(names)) != len(names):
raise ValueError("Duplicate column names")
if self._data and len(names) != len(self._data[0]):
raise ValueError("Invalid columns length")
def _column_name_getter(self, obj):
"""Create callable that returns column names for given obj types."""
if is_namedtuple(obj):
# Use namedtuple fields as columns
def get(obj):
return list(obj._fields)
elif is_dict_like(obj):
# Use dictionary keys as columns
def get(obj):
return list(obj.keys())
elif is_list_like(obj):
# Use either predefined columns, or
# generate range-based column values
predefined = list(self._columns)
def get(obj):
count = len(obj)
if predefined:
if count > len(predefined):
raise ValueError(
f"Data had more than defined {len(predefined)} columns"
)
return predefined[:count]
else:
return list(range(count))
else:
# Fallback to single column
def get(_):
return self._columns[:1] if self._columns else [0]
return get
def _column_value_getter(self, obj):
"""Create callable that returns column values for given object types."""
if is_namedtuple(obj):
# Get values using properties
def get(obj, column):
return getattr(obj, column, None)
elif is_dict_like(obj):
# Get values using dictionary keys
def get(obj, column):
return obj.get(column)
elif is_list_like(obj):
# Get values using list indexes
def get(obj, column):
col = self.column_location(column)
try:
return obj[col]
except IndexError:
return None
else:
# Fallback to single column
def get(obj, _):
return obj
return get
def _sort_columns(self, order):
"""Sort columns to match given order."""
unknown = set(self._columns) - set(order)
if unknown:
names = ", ".join(str(name) for name in unknown)
raise ValueError(f"Unknown columns: {names}")
cols = [self.column_location(column) for column in order]
self._columns = [self._columns[col] for col in cols]
self._data = [[row[col] for col in cols] for row in self._data]
def _validate_self(self):
"""Validate that internal data is valid and coherent."""
self._validate_columns(self._columns)
if self._data:
head = self._data[0]
if len(head) != len(self._columns):
raise ValueError("Columns length does not match data")
def index_location(self, value: Index) -> int:
try:
value = int(value)
except ValueError as err:
raise ValueError(f"Index is not a number: {value}") from err
if value < 0:
value += self.size
if self.size == 0:
raise IndexError("No rows in table")
if (value < 0) or (value >= self.size):
raise IndexError(f"Index ({value}) out of range (0..{self.size - 1})")
return value
def column_location(self, value):
"""Find location for column value."""
# Try to use as-is
try:
return self._columns.index(value)
except ValueError:
pass
# Try as integer index
try:
value = int(value)
if value in self._columns:
location = self._columns.index(value)
elif value < 0:
location = value + len(self._columns)
else:
location = value
size = len(self._columns)
if size == 0:
raise IndexError("No columns in table")
if location >= size:
raise IndexError(f"Column ({location}) out of range (0..{size - 1})")
return location
except ValueError:
pass
# No matches
options = ", ".join(str(col) for col in self._columns)
raise ValueError(f"Unknown column name: {value}, current columns: {options}")
def __getitem__(self, key):
"""Helper method for accessing items in the Table.
Examples:
table[:10] First 10 rows
table[0,1] Value in first row and second column
table[2:10,"email"] Values in "email" column for rows 3 to 11
"""
# Both row index and columns given
if isinstance(key, tuple):
index, column = key
index = self._slice_index(index) if isinstance(index, slice) else index
return self.get(indexes=index, columns=column, as_list=True)
# Row indexed with slice, all columns
elif isinstance(key, slice):
return self.get(indexes=self._slice_index(key), as_list=True)
# Single row
else:
return self.get(indexes=key, as_list=True)
def __setitem__(self, key, value):
"""Helper method for setting items in the Table.
Examples:
table[5] = ["Mikko", "Mallikas"]
table[:2] = [["Marko", "Markonen"], ["Pentti", "Penttinen"]]
"""
# Both row index and columns given
if isinstance(key, tuple):
index, column = key
index = self._slice_index(index) if isinstance(index, slice) else index
return self.set(indexes=index, columns=column, values=value)
# Row indexed with slice, all columns
elif isinstance(key, slice):
return self.set(indexes=self._slice_index(key), values=value)
# Single row
else:
return self.set(indexes=key, values=value)
def _slice_index(self, slicer):
"""Create list of index values from slice object."""
start = self.index_location(slicer.start) if slicer.start is not None else 0
end = self.index_location(slicer.stop) if slicer.stop is not None else self.size
return list(range(start, end))
def copy(self):
"""Create a copy of this table."""
return copy.deepcopy(self)
def clear(self):
"""Remove all rows from this table."""
self._data = []
def head(self, rows, as_list=False):
"""Return first n rows of table."""
indexes = self.index[: int(rows)]
return self.get_table(indexes, as_list=as_list)
def tail(self, rows, as_list=False):
"""Return last n rows of table."""
indexes = self.index[-int(rows) :]
return self.get_table(indexes, as_list=as_list)
def get(self, indexes=None, columns=None, as_list=False):
"""Get values from table. Return type depends on input dimensions.
If `indexes` and `columns` are scalar, i.e. not lists:
Returns single cell value
If either `indexes` or `columns` is a list:
Returns matching row or column
If both `indexes` and `columns` are lists:
Returns a new Table instance with matching cell values
:param indexes: List of indexes, or all if not given
:param columns: List of columns, or all if not given
"""
indexes = if_none(indexes, self.index)
columns = if_none(columns, self._columns)
if is_list_like(indexes) and is_list_like(columns):
return self.get_table(indexes, columns, as_list)
elif not is_list_like(indexes) and is_list_like(columns):
return self.get_row(indexes, columns, as_list)
elif is_list_like(indexes) and not is_list_like(columns):
return self.get_column(columns, indexes, as_list)
else:
return self.get_cell(indexes, columns)
def get_cell(self, index, column):
"""Get single cell value."""
idx = self.index_location(index)
col = self.column_location(column)
return self._data[idx][col]
def get_row(self, index: Index, columns=None, as_list=False):
"""Get column values from row.
:param index: Index for row
:param columns: Column names to include, or all if not given
:param as_list: Return row as dictionary, instead of list
"""
columns = if_none(columns, self._columns)
idx = self.index_location(index)
if as_list:
row = []
for column in columns:
col = self.column_location(column)
row.append(self._data[idx][col])
return row
else:
row = {}
for column in columns:
col = self.column_location(column)
row[self._columns[col]] = self._data[idx][col]
return row
def get_column(self, column, indexes=None, as_list=False):
"""Get row values from column.
:param columns: Name for column
:param indexes: Row indexes to include, or all if not given
:param as_list: Return column as dictionary, instead of list
"""
indexes = if_none(indexes, self.index)
col = self.column_location(column)
if as_list:
column = []
for index in indexes:
idx = self.index_location(index)
column.append(self._data[idx][col])
return column
else:
column = {}
for index in indexes:
idx = self.index_location(index)
column[idx] = self._data[idx][col]
return column
def get_table(self, indexes=None, columns=None, as_list=False):
"""Get a new table from all cells matching indexes and columns."""
indexes = if_none(indexes, self.index)
columns = if_none(columns, self._columns)
if indexes == self.index and columns == self._columns:
return self.copy()
idxs = [self.index_location(index) for index in indexes]
cols = [self.column_location(column) for column in columns]
data = [[self._data[idx][col] for col in cols] for idx in idxs]
if as_list:
return data
else:
return Table(data=data, columns=columns)
def get_slice(self, start: Optional[Index] = None, end: Optional[Index] = None):
"""Get a new table from rows between start and end index."""
index = self._slice_index(slice(start, end))
return self.get_table(index, self._columns)
def _add_row(self, index):
"""Add a new empty row into the table."""
if index is None:
index = self.size
if index < self.size:
raise ValueError(f"Duplicate row index: {index}")
for empty in range(self.size, index):
self._add_row(empty)
self._data.append([None] * len(self._columns))
return self.size - 1
def _add_column(self, column):
"""Add a new empty column into the table."""
if column is None:
column = len(self._columns)
if column in self._columns:
raise ValueError(f"Duplicate column name: {column}")
if isinstance(column, int):
assert column >= len(self._columns)
for empty in range(len(self._columns), column):
self._add_column(empty)
self._columns.append(column)
for idx in self.index:
row = self._data[idx]
row.append(None)
return len(self._columns) - 1
def set(self, indexes=None, columns=None, values=None):
"""Sets multiple cell values at a time.
Both `indexes` and `columns` can be scalar or list-like,
which enables setting individual cells, rows/columns, or regions.
If `values` is scalar, all matching cells will be set to that value.
Otherwise the length should match the cell count defined by the
other parameters.
"""
indexes = to_list(if_none(indexes, self.index))
columns = to_list(if_none(columns, self._columns))
size = len(indexes) + len(columns)
values = to_list(values, size=size)
if not len(values) == size:
raise ValueError("Values size does not match indexes and columns")
for index in indexes:
idx = self.index_location(index)
for column in columns:
col = self.column_location(column)
self.set_cell(index, column, values[idx + col])
def set_cell(self, index, column, value):
"""Set individual cell value.
If either index or column is missing, they are created.
"""
try:
idx = self.index_location(index)
except (IndexError, ValueError):
idx = self._add_row(index)
try:
col = self.column_location(column)
except (IndexError, ValueError):
col = self._add_column(column)
self._data[idx][col] = value
def set_row(self, index, values):
"""Set values in row. If index is missing, it is created."""
try:
idx = self.index_location(index)
except (IndexError, ValueError):
idx = self._add_row(index)
column_values = self._column_value_getter(values)
row = [column_values(values, column) for column in self._columns]
self._data[idx] = row
def set_column(self, column, values):
"""Set values in column. If column is missing, it is created."""
values = to_list(values, size=self.size)
if len(values) != self.size:
raise ValueError(
f"Values length ({len(values)}) should match data length ({self.size})"
)
if column not in self._columns:
self._add_column(column)
for index in self.index:
self.set_cell(index, column, values[index])
def append_row(self, row=None):
"""Append new row to table."""
self.set_row(self.size, row)
def append_rows(self, rows):
"""Append multiple rows to table."""
for row in rows:
self.append_row(row)
def append_column(self, column=None, values=None):
if column is not None and column in self._columns:
raise ValueError(f"Column already exists: {column}")
self.set_column(column, values)
def delete_rows(self, indexes: Union[Index, List[Index]]):
"""Remove rows with matching indexes."""
indexes = [self.index_location(idx) for idx in to_list(indexes)]
unknown = set(indexes) - set(self.index)
if unknown:
names = ", ".join(str(name) for name in unknown)
raise ValueError(f"Unable to remove unknown rows: {names}")
for index in sorted(indexes, reverse=True):
del self._data[index]
def delete_columns(self, columns):
"""Remove columns with matching names."""
columns = to_list(columns)
unknown = set(columns) - set(self._columns)
if unknown:
names = ", ".join(str(name) for name in unknown)
raise ValueError(f"Unable to remove unknown columns: {names}")
for column in columns:
col = self.column_location(column)
for idx in self.index:
del self._data[idx][col]
del self._columns[col]
def append_table(self, table):
"""Append data from table to current data."""
if not table:
return
indexes = []
for idx in table.index:
index = self.size + idx
indexes.append(index)
self.set(indexes=indexes, columns=table.columns, values=table.data)
def sort_by_column(self, columns, ascending=False):
"""Sort table by columns."""
columns = to_list(columns)
# Create sort criteria list, with each row as tuple of column values
values = (self.get_column(column, as_list=True) for column in columns)
values = list(zip(*values))
assert len(values) == self.size
def sorter(row):
"""Sort table by given values, while allowing for disparate types.
Order priority:
- Values by typename
- Numeric types
- None values
"""
criteria = []
for value in row[1]: # Ignore enumeration
criteria.append(
(
value is not None,
"" if isinstance(value, Number) else type(value).__name__,
value,
)
)
return criteria
# Store original index order using enumerate() before sort,
# and use it to sort data later
values = sorted(enumerate(values), key=sorter, reverse=not ascending)
idxs = [value[0] for value in values]
# Re-order data
self._data = [self._data[idx] for idx in idxs]
def group_by_column(self, column):
"""Group rows by column value and return as list of tables."""
ref = self.copy()
ref.sort_by_column(column)
col = self.column_location(column)
groups = groupby(ref.data, itemgetter(col))
result = []
ref.clear()
for _, group in groups:
table = ref.copy()
table.append_rows(group)
result.append(table)
return result
def _filter(self, condition: RowCondition):
filtered = list(filter(lambda idx: not condition(idx), self.index))
self.delete_rows(filtered)
def filter_all(self, condition: RowCondition):
"""Remove rows by evaluating `condition` for every row.
The filtering will be done in-place and all the rows evaluating as falsy
through the provided condition will be removed.
"""
def _check_row(index: int) -> bool:
row = self.get_row(index)
return condition(row)
self._filter(_check_row)
def filter_by_column(self, column: Column, condition: CellCondition):
"""Remove rows by evaluating `condition` for cells in `column`.
The filtering will be done in-place and all the rows where it evaluates to
falsy are removed.
"""
def _check_cell(index: int) -> bool:
cell = self.get_cell(index, column)
return condition(cell)
self._filter(_check_cell)
def iter_lists(self, with_index=True):
"""Iterate rows with values as lists."""
for idx, row in zip(self.index, self._data):
if with_index:
yield idx, list(row)
else:
yield list(row)
def iter_dicts(self, with_index=True) -> Generator[Dict[Column, Any], None, None]:
"""Iterate rows with values as dicts."""
for index in self.index:
row = {"index": index} if with_index else {}
for column in self._columns:
row[column] = self.get_cell(index, column)
yield row
def iter_tuples(self, with_index=True, name="Row"):
"""Iterate rows with values as namedtuples.
Converts column names to valid Python identifiers,
e.g. "First Name" -> "First_Name"
"""
columns = {column: to_identifier(column) for column in self._columns}
fields = ["index"] if with_index else []
fields.extend(columns.values())
container = namedtuple(name, fields)
for row in self.iter_dicts(with_index):
row = {columns[k]: v for k, v in row.items()}
yield container(**row)
def to_list(self, with_index=True):
"""Convert table to list representation."""
export = []
for index in self.index:
row = OrderedDict()
if with_index:
row["index"] = index
for column in self._columns:
row[column] = self.get_cell(index, column)
export.append(row)
return export
def to_dict(self, with_index=True):
"""Convert table to dict representation."""
export = OrderedDict()
if with_index:
export["index"] = self.index
for column in self._columns:
export[column] = []
for index in self.index:
for column in self._columns:
value = self.get_cell(index, column)
export[column].append(value)
return export
class Tables:
"""`Tables` is a library for manipulating tabular data inside Robot Framework.
It can import data from various sources and apply different operations to it.
Common use-cases are reading and writing CSV files, inspecting files in
directories, or running tasks using existing Excel data.
**Import types**
The data a table can be created from can be of two main types:
1. An iterable of individual rows, like a list of lists, or list of dictionaries
2. A dictionary of columns, where each dictionary value is a list of values
For instance, these two input values:
.. code-block:: python
data1 = [
{"name": "Mark", "age": 58},
{"name": "John", "age": 22},
{"name": "Adam", "age": 67},
]
data2 = {
"name": ["Mark", "John", "Adam"],
"age": [ 58, 22, 67],
}
Would both result in the following table:
+-------+------+-----+
| Index | Name | Age |
+=======+======+=====+
| 0 | Mark | 58 |
+-------+------+-----+
| 1 | John | 22 |
+-------+------+-----+
| 2 | Adam | 67 |
+-------+------+-----+
**Indexing columns and rows**
Columns can be referred to in two ways: either with a unique string
name or their position as an integer. Columns can be named either when
the table is created, or they can be (re)named dynamically with keywords.
The integer position can always be used, and it starts from zero.
For instance, a table with columns "Name", "Age", and "Address" would
allow referring to the "Age" column with either the name "Age" or the
number 1.
Rows do not have a name, but instead only have an integer index. This
index also starts from zero. Keywords where rows are indexed also support
negative values, which start counting backwards from the end.
For instance, in a table with five rows, the first row could be referred
to with the number 0. The last row could be accessed with either 4 or
-1.
**Examples**
**Robot Framework**
The `Tables` library can load tabular data from various other libraries
and manipulate it inside Robot Framework.
.. code-block:: robotframework
*** Settings ***
Library RPA.Tables
*** Keywords ***
Files to Table
${files}= List files in directory ${CURDIR}
${files}= Create table ${files}
Filter table by column ${files} size >= ${1024}
FOR ${file} IN @{files}
Log ${file}[name]
END
Write table to CSV ${files} ${OUTPUT_DIR}${/}files.csv
**Python**
The library is also available directly through Python, where it
is easier to handle multiple different tables or do more bespoke
manipulation operations.
.. code-block:: python
from RPA.Tables import Tables
library = Tables()
orders = library.read_table_from_csv(
"orders.csv", columns=["name", "mail", "product"]
)
customers = library.group_table_by_column(rows, "mail")
for customer in customers:
for order in customer:
add_cart(order)
make_order()
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self):
self.logger = logging.getLogger(__name__)
@staticmethod
def _requires_table(obj: Any):
if not isinstance(obj, Table):
raise TypeError("Keyword requires Table object")
def create_table(
self, data: Data = None, trim: bool = False, columns: List[str] = None
) -> Table:
"""Create Table object from data.
Data can be a combination of various iterable containers, e.g.
list of lists, list of dicts, dict of lists.
:param data: Source data for table
:param trim: Remove all empty rows from the end of the worksheet,
default `False`
:param columns: Names of columns (optional)
:return: Table object
See the main library documentation for more information about
supported data types.
Example:
.. code-block:: robotframework
# Create a new table using a Dictionary of Lists
# Because of the dictionary keys the column names will be automatically set
@{Table_Data_name}= Create List Mark John Amy
@{Table_Data_age}= Create List ${58} ${22} ${67}
&{Table_Data}= Create Dictionary
... name=${Table_Data_name}
... age=${Table_Data_age}
${table}= Create Table ${Table_Data}
"""
table = Table(data, columns)
if trim:
self.trim_empty_rows(table)
self.trim_column_names(table)
self.logger.info("Created table: %s", table)
notebook_table(self.table_head(table, 10))
return table
def export_table(
self, table: Table, with_index: bool = False, as_list: bool = True
) -> Union[List, Dict]:
"""Convert a table object into standard Python containers.
:param table: Table to convert to dict
:param with_index: Include index in values
:param as_list: Export data as list instead of dict
:return: A List or Dictionary that represents the table
Example:
.. code-block:: robotframework
${orders}= Read worksheet as table orders.xlsx
Sort table by column ${orders} CustomerId
${export}= Export table ${orders}
# The following keyword expects a dictionary:
Write as JSON ${export}
"""
self._requires_table(table)
if as_list:
return table.to_list(with_index)
else:
return table.to_dict(with_index)
def copy_table(self, table: Table) -> Table:
"""Make a copy of a table object.
:param table: Table to copy
:return: Table object
${table_copy}= Copy table ${table}
"""
self._requires_table(table)
return table.copy()
def clear_table(self, table: Table):
"""Clear table in-place, but keep columns.
:param table: Table to clear
Example:
.. code-block:: robotframework
Clear table ${table}
"""
self._requires_table(table)
table.clear()
def merge_tables(self, *tables: Table, index: Optional[str] = None) -> Table:
"""Create a union of two tables and their contents.
:param tables: Tables to merge
:param index: Column name to use as index for merge
:return: Table object
By default rows from all tables are appended one after the other.
Optionally a column name can be given with ``index``, which is
used to merge rows together.
Example:
For instance, a ``name`` column could be used to identify
unique rows and the merge operation should overwrite values
instead of appending multiple copies of the same name.
====== =====
Name Price
====== =====
Egg 10.0
Cheese 15.0
Ham 20.0
====== =====
====== =====
Name Stock
====== =====
Egg 12.0
Cheese 99.0
Ham 0.0
====== =====
.. code-block:: robotframework
${products}= Merge tables ${prices} ${stock} index=Name
FOR ${product} IN @{products}
Log many
... Product: ${product}[Name]
... Price: ${product}[Price]
... Stock: ${product}[Stock]
END
"""
if index is None:
return self._merge_by_append(tables)
else:
return self._merge_by_index(tables, index)
def _merge_by_append(self, tables: Tuple[Table, ...]):
"""Merge tables by appending columns and rows."""
columns = uniq(column for table in tables for column in table.columns)
merged = Table(columns=columns)
for table in tables:
merged.append_rows(table)
return merged
def _merge_by_index(self, tables: Tuple[Table, ...], index: str):
"""Merge tables by using a column as shared key."""
columns = uniq(column for table in tables for column in table.columns)
merged = Table(columns=columns)
seen = {}
def find_index(row):
"""Find index for row, if key already exists."""
value = row[index]
if value in seen:
return seen[value]
for row_ in merged.iter_dicts(True):
if row_[index] == value:
seen[value] = row_["index"]
return row_["index"]
return None
for table in tables:
for row in table.iter_dicts(False):
row_index = find_index(row)
if row_index is None:
merged.append_row(row)
else:
for column, value in row.items():
merged.set_cell(row_index, column, value)
return merged
def get_table_dimensions(self, table: Table) -> Tuple[int, int]:
"""Return table dimensions, as (rows, columns).
:param table: Table to inspect
:return: Two integer values that represent the number
of rows and columns
Example:
.. code-block:: robotframework
${rows} ${columns}= Get table dimensions ${table}
Log Table has ${rows} rows and ${columns} columns.
"""
self._requires_table(table)
notebook_print(text=table.dimensions)
return table.dimensions
def rename_table_columns(
self, table: Table, names: List[Union[str, None]], strict: bool = False
):
"""Renames columns in the Table with given values. Columns with
name as ``None`` will use the previous value.
:param table: Table to modify
:param names: List of new column names
:param strict: If True, raises ValueError if column lengths
do not match
The renaming will be done in-place.
Examples:
.. code-block:: robotframework
# Initially set the column names
${columns}= Create list First Second Third
Rename table columns ${table} ${columns}
# First, Second, Third
# Update the first and second column names to Uno and Dos
${columns}= Create list Uno Dos
Rename table columns ${table} ${columns}
# Uno, Dos, Third
"""
self._requires_table(table)
before = table.columns
if strict and len(before) != len(names):
raise ValueError("Column lengths do not match")
after = []
for old, new in zip_longest(before, names):
if old is None:
break
elif new is None:
after.append(old)
else:
after.append(new)
table.columns = after
def add_table_column(
self, table: Table, name: Optional[str] = None, values: Any = None
):
"""Append a column to a table.
:param table: Table to modify
:param name: Name of new column
:param values: Value(s) for new column
The ``values`` can either be a list of values, one for each row, or
one single value that is set for all rows.
Examples:
.. code-block:: robotframework
# Add empty column
Add table column ${table}
# Add empty column with name
Add table column ${table} name=Home Address
# Add new column where every every row has the same value
Add table column ${table} name=TOS values=${FALSE}
# Add new column where every row has a unique value
${is_first}= Create list ${TRUE} ${FALSE} ${FALSE}
Add table column ${table} name=IsFirst values=${is_first}
"""
self._requires_table(table)
table.append_column(name, values)
def add_table_row(self, table: Table, values: Any = None):
"""Append rows to a table.
:param table: Table to modify
:param values: Value(s) for new row
The ``values`` can either be a list of values, or a dictionary
where the keys match current column names. Values for unknown
keys are discarded.
It can also be a single value that is set for all columns,
which is ``None`` by default.
Examples:
.. code-block:: robotframework
# Add empty row
Add table row ${table}
# Add row where every column has the same value
Add table row ${table} Unknown
# Add values per column
${values}= Create dictionary Username=Mark Mail=mark@robocorp.com
Add table row ${table} ${values}
"""
self._requires_table(table)
table.append_row(values)
def get_table_row(
self, table: Table, row: Index, as_list: bool = False
) -> Union[Dict, List]:
"""Get a single row from a table.
:param table: Table to read
:param row: Row to read
:param as_list: Return list instead of dictionary
:return: Dictionary or List of table row
Examples:
.. code-block:: robotframework
# returns the first row in the table
${first}= Get table row ${orders}
# returns the last row in the table
${last}= Get table row ${orders} -1 as_list=${TRUE}
"""
self._requires_table(table)
values = table.get_row(row, as_list=as_list)
notebook_print(text=values)
return values
def get_table_column(self, table: Table, column: Column) -> List:
"""Get all values for a single column in a table.
:param table: Table to read
:param column: Column to read
:return: List of the rows in the selected column
Example:
.. code-block:: robotframework
${emails}= Get table column ${users} E-Mail Address
"""
self._requires_table(table)
col = table.get_column(column, as_list=True)
return col
def set_table_row(self, table: Table, row: Index, values: Any):
"""Assign values to a row in the table.
:param table: Table to modify
:param row: Row to modify
:param values: Value(s) to set
The ``values`` can either be a list of values, or a dictionary
where the keys match current column names. Values for unknown
keys are discarded.
It can also be a single value that is set for all columns.
Examples:
.. code-block:: robotframework
${columns}= Create list One Two Three
${table}= Create table columns=${columns}
${values}= Create list 1 2 3
Set table row ${table} 0 ${values}
${values}= Create dictionary One=1 Two=2 Three=3
Set table row ${table} 1 ${values}
Set table row ${table} 2 ${NONE}
"""
self._requires_table(table)
table.set_row(row, values)
def set_table_column(self, table: Table, column: Column, values: Any):
"""Assign values to a column in the table.
:param table: Table to modify
:param column: Column to modify
:param values: Value(s) to set
The ``values`` can either be a list of values, one for each row, or
one single value that is set for all rows.
Examples:
.. code-block:: robotframework
# Set different value for each row (sizes must match)
${ids}= Create list 1 2 3 4 5
Set table column ${users} userId ${ids}
# Set the same value for all rows
Set table column ${users} email ${NONE}
"""
self._requires_table(table)
table.set_column(column, values)
def pop_table_row(
self, table: Table, row: Optional[Index] = None, as_list: bool = False
) -> Union[Dict, List]:
"""Remove row from table and return it.
:param table: Table to modify
:param row: Row index, pops first row if none given
:param as_list: Return list instead of dictionary
:return: Dictionary or List of the removed, popped, row
Examples:
.. code-block:: robotframework
# Pop the firt row in the table and discard it
Pop table row ${orders}
# Pop the last row in the table and store it
${row}= Pop table row ${data} -1 as_list=${TRUE}
"""
self._requires_table(table)
row = if_none(row, table.index[0])
values = table.get_row(row, as_list=as_list)
table.delete_rows(row)
return values
def pop_table_column(
self, table: Table, column: Optional[Column] = None
) -> Union[Dict, List]:
"""Remove column from table and return it.
:param table: Table to modify
:param column: Column to remove
:return: Dictionary or List of the removed, popped, column
Examples:
.. code-block:: robotframework
# Remove column from table and discard it
Pop table column ${users} userId
# Remove column from table and iterate over it
${ids}= Pop table column ${users} userId
FOR ${id} IN @{ids}
Log User id: ${id}
END
"""
self._requires_table(table)
column: Column = if_none(column, table.columns[0])
values = self.get_table_column(table, column)
table.delete_columns(column)
return values
def get_table_slice(
self, table: Table, start: Optional[Index] = None, end: Optional[Index] = None
) -> Union[Table, List[List]]:
"""Return a new Table from a range of given Table rows.
:param table: Table to read from
:param start: Start index (inclusive)
:param start: End index (exclusive)
:return: Table object of the selected rows
If ``start`` is not defined, starts from the first row.
If ``end`` is not defined, stops at the last row.
Examples:
.. code-block:: robotframework
# Get all rows except first five
${slice}= Get table slice ${table} start=5
# Get rows at indexes 5, 6, 7, 8, and 9
${slice}= Get table slice ${table} start=5 end=10
# Get all rows except last five
${slice}= Get table slice ${table} end=-5
"""
self._requires_table(table)
return table.get_slice(start, end)
def set_row_as_column_names(self, table: Table, row: Index):
"""Set existing row as names for columns.
:param table: Table to modify
:param row: Row to use as column names
Example:
.. code-block:: robotframework
# Set the column names based on the first row
Set row as column names ${table} 0
"""
values = self.pop_table_row(table, row, as_list=True)
table.columns = values
def table_head(
self, table: Table, count: int = 5, as_list: bool = False
) -> Union[Table, List[List]]:
"""Return first ``count`` rows from a table.
:param table: Table to read from
:param count: Number of lines to read
:param as_list: Return list instead of Table
:return: Return Table object or List of the selected rows
Example:
.. code-block:: robotframework
# Get the first 10 employees
${first}= Table head ${employees} 10
"""
self._requires_table(table)
return table.head(count, as_list)
def table_tail(
self, table: Table, count: int = 5, as_list: bool = False
) -> Union[Table, List[List]]:
"""Return last ``count`` rows from a table.
:param table: Table to read from
:param count: Number of lines to read
:param as_list: Return list instead of Table
:return: Return Table object or List of the selected rows
Example:
.. code-block:: robotframework
# Get the last 10 orders
${latest}= Table tail ${orders} 10
"""
self._requires_table(table)
return table.tail(count, as_list)
def get_table_cell(self, table: Table, row: Index, column: Column) -> Any:
"""Get a cell value from a table.
:param table: Table to read from
:param row: Row of cell
:param column: Column of cell
:return: Cell value
Examples:
.. code-block:: robotframework
# Get the value in the first row and first column
Get table cell ${table} 0 0
# Get the value in the last row and first column
Get table cell ${table} -1 0
# Get the value in the last row and last column
Get table cell ${table} -1 -1
# Get the value in the third row and column "Name"
Get table cell ${table} 2 Name
"""
self._requires_table(table)
return table.get_cell(row, column)
def set_table_cell(self, table: Table, row: Index, column: Column, value: Any):
"""Set a cell value in a table.
:param table: Table to modify to
:param row: Row of cell
:param column: Column of cell
:param value: Value to set
Examples:
.. code-block:: robotframework
# Set the value in the first row and first column to "First"
Set table cell ${table} 0 0 First
# Set the value in the last row and first column to "Last"
Set table cell ${table} -1 0 Last
# Set the value in the last row and last column to "Corner"
Set table cell ${table} -1 -1 Corner
# Set the value in the third row and column "Name" to "Unknown"
Set table cell ${table} 2 Name Unknown
"""
self._requires_table(table)
table.set_cell(row, column, value)
def find_table_rows(self, table: Table, column: Column, operator: str, value: Any):
"""Find all the rows in a table which match a condition for a given column.
:param table: Table to search into.
:param column: Name or position of the column to compare with.
:param operator: Comparison operator used with every cell value on the
specified column.
:param value: Value to compare against.
:return: New `Table` object containing all the rows matching the condition.
Supported operators:
============ ========================================
Operator Description
============ ========================================
> Cell value is larger than
< Cell value is smaller than
>= Cell value is larger or equal than
<= Cell value is smaller or equal than
== Cell value is equal to
!= Cell value is not equal to
is Cell value is the same object
not is Cell value is not the same object
contains Cell value contains given value
not contains Cell value does not contain given value
in Cell value is in given value
not in Cell value is not in given value
============ ========================================
Returns the matches as a new `Table` instance.
Examples:
.. code-block:: robotframework
# Find all rows where price is over 200
@{rows} = Find table rows ${table} Price > ${200}
# Find all rows where the status does not contain "removed"
@{rows} = Find table rows ${table} Status not contains removed
"""
self._requires_table(table)
condition = to_condition(operator, value)
matches = []
for index in table.index:
cell = table.get_cell(index, column)
if condition(cell):
matches.append(index)
return table.get_table(matches)
def sort_table_by_column(
self, table: Table, column: Column, ascending: bool = True
):
"""Sort a table in-place according to ``column``.
:param table: Table to sort
:param column: Column to sort with
:param ascending: Table sort order
Examples:
.. code-block:: robotframework
# Sorts the `order_date` column ascending
Sort table by column ${orders} order_date
# Sorts the `order_date` column descending
Sort table by column ${orders} order_date ascending=${FALSE}
"""
self._requires_table(table)
table.sort_by_column(column, ascending=ascending)
def group_table_by_column(self, table: Table, column: Column) -> List[Table]:
"""Group a table by ``column`` and return a list of grouped Tables.
:param table: Table to use for grouping
:param column: Column which is used as grouping criteria
:return: List of Table objects
Example:
.. code-block:: robotframework
# Groups rows of matching customers from the `customer` column
# and returns the groups or rows as Tables
@{groups}= Group table by column ${orders} customer
# An example of how to use the List of Tables once returned
FOR ${group} IN @{groups}
# Process all orders for the customer at once
Process order ${group}
END
"""
self._requires_table(table)
groups = table.group_by_column(column)
self.logger.info("Found %s groups", len(groups))
return groups
def filter_table_by_column(
self, table: Table, column: Column, operator: str, value: Any
):
"""Remove all rows where column values don't match the
given condition.
:param table: Table to filter
:param column: Column to filter with
:param operator: Filtering operator, e.g. >, <, ==, contains
:param value: Value to compare column to (using operator)
See the keyword ``Find table rows`` for all supported operators
and their descriptions.
The filtering will be done in-place.
Examples:
.. code-block:: robotframework
# Only accept prices that are non-zero
Filter table by column ${table} price != ${0}
# Remove uwnanted product types
@{types}= Create list Unknown Removed
Filter table by column ${table} product_type not in ${types}
"""
self._requires_table(table)
condition = to_condition(operator, value)
before = len(table)
table.filter_by_column(column, condition)
after = len(table)
self.logger.info("Filtered %d rows", after - before)
def filter_table_with_keyword(self, table: Table, name: str, *args):
"""Run a keyword for each row of a table, then remove all rows where the called
keyword returns a falsy value.
Can be used to create custom RF keyword based filters.
:param table: Table to modify.
:param name: Keyword name used as filter.
:param args: Additional keyword arguments to be passed. (optional)
The row object will be given as the first argument to the filtering keyword.
"""
self._requires_table(table)
def condition(row: Row) -> bool:
return BuiltIn().run_keyword(name, row, *args)
before = len(table)
table.filter_all(condition)
after = len(table)
self.logger.info("Removed %d row(s)", before - after)
def map_column_values(self, table: Table, column: Column, name: str, *args):
"""Run a keyword for each cell in a given column, and replace its content with
the return value.
Can be used to easily convert column types or values in-place.
:param table: Table to modify.
:param column: Column to modify.
:param name: Mapping keyword name.
:param args: Additional keyword arguments. (optional)
The cell value will be given as the first argument to the mapping keyword.
Examples:
.. code-block:: robotframework
# Convert all columns values to a different type
Map column values ${table} Price Convert to integer
# Look up values with a custom keyword
Map column values ${table} User Map user ID to name
"""
self._requires_table(table)
values = []
for index in table.index:
cell = table.get_cell(index, column)
output = BuiltIn().run_keyword(name, cell, *args)
values.append(output)
table.set_column(column, values)
def filter_empty_rows(self, table: Table):
"""Remove all rows from a table which have only ``None`` values.
:param table: Table to filter
The filtering will be done in-place.
Example:
.. code-block:: robotframework
Filter empty rows ${table}
"""
self._requires_table(table)
empty = []
for idx, row in table.iter_lists():
if all(value is None for value in row):
empty.append(idx)
table.delete_rows(empty)
def trim_empty_rows(self, table: Table):
"""Remove all rows from the *end* of a table
which have only ``None`` as values.
:param table: Table to filter
The filtering will be done in-place.
Example:
.. code-block:: robotframework
Trim empty rows ${table}
"""
self._requires_table(table)
empty = []
for idx in reversed(table.index):
row = table[idx]
if any(value is not None for value in row):
break
empty.append(idx)
table.delete_rows(empty)
def trim_column_names(self, table: Table):
"""Remove all extraneous whitespace from column names.
:param table: Table to filter
The filtering will be done in-place.
Example:
.. code-block:: robotframework
# This example will take colums such as:
# "One", "Two ", " Three "
# and trim them to become the below:
# "One", "Two", "Three"
Trim column names ${table}
"""
self._requires_table(table)
table.columns = [
column.strip() if isinstance(column, str) else column
for column in table.columns
]
@keyword("Read table from CSV")
def read_table_from_csv(
self,
path: str,
header: Optional[bool] = None,
columns: Optional[List[str]] = None,
dialect: Optional[Union[str, Dialect]] = None,
delimiters: Optional[str] = None,
column_unknown: str = "Unknown",
encoding: Optional[str] = None,
) -> Table:
"""Read a CSV file as a table.
:param path: Path to CSV file
:param header: CSV file includes header
:param columns: Names of columns in resulting table
:param dialect: Format of CSV file
:param delimiters: String of possible delimiters
:param column_unknown: Column name for unknown fields
:param encoding: Text encoding for input file,
uses system encoding by default
:return: Table object
By default attempts to deduce the CSV format and headers
from a sample of the input file. If it's unable to determine
the format automatically, the dialect and header will
have to be defined manually.
Builtin ``dialect`` values are ``excel``, ``excel-tab``, and ``unix``,
and ``header`` is boolean argument (``True``/``False``). Optionally a
set of valid ``delimiters`` can be given as a string.
The ``columns`` argument can be used to override the names of columns
in the resulting table. The amount of columns must match the input
data.
If the source data has a header and rows have more fields than
the header defines, the remaining values are put into the column
given by ``column_unknown``. By default it has the value "Unknown".
Examples:
.. code-block:: robotframework
# Source dialect is deduced automatically
${table}= Read table from CSV export.csv
Log Found columns: ${table.columns}
# Source dialect is known and given explicitly
${table}= Read table from CSV export-excel.csv dialect=excel
Log Found columns: ${table.columns}
"""
sniffer = csv.Sniffer()
with open(path, newline="", encoding=encoding) as fd:
sample = fd.readline()
if dialect is None:
dialect_name = sniffer.sniff(sample, delimiters)
elif isinstance(dialect, Dialect):
dialect_name = dialect.value
else:
dialect_name = dialect
if header is None:
header = sniffer.has_header(sample)
with open(path, newline="", encoding=encoding) as fd:
if header:
reader = csv.DictReader(
fd, dialect=dialect_name, restkey=str(column_unknown)
)
else:
reader = csv.reader(fd, dialect=dialect_name)
rows = list(reader)
table = Table(rows, columns)
notebook_table(self.table_head(table, 10))
if header and column_unknown in table.columns:
self.logger.warning(
"CSV file (%s) had fields not defined in header, "
"which can be the result of a wrong dialect",
path,
)
return table
@keyword("Write table to CSV")
def write_table_to_csv(
self,
table: Table,
path: str,
header: bool = True,
dialect: Union[str, Dialect] = Dialect.Excel,
encoding: Optional[str] = None,
delimiter: Optional[str] = ",",
):
"""Write a table as a CSV file.
:param table: Table to write
:param path: Path to write to
:param header: Write columns as header to CSV file
:param dialect: The format of output CSV
:param encoding: Text encoding for output file,
uses system encoding by default
:param delimiter: Delimiter character between columns
Builtin ``dialect`` values are ``excel``, ``excel-tab``, and ``unix``.
Example:
.. code-block:: robotframework
${sheet}= Read worksheet as table orders.xlsx header=${TRUE}
Write table to CSV ${sheet} output.csv
"""
self._requires_table(table)
if isinstance(dialect, Dialect):
dialect_name = dialect.value
else:
dialect_name = dialect
with open(path, mode="w", newline="", encoding=encoding) as fd:
writer = csv.DictWriter(
fd, fieldnames=table.columns, dialect=dialect_name, delimiter=delimiter
)
if header:
writer.writeheader()
for row in table.iter_dicts(with_index=False):
writer.writerow(row) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Tables.py | 0.84124 | 0.303429 | Tables.py | pypi |
import logging
import time
from dataclasses import dataclass
from pathlib import Path
from typing import List
from PIL import Image
from PIL import ImageDraw
from PIL import ImageOps
from RPA.core.geometry import Region, to_point, to_region
from RPA.core.notebook import notebook_image
try:
from RPA.recognition import templates
HAS_RECOGNITION = True
except ImportError:
HAS_RECOGNITION = False
def to_image(obj):
"""Convert `obj` to instance of Pillow's Image class."""
if obj is None or isinstance(obj, Image.Image):
return obj
return Image.open(obj)
def clamp(minimum, value, maximum):
"""Clamp value between given minimum and maximum."""
return max(minimum, min(value, maximum))
def chunks(obj, size, start=0):
"""Convert `obj` container to list of chunks of `size`."""
return [obj[i : i + size] for i in range(start, len(obj), size)]
@dataclass
class RGB:
"""Container for a single RGB value."""
red: int
green: int
blue: int
@classmethod
def from_pixel(cls, value):
"""Create RGB value from pillow getpixel() return value."""
# RGB(A), ignore possible alpha channel
if isinstance(value, tuple):
red, green, blue = value[:3]
# Grayscale
else:
red, green, blue = [value] * 3
return cls(red, green, blue)
def luminance(self) -> int:
"""Approximate (perceived) luminance for RGB value."""
return (self.red * 2 + self.green * 3 + self.blue) // 6
class ImageNotFoundError(Exception):
"""Raised when template matching fails."""
class Images:
"""`Images` is a library for general image manipulation.
For image-based desktop automation, use the ``RPA.Desktop`` library.
**Coordinates**
The coordinates used in the library are pairs of x and y values that
represent pixels. The upper left corner of the image or screen
is (0, 0). The x-coordinate increases towards the right, and the y-coordinate
increases towards the bottom.
Regions are represented as tuples of (left, top, right, bottom). For example,
a 400 by 200-pixel region in the upper left corner would be (0, 0, 400, 200).
**Template matching**
Template matching refers to an operation where the (potential) location of
a smaller image is searched from a larger image. It can be used for verifying
certain conditions or locating UI elements for desktop or web automation.
**Requirements**
The default installation depends on `Pillow <https://python-pillow.org/>`_
library, which is used for general image manipulation operations.
For more robust and faster template matching, the library can use a combination
of `NumPy <https://numpy.org/>`_ and `OpenCV <https://opencv.org/>`_.
They can be installed by opting in to the recognition dependency:
``pip install rpaframework rpaframework-recognition``
**Examples**
**Robot Framework**
The `Images` library can be imported and used directly in Robot Framework,
for instance, for capturing screenshots or verifying something on the screen.
Desktop automation based on images should be done using the corresponding
desktop library, i.e. ``RPA.Desktop``.
.. code-block:: robotframework
*** Settings ***
Library RPA.Images
*** Keywords ***
Should show success
[Documentation] Raises ImageNotFoundError if success image is not on screen
Find template on screen ${CURDIR}${/}success.png
Save screenshot to results
[Documentation] Saves screenshot of desktop with unique name
${timestamp}= Get current date result_format=%H%M%S
Take screenshot filename=${OUTPUT_DIR}${/}desktop_${timestamp}.png
**Python**
.. code-block:: python
from RPA.Images import Images
def draw_matches_on_image(source, template):
matches = lib.find_template_in_image(source, template)
for match in matches:
lib.show_region_in_image(source, match)
source.save("matches.png")
""" # noqa: E501
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self):
self.logger = logging.getLogger(__name__)
self.matcher = TemplateMatcher()
def crop_image(self, image, region, filename=None) -> None:
"""Crop an existing image.
:param image: Image to crop
:param region: Region to crop image to
:param filename: Save cropped image to filename
"""
region = to_region(region)
image = to_image(image)
image = image.crop(region.as_tuple())
image.load()
if filename:
# Suffix isn't created automatically here
image.save(Path(filename).with_suffix(".png"), "PNG")
notebook_image(filename)
def find_template_in_image(
self, image, template, region=None, limit=None, tolerance=None
) -> List[Region]:
"""Attempt to find the template from the given image.
:param image: Path to image or Image instance, used to search from
:param template: Path to image or Image instance, used to search with
:param limit: Limit returned results to maximum of `limit`.
:param region: Area to search from. Can speed up search significantly.
:param tolerance: Tolerance for matching, value between 0.1 and 1.0
:return: List of matching regions
:raises ImageNotFoundError: No match was found
:raises ValueError: Template is larger than search region
"""
# Ensure images are in Pillow format
image = to_image(image)
template = to_image(template)
# Crop image if requested
if region is not None:
region = to_region(region)
image = image.crop(region.as_tuple())
# Verify template still fits in image
if template.size[0] > image.size[0] or template.size[1] > image.size[1]:
raise ValueError("Template is larger than search region")
# Strip alpha channels
if image.mode == "RGBA":
image = image.convert("RGB")
if template.mode == "RGBA":
template = template.convert("RGB")
# Do the actual search
start = time.time()
matches = self.matcher.match(image, template, limit, tolerance)
logging.info("Scanned image in %.2f seconds", time.time() - start)
if not matches:
raise ImageNotFoundError("No matches for given template")
# Convert region coördinates back to full-size coördinates
if region is not None:
for match in matches:
match.move(region.left, region.top)
return matches
def show_region_in_image(self, image, region, color="red", width=5) -> Image:
"""Draw a rectangle onto the image around the given region.
:param image: image to draw onto
:param region: coordinates for region or Region object
:param color: color of rectangle
:param width: line width of rectangle
:return: Image of the selected region
"""
image = to_image(image)
region = to_region(region)
draw = ImageDraw.Draw(image)
draw.rectangle(region.as_tuple(), outline=color, width=int(width))
return image
def get_pixel_color_in_image(self, image, point) -> RGB:
"""Get the RGB value of a pixel in the image.
:param image: image to get pixel from
:param point: coordinates for pixel or Point object
:return: RGB value of pixel in image
"""
point = to_point(point)
pixel = image.getpixel(point.as_tuple())
return RGB.from_pixel(pixel)
class TemplateMatcher:
"""Container class for different template matching methods."""
DEFAULT_TOLERANCE = 0.95 # Tolerance for correlation matching methods
LIMIT_FAILSAFE = 256 # Fail-safe limit of maximum match count
def __init__(self):
self.logger = logging.getLogger(__name__)
self._tolerance = self.DEFAULT_TOLERANCE
self._tolerance_warned = False
@property
def tolerance(self) -> float:
return self._tolerance
@tolerance.setter
def tolerance(self, value) -> float:
self._tolerance = clamp(0.10, value, 1.00)
def match(self, image, template, limit=None, tolerance=None) -> List[Region]:
"""Attempt to find the template in the given image.
:param image: image to search from
:param template: image to search with
:param limit: maximum number of returned matches
:param tolerance: minimum correlation factor between template and image
:return: list of regions that match the criteria
"""
if HAS_RECOGNITION:
return self._find_recognition(image, template, limit, tolerance)
else:
return self._find_exact(image, template, limit, tolerance)
def _find_recognition(
self, image, template, limit=None, tolerance=None
) -> List[Region]:
"""Find template using recognition module."""
if tolerance is None:
tolerance = self._tolerance
confidence = tolerance * 100.0
return templates.find(image, template, limit=limit, confidence=confidence)
def _find_exact(self, image, template, limit=None, tolerance=None) -> List[Region]:
"""Fallback finder when no recognition module available."""
if tolerance is not None and not self._tolerance_warned:
self._tolerance_warned = True
self.logger.warning(
"Template matching tolerance not supported for current search method"
)
matches = []
for match in self._iter_matches(image, template):
matches.append(match)
if limit is not None and len(matches) >= int(limit):
break
elif len(matches) >= self.LIMIT_FAILSAFE:
self.logger.warning(
"Reached maximum of %d matches", self.LIMIT_FAILSAFE
)
break
return matches
def _iter_matches(self, image, template) -> Region:
"""Brute-force search for template image in larger image.
Use optimized string search for finding the first row and then
check if whole template matches.
TODO: Generalize string-search algorithm to work in two dimensions
"""
image = ImageOps.grayscale(image)
template = ImageOps.grayscale(template)
template_width, template_height = template.size
template_rows = chunks(tuple(template.getdata()), template_width)
image_width, _ = image.size
image_rows = chunks(tuple(image.getdata()), image_width)
for image_y, image_row in enumerate(image_rows[: -len(template_rows)]):
for image_x in self._search_string(image_row, template_rows[0]):
match = True
for match_y, template_row in enumerate(template_rows[1:], image_y):
match_row = image_rows[match_y][image_x : image_x + template_width]
if template_row != match_row:
match = False
break
if match:
yield Region.from_size(
image_x, image_y, template_width, template_height
)
def _search_string(self, text, pattern) -> int:
"""Python implementation of Knuth-Morris-Pratt string search algorithm."""
pattern_len = len(pattern)
# Build table of shift amounts
shifts = [1] * (pattern_len + 1)
shift = 1
for idx in range(pattern_len):
while shift <= idx and pattern[idx] != pattern[idx - shift]:
shift += shifts[idx - shift]
shifts[idx + 1] = shift
# Do the actual search
start_idx = 0
match_len = 0
for char in text:
while (
match_len == pattern_len
or match_len >= 0
and pattern[match_len] != char
):
start_idx += shifts[match_len]
match_len -= shifts[match_len]
match_len += 1
if match_len == pattern_len:
yield start_idx | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Images.py | 0.943919 | 0.517388 | Images.py | pypi |
from functools import wraps
import itertools
import logging
from netsuitesdk import NetSuiteConnection
from netsuitesdk.internal.client import NetSuiteClient
from netsuitesdk.internal.utils import PaginatedSearch
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
from RPA.core.helpers import required_env
from RPA.RobotLogListener import RobotLogListener
try:
BuiltIn().import_library("RPA.RobotLogListener")
except RobotNotRunningError:
pass
def ns_instance_required(f):
@wraps(f)
def wrapper(*args, **kwargs):
if args[0].client is None:
raise NetsuiteAuthenticationError("Authentication is not completed")
return f(*args, **kwargs)
return wrapper
class NetsuiteAuthenticationError(Exception):
"Error when authenticated Netsuite instance does not exist."
class Netsuite:
"""`Netsuite` is a library for accessing Netsuite using NetSuite SOAP web service SuiteTalk.
The library extends the `netsuitesdk library`_.
More information available at `NetSuite SOAP webservice SuiteTalk`_.
.. _netsuitesdk library:
https://github.com/fylein/netsuite-sdk-py
.. _NetSuite SOAP webservice SuiteTalk:
http://www.netsuite.com/portal/platform/developer/suitetalk.shtml
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.Netsuite
Library RPA.Excel.Files
Library RPA.Tables
Task Setup Authorize Netsuite
*** Tasks ***
Get data from Netsuite and Store into Excel files
${accounts}= Get Accounts account_type=_expense
${accounts}= Create table ${accounts}
Create Workbook
Append Rows To Worksheet ${accounts}
Save Workbook netsuite_accounts.xlsx
Close Workbook
${bills}= Get Vendor Bills
${bills}= Create table ${bills}
Create Workbook
Append Rows To Worksheet ${bills}
Save Workbook netsuite_bills.xlsx
Close Workbook
*** Keywords ***
Authorize Netsuite
${secrets}= Get Secret netsuite
Connect
... account=${secrets}[ACCOUNT]
... consumer_key=${secrets}[CONSUMER_KEY]
... consumer_secret=${secrets}[CONSUMER_KEY]
... token_key=${secrets}[CONSUMER_SECRET]
... token_secret=${secrets}[TOKEN_KEY]
**Python**
.. code-block:: python
from RPA.Netsuite import Netsuite
ns = Netsuite()
ns.connect()
accounts = ns.get_accounts()
currencies = ns.get_currencies()
""" # noqa: E501
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self) -> None:
self.client = None
self.account = None
self.logger = logging.getLogger(__name__)
listener = RobotLogListener()
listener.register_protected_keywords(
["RPA.Netsuite.connect", "RPA.Netsuite.login"]
)
def connect(
self,
account: str = None,
consumer_key: str = None,
consumer_secret: str = None,
token_key: str = None,
token_secret: str = None,
) -> None:
"""Connect to Netsuite with credentials from environment
variables.
Parameters are not logged into Robot Framework log.
:param account: parameter or environment variable `NS_ACCOUNT`
:param consumer_key: parameter or environment variable `NS_CONSUMER_KEY`
:param consumer_secret: parameter or environment variable `NS_CONSUMER_SECRET`
:param token_key: parameter or environment variable `NS_TOKEN_KEY`
:param token_secret: parameter or environment variable `NS_TOKEN_SECRET`
"""
if account is None:
self.account = required_env("NS_ACCOUNT")
else:
self.account = account
NS_CONSUMER_KEY = required_env("NS_CONSUMER_KEY", consumer_key)
NS_CONSUMER_SECRET = required_env("NS_CONSUMER_SECRET", consumer_secret)
NS_TOKEN_KEY = required_env("NS_TOKEN_KEY", token_key)
NS_TOKEN_SECRET = required_env("NS_TOKEN_SECRET", token_secret)
self.client = NetSuiteConnection(
account=self.account,
consumer_key=NS_CONSUMER_KEY,
consumer_secret=NS_CONSUMER_SECRET,
token_key=NS_TOKEN_KEY,
token_secret=NS_TOKEN_SECRET,
)
def login(
self,
account: str = None,
email: str = None,
password: str = None,
role: str = None,
appid: str = None,
) -> None:
"""Login to Netsuite with credentials from environment variables
Parameters are not logged into Robot Framework log.
:param account: parameter or environment variable `NS_ACCOUNT`
:param email: parameter or environment variable `NS_EMAIL`
:param password: parameter or environment variable `NS_PASSWORD`
:param role: parameter or environment variable `NS_ROLE`
:param appid: parameter or environment variable `NS_APPID`
"""
if account is None:
account = required_env("NS_ACCOUNT", self.account)
if account is None:
raise NetsuiteAuthenticationError("Authentication is not completed")
NS_EMAIL = required_env("NS_EMAIL", email)
NS_PASSWORD = required_env("NS_PASSWORD", password)
NS_ROLE = required_env("NS_ROLE", role)
NS_APPID = required_env("NS_APPID", appid)
if self.client is None:
self.client = NetSuiteClient(account=account)
self.client.login(
email=NS_EMAIL,
password=NS_PASSWORD,
role=NS_ROLE,
application_id=NS_APPID,
)
@ns_instance_required
def netsuite_get(
self, record_type: str = None, internal_id: str = None, external_id: str = None
) -> list:
"""Get all records of given type and internalId and/or externalId.
:param record_type: type of Netsuite record to get
:param internal_id: internalId of the type, default None
:param external_id: external_id of the type, default None
:raises ValueError: if record_type is not given
:return: records as a list or None
"""
if record_type is None:
raise ValueError("Parameter 'record_type' is required for kw: netsuite_get")
if internal_id is None and external_id is None:
raise ValueError(
"Parameter 'internal_id' or 'external_id' "
" is required for kw: netsuite_get"
)
kwargs = {"recordType": record_type}
if internal_id is not None:
kwargs["internalId"] = internal_id
if external_id is not None:
kwargs["externalId"] = external_id
return self.client.get(**kwargs)
@ns_instance_required
def netsuite_get_all(self, record_type: str) -> list:
"""Get all records of given type.
:param record_type: type of Netsuite record to get
:raises ValueError: if record_type is not given
:return: records as a list or None
"""
if record_type is None:
raise ValueError(
"Parameter 'record_type' is required for kw: netsuite_get_all"
)
return self.client.getAll(recordType=record_type)
def netsuite_search(
self,
type_name: str,
search_value: str,
operator: str = "contains",
page_size: int = 5,
) -> PaginatedSearch:
"""Search Netsuite for value from a type. Default operator is
`contains`.
:param type_name: search target type name
:param search_value: what to search for within type
:param operator: name of the operation, defaults to "contains"
:param page_size: result items within one page, defaults to 5
:return: paginated search object
"""
# pylint: disable=E1101
record_type_search_field = self.client.SearchStringField(
searchValue=search_value, operator=operator
)
basic_search = self.client.basic_search_factory(
type_name, recordType=record_type_search_field
)
paginated_search = PaginatedSearch(
client=self.client,
type_name=type_name,
basic_search=basic_search,
pageSize=page_size,
)
return paginated_search
def netsuite_search_all(
self, type_name: str, page_size: int = 20
) -> PaginatedSearch:
"""Search Netsuite for a type results.
:param type_name: search target type name
:param page_size: result items within one page, defaults to 5
:return: paginated search object
"""
paginated_search = PaginatedSearch(
client=self.client, type_name=type_name, pageSize=page_size
)
return paginated_search
@ns_instance_required
def get_accounts(self, count: int = 100, account_type: str = None) -> list:
"""Get Accounts of any type or specified type.
:param count: number of Accounts to return, defaults to 100
:param account_type: if None returns all account types, example. "_expense",
defaults to None
:return: accounts
"""
all_accounts = list(
itertools.islice(self.client.accounts.get_all_generator(), count)
)
if account_type is None:
return all_accounts
return [a for a in all_accounts if a["acctType"] == account_type]
@ns_instance_required
def get_currency(self, currency_id: str) -> object:
"""Get all a Netsuite Currency by its ID
:param currency_id: ID of the currency to get
:return: currency
"""
return self.client.currencies.get(internalId=currency_id)
@ns_instance_required
def get_currencies(self) -> list:
"""Get all Netsuite Currencies
:return: currencies
"""
return self.client.currencies.get_all()
@ns_instance_required
def get_locations(self) -> list:
"""Get all Netsuite Locations
:return: locations
"""
return self.client.locations.get_all()
@ns_instance_required
def get_departments(self) -> list:
"""Get all Netsuite Departments
:return: departments
"""
return self.client.departments.get_all()
@ns_instance_required
def get_classifications(self) -> list:
"""Get all Netsuite Classifications
:return: classifications
"""
return self.client.classifications.get_all()
@ns_instance_required
def get_vendors(self, count: int = 10) -> list:
"""Get list of vendors
:param count: number of vendors to return, defaults to 10
:return: list of vendors
"""
return list(itertools.islice(self.client.vendors.get_all_generator(), count))
@ns_instance_required
def get_vendor_bills(self, count: int = 10) -> list:
"""Get list of vendor bills
:param count: number of vendor bills to return, defaults to 10
:return: list of vendor bills
"""
return list(
itertools.islice(self.client.vendor_bills.get_all_generator(), count)
) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Netsuite.py | 0.69181 | 0.15034 | Netsuite.py | pypi |
import functools
from itertools import count
from typing import Any
from RPA.application import BaseApplication, catch_com_error, to_path, to_str_path
def requires_workbook(func):
"""Ensures a workbook is open."""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if self.workbook is None:
raise ValueError("No workbook open")
return func(self, *args, **kwargs)
return wrapper
class Application(BaseApplication):
"""`Excel.Application` is a library for controlling the Excel application.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.Excel.Application
Task Setup Open Application
Task Teardown Quit Application
*** Tasks ***
Manipulate Excel application
Open Workbook workbook.xlsx
Set Active Worksheet sheetname=new stuff
Write To Cells row=1
... column=1
... value=my data
Save Excel
Run Excel Macro
Open Workbook orders_with_macro.xlsm
Run Macro Sheet1.CommandButton1_Click
Export Workbook as PDF
Open Workbook workbook.xlsx
Export as PDF workbook.pdf
**Python**
.. code-block:: python
from RPA.Excel.Application import Application
app = Application()
app.open_application()
app.open_workbook('workbook.xlsx')
app.set_active_worksheet(sheetname='new stuff')
app.write_to_cells(row=1, column=1, value='new data')
app.save_excel()
app.quit_application()
"""
APP_DISPATCH = "Excel.Application"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.workbook = None
self.worksheet = None
@property
def _active_document(self):
return self.workbook
def _deactivate_document(self):
self.workbook = None
self.worksheet = None
def add_new_workbook(self) -> None:
"""Adds new workbook for Excel application"""
with catch_com_error():
self.workbook = self.app.Workbooks.Add()
def open_workbook(self, filename: str) -> None:
"""Open Excel by filename
By default sets active worksheet to sheet number 1
:param filename: path to filename
"""
if not self._app:
self.open_application()
path = to_path(filename)
if not path.is_file():
raise FileNotFoundError(f"{str(path)!r} doesn't exist")
path = str(path)
self.logger.info("Opening workbook: %s", path)
with catch_com_error():
try:
self.workbook = self.app.Workbooks(path)
except Exception as exc: # pylint: disable=broad-except
self.logger.debug(str(exc))
self.logger.info("Trying to open workbook by another method...")
self.workbook = self.app.Workbooks.Open(path)
self.set_active_worksheet(sheetnumber=1)
self.logger.debug("Current workbook: %s", self.workbook)
@requires_workbook
def set_active_worksheet(
self, sheetname: str = None, sheetnumber: int = None
) -> None:
"""Set active worksheet by either its sheet number or name
:param sheetname: name of Excel sheet, defaults to None
:param sheetnumber: index of Excel sheet, defaults to None
"""
with catch_com_error():
if sheetnumber:
self.worksheet = self.workbook.Worksheets(int(sheetnumber))
elif sheetname:
self.worksheet = self.workbook.Worksheets(sheetname)
def add_new_sheet(self, sheetname: str, create_workbook: bool = True) -> None:
"""Add new worksheet to workbook. Workbook is created by default if
it does not exist.
:param sheetname: name for sheet
:param create_workbook: create workbook if True, defaults to True
:raises ValueError: error is raised if workbook does not exist and
`create_workbook` is False
"""
if not self.workbook:
if not create_workbook:
raise ValueError("No workbook open")
self.add_new_workbook()
self.logger.info("Adding sheet: %s", sheetname)
with catch_com_error():
last = self.app.Worksheets(self.app.Worksheets.Count)
self.worksheet = self.app.Worksheets.Add(After=last)
self.worksheet.Name = sheetname
def find_first_available_row(
self, worksheet: Any = None, row: int = 1, column: int = 1
) -> Any:
"""Find first available free row
:param worksheet: worksheet to handle, defaults to active worksheet if None
:param row: starting row for search, defaults to 1
:param column: starting column for search, defaults to 1
:return: row or None
"""
cell = self.find_first_available_cell(worksheet, row, column)
return cell
@requires_workbook
def find_first_available_cell(
self, worksheet: Any = None, row: int = 1, column: int = 1
) -> Any:
"""Find first available free cell
:param worksheet: worksheet to handle, defaults to active worksheet if None
:param row: starting row for search, defaults to 1
:param column: starting column for search, defaults to 1
:return: tuple (row, column) or (None, None) if not found
"""
if worksheet:
self.set_active_worksheet(worksheet)
with catch_com_error():
for current_row in count(int(row)):
cell = self.worksheet.Cells(current_row, column)
if cell.Value is None:
return current_row, column
return None, None
@requires_workbook
def write_to_cells(
self,
worksheet: Any = None,
row: int = None,
column: int = None,
value: str = None,
number_format: str = None,
formula: str = None,
) -> None:
"""Write value, number_format and/or formula into cell.
:param worksheet: worksheet to handle, defaults to active worksheet if None
:param row: target row, defaults to None
:param column: target row, defaults to None
:param value: possible value to set, defaults to None
:param number_format: possible number format to set, defaults to None
:param formula: possible format to set, defaults to None
:raises ValueError: if cell is not given
"""
if row is None or column is None:
raise ValueError("No cell was given")
if worksheet:
self.set_active_worksheet(worksheet)
with catch_com_error():
cell = self.worksheet.Cells(int(row), int(column))
if number_format:
cell.NumberFormat = number_format
if value:
cell.Value = value
if formula:
cell.Formula = formula
@requires_workbook
def read_from_cells(
self,
worksheet: Any = None,
row: int = None,
column: int = None,
) -> str:
"""Read value from cell.
:param worksheet: worksheet to handle, defaults to active worksheet if None
:param row: target row, defaults to None
:param column: target row, defaults to None
:raises ValueError: if cell is not given
"""
if row is None or column is None:
raise ValueError("No cell was given")
if worksheet:
self.set_active_worksheet(worksheet)
with catch_com_error():
cell = self.worksheet.Cells(int(row), int(column))
return cell.Value
@requires_workbook
def save_excel(self) -> None:
"""Saves Excel file"""
with catch_com_error():
self.workbook.Save()
@requires_workbook
def save_excel_as(
self, filename: str, autofit: bool = False, file_format=None
) -> None:
"""Save Excel with name if workbook is open
:param filename: where to save file
:param autofit: autofit cell widths if True, defaults to False
:param file_format: format of file
**Note:** Changing the file extension for the path does not
affect the actual format. To use an older format, use
the ``file_format`` argument with one of the following values:
https://docs.microsoft.com/en-us/office/vba/api/excel.xlfileformat
Examples:
.. code-block:: robotframework
# Save workbook in modern format
Save excel as orders.xlsx
# Save workbook in Excel 97 format (format from above URL)
Save excel as legacy.xls file_format=${56}
"""
with catch_com_error():
if autofit:
self.worksheet.Rows.AutoFit()
self.worksheet.Columns.AutoFit()
path = to_str_path(filename)
if file_format is not None:
self.workbook.SaveAs(path, FileFormat=file_format)
else:
self.workbook.SaveAs(path)
@requires_workbook
def run_macro(self, macro_name: str, *args: Any):
"""Run Excel macro with given name
:param macro_name: macro to run
:param args: arguments to pass to macro
"""
with catch_com_error():
self.app.Application.Run(f"'{self.workbook.Name}'!{macro_name}", *args)
def export_as_pdf(self, pdf_filename: str, excel_filename: str = None):
"""Export Excel as PDF file
If Excel filename is not given, the currently open workbook
will be exported as PDF.
:param pdf_filename: PDF filename to save
:param excel_filename: Excel filename to open
"""
if excel_filename:
self.open_workbook(excel_filename)
else:
if not self.workbook:
raise ValueError("No workbook open, can't export PDF")
with catch_com_error():
pdf_path = to_str_path(pdf_filename)
self.workbook.ExportAsFixedFormat(0, pdf_path) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Excel/Application.py | 0.82176 | 0.201656 | Application.py | pypi |
import time
from datetime import datetime
from pathlib import Path
from typing import Any, List, Optional, Union
from RPA.application import BaseApplication, COMError
from RPA.Email.common import counter_duplicate_path
class Application(BaseApplication):
# pylint: disable=C0301
"""`Outlook.Application` is a library for controlling the Outlook application.
**About Email Filtering**
Emails can be filtered according to specification set by Restrict method of the
Item class https://docs.microsoft.com/en-us/office/vba/api/outlook.items.restrict.
Couple of examples:
.. code-block:: robotframework
Get Emails
... email_filter=[Subject]='test email'
Move Emails
... email_filter=[SenderEmailAddress]='hello@gmail.com'
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.Outlook.Application
Task Setup Open Application
Suite Teardown Quit Application
*** Variables ***
${RECIPIENT} address@domain.com
*** Tasks ***
Send message
Send Message recipients=${RECIPIENT}
... subject=This is the subject
... body=This is the message body
.. attachments=approved.png
**Python**
.. code-block:: python
from RPA.Outlook.Application import Application
def send_message():
app = Application()
app.open_application()
app.send_message(
recipients='EMAILADDRESS_1, EMAILADDRESS_2',
subject='email subject',
body='email body message',
attachments='../orders.csv'
For more information, see: https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2007/bb219950(v=office.12)
""" # noqa: E501
APP_DISPATCH = "Outlook.Application"
def send_email(
self,
recipients: Union[str, List[str]],
subject: str,
body: str,
html_body: bool = False,
attachments: Optional[Union[str, List[str]]] = None,
save_as_draft: bool = False,
cc_recipients: Optional[Union[str, List[str]]] = None,
bcc_recipients: Optional[Union[str, List[str]]] = None,
) -> bool:
"""Send email with Outlook
:param recipients: list of addresses
:param subject: email subject
:param body: email body
:param html_body: True if body contains HTML, defaults to False
:param attachments: list of filepaths to include in the email, defaults to []
:param save_as_draft: email is saved as draft when `True`
:param cc_recipients: list of addresses for CC field, default None
:param bcc_recipients: list of addresses for BCC field, default None
:return: `True` if there were no errors
Example:
.. code-block:: python
library = Outlook()
library.open_application()
cc_recipients = ["recipient3@domain.com","recipient4@domain.com"]
library.send_email(
recipients="recipient1@domain.com",
cc_recipients=cc_recipients,
bcc_recipients="recipient3@domain.com;recipient4@domain.com",
subject="hello from Outlook",
body="empty body",
attachments=os.path.join(os.path.curdir, "example.xslx")
)
.. code-block:: robotframework
${cc}= Create List recipient3@domain.com recipient4@domain.com
Send Email
... recipients=recipient1@domain.com
... cc_repients=${cc}
... bcc_repients=recipient5@domain.com;recipient6@domain.com
... subject=hello from Outlook
... body=empty body
... attachments=${CURDIR}${/}example.xlsx
"""
# pylint: disable=no-member
attachments = attachments or []
if not isinstance(attachments, list):
attachments = str(attachments).split(";")
try:
mail = self.app.CreateItem(0)
mail.Subject = subject
self._add_all_recipients(mail, recipients, cc_recipients, bcc_recipients)
if html_body:
mail.HTMLBody = body
else:
mail.Body = body
self._add_attachments(mail, attachments)
if save_as_draft:
mail.Save()
self.logger.debug("Email draft saved")
else:
mail.Send()
self.logger.debug("Email sent")
# On non-Windows OS `COMError` is `Exception`.
except COMError as exc: # pylint: disable=broad-except
self.logger.error(
f"Mail {'saving' if save_as_draft else 'sending'} failed: %s", exc
)
return False
return True
def _add_all_recipients(self, email, recipients, cc_recipients, bcc_recipients):
if isinstance(recipients, list):
email.To = ";".join(recipients)
else:
email.To = recipients
if cc_recipients:
if isinstance(cc_recipients, list):
email.CC = ";".join(cc_recipients)
else:
email.CC = cc_recipients
if bcc_recipients:
if isinstance(bcc_recipients, list):
email.BCC = ";".join(bcc_recipients)
else:
email.BCC = bcc_recipients
def _add_attachments(self, email, attachments):
for attachment in attachments:
filepath = Path(attachment).absolute()
email.Attachments.Add(str(filepath))
def _is_email_too_old(self, email):
now = datetime.now().timestamp()
msg_time = email["ReceivedTimestamp"]
timediff = now - msg_time
return timediff > 30.0
def _check_for_matching(self, criterion, email):
crit_key, crit_val = criterion.split(":", 1)
crit_key = crit_key.upper()
crit_val = crit_val.lower()
match_found = None
if crit_key.upper() == "SUBJECT" and crit_val in email["Subject"].lower():
match_found = email
elif crit_key.upper() == "SENDER" and crit_val in email["Sender"].lower():
match_found = email
elif crit_key.upper() == "BODY" and crit_val in email["Body"].lower():
match_found = email
return match_found
def wait_for_email(
self, criterion: str = None, timeout: float = 5.0, interval: float = 1.0
) -> Any:
"""Wait for email matching `criterion` to arrive into mailbox.
:param criterion: email filter to wait for, defaults to ""
:param timeout: total time in seconds to wait for email, defaults to 5.0
:param interval: time in seconds for new check, defaults to 1.0
:return: list of messages or False
Possible wait criterias are: SUBJECT, SENDER and BODY
Example:
.. code-block:: robotframework
Wait for Email SUBJECT:rpa task calling timeout=300 interval=10
"""
if criterion is None:
self.logger.warning(
"Wait for message requires criteria for which message to wait for."
)
return False
end_time = time.time() + float(timeout)
namespace = self.app.GetNamespace("MAPI")
inbox = namespace.GetDefaultFolder(6)
while time.time() < end_time:
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
for msg in messages:
if type(msg).__name__ != "_MailItem":
continue
m = self._mail_item_to_dict(msg)
if self._is_email_too_old(m):
break
else:
match_found = self._check_for_matching(criterion, m)
if match_found:
return match_found
time.sleep(interval)
raise AssertionError("Did not find matching message in the Outlook inbox")
def get_emails(
self,
account_name: str = None,
folder_name: str = None,
email_filter: str = None,
save_attachments: bool = False,
attachment_folder: str = None,
sort: bool = False,
sort_key: str = None,
sort_descending: bool = True,
) -> List:
"""Get emails from a specified email folder. Can be used to save attachments.
:param account_name: needs to be given if there are shared accounts in use,
defaults to None
:param folder_name: target folder where to get emails from, default Inbox
:param email_filter: how to filter email, default no filter,
ie. all emails in folder
:param save_attachments: if attachments should be saved, defaults to False
:param attachment_folder: target folder where attachments are saved,
defaults to current directory
:param sort: if emails should be sorted, defaults to False
:param sort_key: needs to be given if emails are to be sorted
:param sort_descending: set to False for ascending sort, defaults to True
:return: list of emails (list of dictionaries)
Example:
.. code-block:: robotframework
${emails}= Get Emails
... email_folder=priority
... email_filter=[Subject]='incoming order'
... save_attachments=True
... attachment_folder=%{ROBOT_ROOT}${/}attachments
... sort=True
... sort_key=Received
... sort_descending=False
"""
folder = self._get_folder(account_name, folder_name)
folder_messages = folder.Items if folder else []
messages = []
if folder_messages and email_filter:
try:
folder_messages = folder_messages.Restrict(email_filter)
except Exception: # pylint: disable=broad-except
raise AttributeError( # pylint: disable=raise-missing-from
"Invalid email filter '%s'" % email_filter
)
if folder_messages and sort:
sort_key = sort_key or "ReceivedTime"
try:
folder_messages.Sort(f"[{sort_key}]", sort_descending)
except Exception: # pylint: disable=broad-except
raise AttributeError( # pylint: disable=raise-missing-from
"Invalid email sort key '%s'" % sort_key
)
for message in folder_messages:
if type(message).__name__ != "_MailItem":
continue
if save_attachments:
self.save_email_attachments(message.Attachments, attachment_folder)
messages.append(self._mail_item_to_dict(message))
return messages
def _get_folder(self, account_name, email_folder):
namespace = self.app.GetNamespace("MAPI")
if not account_name and not email_folder:
self.logger.warning("Getting items from default account inbox")
return namespace.GetDefaultFolder(6)
email_folder = email_folder or "Inbox"
if account_name:
account_folder = self._get_account_folder(namespace, account_name)
if account_folder:
folder = self._get_matching_folder(email_folder, account_folder)
else:
raise AttributeError("Did not find account by name '%s'" % account_name)
else:
folder = self._get_matching_folder(email_folder, None)
return folder if folder else []
def _get_account_folder(self, namespace, account_name):
account_folder = None
for f in namespace.Folders:
if f.Name == account_name:
account_folder = f
break
return account_folder
def _get_matching_folder(self, folder_name, folder=None):
if not folder or isinstance(folder, str):
folders = self.app.GetNamespace("MAPI").Folders
elif isinstance(folder, list):
folders = folder
else:
folders = folder.Folders
for f in folders:
if folder_name == f.Name:
self.logger.debug("Found matching folder: %s", f.Name)
return f
emails = self._get_matching_folder(folder_name, f)
if emails:
return emails
return None
def save_email_attachments(
self, attachments: Any, attachment_folder: str, overwrite: bool = False
) -> None:
"""Save email attachments.
Note. Keyword "Get Emails" can be also used to save attachments.
:param attachments: all attachments from email or single attachment
:param attachment_folder: target folder where attachments are saved,
defaults to current directory
:param overwrite: overwrite existing file if True, defaults to False
Example:
.. code-block:: robotframework
${emails} = Get Emails
... email_folder=priority
FOR ${email} IN @{emails}
FOR ${attachment} IN @{email}[Attachments]
IF ${attachment}[size] < 100000 # bytes
Save Email Attachments
... ${attachment}
... ${CURDIR}${/}attachments
ELSE IF ".pdf" in "${attachment}[filename]"
Save Email Attachments
... ${attachment}
... ${CURDIR}${/}attachments${/}pdf
END
END
END
"""
attachment_target = Path(attachment_folder) if attachment_folder else Path(".")
if isinstance(attachments, dict):
email_attachments = [attachments["item"]]
else:
email_attachments = attachments
for attachment in email_attachments:
file_path = (attachment_target / attachment.FileName).absolute()
if not overwrite:
file_path = counter_duplicate_path(file_path)
attachment.SaveAsFile(file_path)
def mark_email_as_read(self, email: Any, read: bool = True) -> None:
"""Mark email 'read' property. Can be used to mark email as unread.
:param email: target email
:param read: True marks email as Read, False as Unread
Example:
.. code-block:: robotframework
${emails}= Get Emails
# Mark all as read
FOR ${email} IN @{emails}
Mark Email As Read ${email}
END
# Mark all as unread
FOR ${email} IN @{emails}
Mark Email As Read ${email} False
END
"""
read_value = not read
if type(email).__name__ == "_MailItem":
email.UnRead = read_value
email.Save()
elif isinstance(email, dict):
email["object"].UnRead = read_value
email["object"].Save()
def move_emails(
self,
account_name: str = None,
source_folder: str = None,
email_filter: str = None,
target_folder: str = None,
) -> bool:
"""Move emails from source folder to target folder.
Use of "account_name" is recommended if there are shared accounts in use.
:param account_name: needs to be given if there are shared accounts in use,
defaults to None
:param source_folder: folder where source emails exist
:param email_filter: how to filter email, default no filter,
ie. all emails in folder
:param target_folder: folder where emails are moved into
:return: True if move operation was success, False if not
Example:
.. code-block:: robotframework
# moving messages from Inbox to target_folder
Move Emails
... target_folder=Processed Invoices
... email_filter=[Subject]='incoming invoice'
# moving messages from source_folder to target_folder
Move Emails
... source_folder=Incoming Invoices
... target_folder=Processed Invoices
... email_filter=[Subject]='incoming invoice'
"""
if not target_folder:
raise AttributeError("Can't move emails without target_folder")
folder = self._get_folder(account_name, source_folder)
folder_messages = folder.Items if folder else []
if folder_messages and email_filter:
try:
folder_messages = folder_messages.Restrict(email_filter)
except Exception: # pylint: disable=broad-except
raise AttributeError( # pylint: disable=raise-missing-from
"Invalid email filter '%s'" % email_filter
)
if not folder_messages:
self.logger.warning("Did not find emails to move")
return False
tf = self._get_folder(account_name, target_folder)
if not tf or tf.Name != target_folder:
self.logger.warning("Did not find target folder")
return False
self.logger.info("Found %d emails to move", len(folder_messages))
self.logger.info("Found target folder: %s", tf.Name)
for m in folder_messages:
m.UnRead = False
m.Move(tf)
m.Save()
return True
def _mail_item_to_dict(self, mail_item):
mi = mail_item
response = {
"Sender": self._get_sender_email_address(mi),
"To": [],
"CC": [],
"BCC": [],
"Subject": mi.Subject,
"Body": mi.Body,
"Attachments": [
{"filename": a.FileName, "size": a.Size, "item": a}
for a in mi.Attachments
],
"Size": mi.Size,
"object": mi,
}
rt = getattr(mail_item, "ReceivedTime", "<UNKNOWN>")
response["ReceivedTime"] = rt.isoformat() if rt != "<UNKNOWN>" else rt
response["ReceivedTimestamp"] = (
datetime(
rt.year, rt.month, rt.day, rt.hour, rt.minute, rt.second
).timestamp()
if rt
else None
)
so = getattr(mail_item, "SentOn", "<UNKNOWN>")
response["SentOn"] = so.isoformat() if so != "<UNKNOWN>" else so
self._handle_recipients(mi.Recipients, response)
return response
def _get_recipient_email_address(self, recipient):
email_address = None
try:
email_address = recipient.AddressEntry.GetExchangeUser().PrimarySmtpAddress
except Exception: # pylint: disable=broad-except
email_address = recipient.Address
return email_address
def _handle_recipients(self, recipients, response):
for r in recipients:
if r.Type == 1:
response["To"].append(
{
"name": r.Name,
"email": self._get_recipient_email_address(r),
}
)
elif r.Type == 2:
response["CC"].append(
{
"name": r.Name,
"email": self._get_recipient_email_address(r),
}
)
elif r.Type == 3:
response["BCC"].append(
{
"name": r.Name,
"email": self._get_recipient_email_address(r),
}
)
def _get_sender_email_address(self, mail_item):
mi = mail_item
return (
mi.Sender.GetExchangeUser().PrimarySmtpAddress
if mi.SenderEmailType == "EX"
else mi.SenderEmailAddress
)
def _address_entry_to_dict(self, address_entry):
ae = address_entry
return {"Name": ae.Name, "Address": ae.Address} | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Outlook/Application.py | 0.852168 | 0.170992 | Application.py | pypi |
import base64
import logging
import mimetypes
from typing import Dict, List
import requests
from RPA.JSON import JSONType
from RPA.RobotLogListener import RobotLogListener
class Nanonets:
"""Library to support `Nanonets <https://nanonets.com/>`_ service for intelligent document processing (IDP).
Library requires at the minimum `rpaframework` version **19.0.0**.
Service supports identifying fields in the documents, which can be given to the
service in multiple different file formats and via URL.
**Robot Framework example usage**
.. code-block:: robotframework
*** Settings ***
Library RPA.DocumentAI.Nanonets
Library RPA.Robocorp.Vault
*** Tasks ***
Identify document
${secrets}= Get Secret nanonets-auth
Set Authorization ${secrets}[apikey]
${result}= Predict File
... ${CURDIR}${/}files${/}eckero.jpg
... ${secrets}[receipts-model-id]
${fields}= Get Fields From Prediction Result ${result}
FOR ${field} IN @{fields}
Log To Console Label:${field}[label] Text:${field}[ocr_text]
END
${tables}= Get Tables From Prediction Result ${result}
FOR ${table} IN @{tables}
FOR ${rows} IN ${table}[rows]
FOR ${row} IN @{rows}
${cells}= Evaluate [cell['text'] for cell in $row]
Log To Console ROW:${{" | ".join($cells)}}
END
END
END
**Python example usage**
.. code-block:: python
from RPA.DocumentAI.Nanonets import Nanonets
from RPA.Robocorp.Vault import Vault
secrets = Vault().get_secret("nanonets-auth")
nanolib = Nanonets()
nanolib.set_authorization(secrets["apikey"])
result = nanolib.predict_file(file_to_scan, secrets["receipts-model-id"])
fields = nanolib.get_fields_from_prediction_result(result)
for field in fields:
print(f"Label: {field['label']} Text: {field['ocr_text']}")
tables = nanolib.get_tables_from_prediction_result(result)
for table in tables:
rpatable = Tables().create_table(table["rows"])
for row in table["rows"]:
cells = [cell["text"] for cell in row]
print(f"ROW: {' | '.join(cells)}")
""" # noqa: E501
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self):
self.logger = logging.getLogger(__name__)
self.base_url = "https://app.nanonets.com/api/v2"
self._request_headers = {"Content-Type": "application/json"}
self.apikey = None
listener = RobotLogListener()
listener.register_protected_keywords(
["RPA.DocumentAI.Nanonets.set_authorization"]
)
def _get_file_base64_and_mimetype(self, file_path: str):
with open(file_path, "rb") as image_file:
encoded_content = base64.b64encode(image_file.read())
return encoded_content.decode("utf-8"), mimetypes.guess_type(file_path)[0]
def set_authorization(self, apikey: str) -> None:
"""Set Nanonets request headers with key related to API.
:param apikey: key related to the API
Robot Framework example:
.. code-block:: robotframework
${secrets}= Get Secret nanonets-auth
Set Authorization ${secrets}[apikey]
Python example:
.. code-block:: python
secrets = Vault().get_secret("nanonets-auth")
nanolib = Nanonets()
nanolib.set_authorization(secrets["apikey"])
"""
self.apikey = apikey
def ocr_fulltext(self, filename: str, filepath: str) -> List:
"""OCR fulltext a given file. Returns words and full text.
Filename and filepath needs to be given separately.
:param filename: name of the file
:param filepath: path of the file
:return: the result in a list format
Robot Framework example:
.. code-block:: robotframework
${results}= OCR Fulltext
... invoice.pdf
... ${CURDIR}${/}invoice.pdf
FOR ${result} IN @{results}
Log To Console Filename: ${result}[filename]
FOR ${pagenum} ${page} IN ENUMERATE @{result.pagedata} start=1
Log To Console Page ${pagenum} raw Text: ${page}[raw_text]
END
END
Python example:
.. code-block:: python
results = nanolib.ocr_fulltext("IMG_8277.jpeg", "./IMG_8277.jpeg")
for result in results:
print(f"FILENAME: {result['filename']}")
for page in result["page_data"]:
print(f"Page {page['page']+1}: {page['raw_text']}")
"""
_, mime = self._get_file_base64_and_mimetype(filepath)
# pylint: disable=R1732
files = [("file", (filename, open(filepath, "rb"), mime))]
response = requests.request(
"POST",
f"{self.base_url}/OCR/FullText",
files=files,
auth=requests.auth.HTTPBasicAuth(self.apikey, ""),
)
response.raise_for_status()
return response.json()["results"]
def get_all_models(self) -> Dict:
"""Get all available models related to the API key.
:return: object containing available models
Robot Framework example:
.. code-block:: robotframework
${models}= Get All Models
FOR ${model} IN @{models}
Log To Console Model ID: ${model}[model_id]
Log To Console Model Type: ${model}[model_type]
END
Python example:
.. code-block:: python
models = nanolib.get_all_models()
for model in models:
print(f"model id: {model['model_id']}")
print(f"model type: {model['model_type']}")
"""
response = requests.request(
"GET",
f"{self.base_url}/ImageCategorization/Models/",
auth=requests.auth.HTTPBasicAuth(self.apikey, ""),
)
response.raise_for_status()
return response.json()
def predict_file(self, filepath: str, model_id: str) -> JSONType:
"""Get prediction result for a file by a given model id.
:param filepath: filepath to the file
:param model_id: id of the Nanonets model to categorize a file
:return: the result in a list format
Robot Framework example:
.. code-block:: robotframework
${result}= Predict File ./document.pdf ${MODEL_ID}
${fields}= Get Fields From Prediction Result ${result}
FOR ${field} IN @{fields}
Log To Console Label:${field}[label] Text:${field}[ocr_text]
END
${tables}= Get Tables From Prediction Result ${result}
FOR ${table} IN @{tables}
FOR ${rows} IN ${table}[rows]
FOR ${row} IN @{rows}
${cells}= Evaluate [cell['text'] for cell in $row]
Log To Console ROW:${{" | ".join($cells)}}
END
END
END
Python example:
.. code-block:: python
result = nanolib.predict_file("./docu.pdf", secrets["receipts-model-id"])
fields = nanolib.get_fields_from_prediction_result(result)
for field in fields:
print(f"Label: {field['label']} Text: {field['ocr_text']}")
tables = nanolib.get_tables_from_prediction_result(result)
for table in tables:
for row in table["rows"]:
cells = [cell["text"] for cell in row]
print(f"ROW: {' | '.join(cells)}")
"""
url = f"{self.base_url}/OCR/Model/{model_id}/LabelFile/"
# pylint: disable=R1732
data = {"file": open(filepath, "rb")}
response = requests.post(
url,
headers={},
auth=requests.auth.HTTPBasicAuth(self.apikey, ""),
files=data,
)
response.raise_for_status()
return response.json()
def get_fields_from_prediction_result(self, prediction: JSONType) -> List:
"""Helper keyword to get found fields from a prediction result.
For example. see ``Predict File`` keyword
:param prediction: prediction result dictionary
:return: list of found fields
"""
return [
item
for item in prediction["result"][0]["prediction"]
if "type" in item.keys() and item["type"] == "field"
]
def get_tables_from_prediction_result(self, prediction: JSONType) -> List:
"""Helper keyword to get found tables from a prediction result.
For another example. see ``Predict File`` keyword
:param prediction: prediction result dictionary
:return: list of found tables
Robot Framework example:
.. code-block:: robotframework
# It is possible to create ``RPA.Tables`` compatible tables from the result
${tables}= Get Tables From Prediction Result ${result}
FOR ${table} IN @{tables}
${rpatable}= Create Table ${table}[rows]
FOR ${row} IN @{rpatable}
Log To Console ${row}
END
END
Python example:
.. code-block:: python
# It is possible to create ``RPA.Tables`` compatible tables from the result
tables = nanolib.get_tables_from_prediction_result(result)
for table in tables:
rpatable = Tables().create_table(table["rows"])
for row in rpatable:
print(row)
"""
tables = [
item
for item in prediction["result"][0]["prediction"]
if "type" in item.keys() and item["type"] == "table"
]
for table in tables:
table["rows"] = []
row = []
last_row = 1
for cell in table["cells"]:
if len(row) == 0 or last_row == cell["row"]:
row.append(cell)
elif last_row != cell["row"]:
table["rows"].append(row)
row = [cell]
last_row = cell["row"]
if len(row) > 0:
table["rows"].append(row)
return tables | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/DocumentAI/Nanonets.py | 0.758063 | 0.310028 | Nanonets.py | pypi |
import functools
import logging
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
from robot.api.deco import keyword, library
from RPA.JSON import JSONType
from RPA.Robocorp.Vault import Vault
from RPA.Robocorp.utils import PathType
from RPA.RobotLogListener import RobotLogListener
lib_vault = Vault()
SecretType = Optional[Union[str, Path, Tuple, List, Dict]]
ResultType = JSONType
try:
from google.cloud import documentai_v1 as documentai
except ImportError:
pass
else:
ResultType = Union[ResultType, documentai.Document]
class EngineName(Enum):
"""Supported engines to process documents with."""
GOOGLE = "google"
BASE64 = "base64ai"
NANONETS = "nanonets"
@library
class DocumentAI:
"""Wrapper library offering generic keywords for initializing, scanning and
retrieving results as fields from documents (PDF, PNG etc.).
Library requires at the minimum `rpaframework` version **19.0.0**.
This is a helper facade for the following libraries:
- RPA.Cloud.Google (requires `rpaframework-google`)
- RPA.DocumentAI.Base64AI
- RPA.DocumentAI.Nanonets
Where the following steps are required:
1. Engine initialization: ``Init Engine``
2. Document scan: ``Predict``
3. Result retrieval: ``Get Result``
So no matter the engine you're using, the very same keywords can be used, as only
the passed parameters will differ (please check the docs on each library for
particularities). Once initialized, you can jump between the engines with
``Switch Engine``. Before scanning documents, you must configure the service first,
with a model to scan the files with and an API key for authorizing the access.
See Portal example: https://robocorp.com/portal/robot/robocorp/example-document-ai
**Example: Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.DocumentAI
*** Tasks ***
Scan Documents
Init Engine base64ai vault=document_ai:base64ai
Init Engine nanonets vault=document_ai:nanonets
Switch Engine base64ai
Predict invoice.png
${data} = Get Result
Log List ${data}
Switch Engine nanonets
Predict invoice.png model=858e4b37-6679-4552-9481-d5497dfc0b4a
${data} = Get Result
Log List ${data}
**Example: Python**
.. code-block:: python
from RPA.DocumentAI import DocumentAI, EngineName
lib_docai = DocumentAI()
lib_docai.init_engine(
EngineName.GOOGLE, vault="document_ai:serviceaccount", region="eu"
)
lib_docai.predict(
"invoice.pdf", model="df1d166771005ff4",
project_id="complete-agency-347912", region="eu"
)
print(lib_docai.get_result())
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self):
listener = RobotLogListener()
listener.register_protected_keywords(["RPA.DocumentAI.init_engine"])
self.logger = logging.getLogger(__name__)
self._active_engine: Optional[EngineName] = None
self._engines: Dict[EngineName, Any] = {}
self._results: Dict[EngineName, ResultType] = {}
def _check_engine(self):
if not self._active_engine:
raise RuntimeError(
"can't execute without an engine set, please run"
" `Init Engine <name> ...` first"
)
@property
def engine(self) -> Any:
self._check_engine()
return self._engines[self._active_engine]
@property
def result(self) -> ResultType:
self._check_engine()
result = self._results.get(self._active_engine)
if not result:
raise RuntimeError(
"there's no result obtained yet, please run"
" `Predict <location> ...` first"
)
return result
def _get_secret_value(
self, secret: SecretType, vault: Optional[Dict]
) -> SecretType:
if vault:
assert (
len(vault) == 1
), "`vault` should contain one key (Vault name) and one value (secret key)"
name, key = list(vault.items())[0]
secrets = lib_vault.get_secret(name)
self.logger.debug("Using secret from the Vault.")
return secrets[key]
if not secret:
self.logger.debug("Using secret implicitly from environment variable(s).")
return None
secret_path = (
Path(secret).expanduser().resolve() if isinstance(secret, str) else None
)
if secret_path and secret_path.exists():
# File-based secret, don't return its content, but its file location
# as object instead. (the engine itself knows how to use it from there)
self.logger.debug("Using secret from local file path at: %s", secret_path)
return secret_path
self.logger.debug("Using secret as provided.")
return secret # secret in plain text or object
def _init_google(
self,
secret_value: SecretType,
vault: Optional[Dict] = None,
auth_type: Optional[str] = None,
region: Optional[str] = None,
):
# pylint: disable=import-outside-toplevel
try:
from RPA.Cloud.Google import Google
except ImportError as exc:
raise ImportError(
"dependency `rpaframework-google` needs to be installed in order to"
" use the 'google' engine"
) from exc
lib_kwargs = {}
init_kwargs = {}
if vault:
# Vault is enabled, so mark the same in the engine library as well.
name, key = list(vault.items())[0]
lib_kwargs.update(
{
"vault_name": name,
"vault_secret_key": key,
}
)
init_kwargs["use_robocorp_vault"] = True
elif secret_value:
# Vault not used, therefore the provided secret is a file path pointing to
# a service account or token JSON file.
if not isinstance(secret_value, Path):
raise ValueError(
f"secret {secret_value!r} not supported,"
" a file path holding the content is needed"
)
if (auth_type or "serviceaccount") == "serviceaccount":
secret_type = "service_account"
else:
secret_type = "token_file"
init_kwargs[secret_type] = str(secret_value)
if auth_type:
lib_kwargs["cloud_auth_type"] = auth_type
if region:
init_kwargs["region"] = region
engine = Google(**lib_kwargs)
engine.init_document_ai(**init_kwargs)
self._engines[EngineName.GOOGLE] = engine
@staticmethod
def _secret_value_to_params(secret_value: SecretType) -> Tuple[Tuple, Dict]:
args, kwargs = (), {}
if isinstance(secret_value, (tuple, list)):
args = tuple(secret_value)
elif isinstance(secret_value, dict):
kwargs = secret_value
elif isinstance(secret_value, str):
for part in secret_value.split(","):
part = part.strip()
if ":" in part:
key, value = part.split(":", 1)
kwargs[key] = value
else:
args += (part,)
else:
raise TypeError(f"not supported secret type {type(secret_value)}")
return args, kwargs
def _init_base64(self, secret_value: SecretType):
# pylint: disable=import-outside-toplevel
from RPA.DocumentAI.Base64AI import Base64AI
engine = Base64AI()
args, kwargs = self._secret_value_to_params(secret_value)
engine.set_authorization(*args, **kwargs)
self._engines[EngineName.BASE64] = engine
def _init_nanonets(self, secret_value: SecretType):
# pylint: disable=import-outside-toplevel
from RPA.DocumentAI.Nanonets import Nanonets
engine = Nanonets()
args, kwargs = self._secret_value_to_params(secret_value)
engine.set_authorization(*args, **kwargs)
self._engines[EngineName.NANONETS] = engine
@keyword
def switch_engine(self, name: Union[EngineName, str]) -> None:
"""Switch between already initialized engines.
Use this to jump between engines when scanning with multiple of them.
:param name: Name of the engine to be set as active. (choose between: %s)
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Document AI All
@{engines} = Create List base64ai nanonets
FOR ${engine} IN @{engines}
Switch Engine ${engine}
Log Scanning with engine: ${engine}...
Predict invoice.png
${data} = Get Result
Log List ${data}
END
**Example: Python**
.. code-block:: python
lib_docai.switch_engine("base64ai")
lib_docai.predict("invoice.png")
"""
name: EngineName = (
name if isinstance(name, EngineName) else EngineName(name.lower())
)
if name not in self._engines:
raise RuntimeError(
f"can't switch to {name.value!r} engine, please run"
f" `Init Engine {name.value} ...` first"
)
self._active_engine = name
switch_engine.__doc__ %= ", ".join([engine.value for engine in EngineName])
@keyword
def init_engine(
self,
name: Union[EngineName, str],
secret: Optional[SecretType] = None,
vault: Optional[Union[Dict, str]] = None,
**kwargs,
) -> None:
"""Initialize the engine you want to scan documents with.
This is required before being able to run ``Predict``. Once initialized, you
don't need to run this again, simply use ``Switch Engine`` to jump between
the engines. The final secret value (passed directly with `secret` or picked up
automatically from the Vault with `vault`) will be split into authorization
args and kwargs or just passed as it is to the wrapped library. Keep in mind
that some engines are expecting API keys where others tokens or private keys.
Any optional keyword argument will be passed further in the wrapped library.
:param name: Name of the engine.
:param secret: Authenticate with a string/file/object secret directly.
:param vault: Specify the Vault storage `name` and secret `key` in order to
authenticate. ('name:key' or {name: key} formats are supported)
**How secret resolution works**
When `vault` is passed in, the corresponding Vault is retrieved and the value
belonging to specified field is returned as a secret. If a `secret` is used,
then this value is returned as it is if this isn't a path pointing to the file
holding the value to be returned. We'll be relying on environment variables in
the absence of both the `secret` and `vault`.
Expected secret value formats:
- google: `<json-service/token>` (``RPA.Cloud.Google.Init Document AI``)
- base64ai: `<e-mail>,<api-key>`
(``RPA.DocumentAI.Base64AI.Set Authorization``)
- nanonets: `<api-key>` (``RPA.DocumentAI.Nanonets.Set Authorization``)
**Example: Robot Framework**
.. code-block:: robotframework
*** Keywords ***
Init Base64
Init Engine base64ai vault=document_ai:base64ai
**Example: Python**
.. code-block:: python
from RPA.DocumentAI import DocumentAI
from RPA.Robocorp.Vault import Vault
lib_docai = DocumentAI()
mail_apikey = Vault().get_secret("document_ai")["base64ai"]
lib_docai.init_engine("base64ai", secret=mail_apikey)
"""
if secret and vault:
raise ValueError("choose between `secret` and `vault`")
elif not (secret or vault):
self.logger.warning("No `secret` or `vault` provided, relying on env vars.")
if isinstance(vault, str):
vault_name, vault_secret_key = vault.split(":")
vault = {vault_name: vault_secret_key}
init_map = {
# Google library needs to be Vault aware due to its internal way of
# handling secrets directly from there. (without our parsing)
EngineName.GOOGLE: functools.partial(self._init_google, vault=vault),
# Rest of the engines have a normalized way of picking up secrets. They can
# be provided directly (string, file path, list or dict) or through Vault.
EngineName.BASE64: self._init_base64,
EngineName.NANONETS: self._init_nanonets,
}
name: EngineName = (
name if isinstance(name, EngineName) else EngineName(name.lower())
)
secret_value = self._get_secret_value(secret, vault)
# Will raise by itself if additional `kwargs` are required but not provided,
# given the selected engine.
init_map[name](secret_value, **kwargs)
self.switch_engine(name)
@keyword
def predict(
self,
location: PathType,
model: Optional[Union[str, List[str]]] = None,
**kwargs,
) -> None:
"""Scan a document with the currently active engine and store the result
internally for a later retrieval.
Based on the selected engine, this wraps a chain of libraries until calling a
service API in the end, where the passed file is analyzed. Any optional keyword
argument will be passed further in the wrapped library. (some engines require
mandatory parameters like project ID or region)
:param location: Path to a local file or URL address of a remote one. (not all
engines work with URLs)
:param model: Model name(s) to scan with. (some engines guess the model if
not specified)
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Document AI Base64
[Setup] Init Base64
Predict https://site.com/path/to/invoice.png
**Example: Python**
.. code-block:: python
lib_docai.predict("local/path/to/invoice.png", model="finance/invoice")
"""
location_file = Path(location).expanduser().resolve()
if location_file.exists():
location_url = None
self.logger.info("Using file path based location: %s", location_file)
else:
location_url = location
location_file = None
self.logger.info("Using URL address based location: %s", location_url)
if self._active_engine in (EngineName.GOOGLE, EngineName.NANONETS):
self.logger.warning(
f"Engine {self._active_engine} isn't supporting URL input at the "
"moment!"
)
if not model and self._active_engine in (
EngineName.GOOGLE,
EngineName.NANONETS,
):
self.logger.warning(
f"Engine {self._active_engine} requires a specific `model` passed in!"
)
process_map = {
EngineName.GOOGLE: lambda: self.engine.process_document(
file_path=location_file, processor_id=model, **kwargs
),
EngineName.BASE64: lambda: (
self.engine.scan_document_file
if location_file
else self.engine.scan_document_url
)(location_file or location_url, model_types=model, **kwargs),
EngineName.NANONETS: lambda: self.engine.predict_file(
filepath=location_file, model_id=model
),
}
result = process_map[self._active_engine]()
self._results[self._active_engine] = result
@keyword
def get_result(self, extended: bool = False) -> ResultType:
"""Retrieve the result data previously obtained with ``Predict``.
The stored raw result is usually pre-processed with a library specific keyword
prior the return.
:param extended: Get all the details inside the result data. (main fields only
by default)
:returns: Usually a list of fields detected in the document.
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Scan With Base64
Document AI Base64
${data} = Get Result
Log List ${data}
**Example: Python**
.. code-block:: python
result = lib_docai.get_result()
for field in result:
print(field)
"""
if extended:
return self.result
result_map = {
EngineName.GOOGLE: lambda: self.engine.get_document_entities(self.result),
EngineName.BASE64: lambda: self.engine.get_fields_from_prediction_result(
self.result
),
EngineName.NANONETS: lambda: self.engine.get_fields_from_prediction_result(
self.result
),
}
return result_map[self._active_engine]() | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/DocumentAI/DocumentAI.py | 0.821259 | 0.306881 | DocumentAI.py | pypi |
import json
import logging
import os
import random
import time
import urllib.parse as urlparse
from json import JSONDecodeError # pylint: disable=no-name-in-module
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Union
import requests
from requests.exceptions import HTTPError
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
from tenacity import (
before_sleep_log,
retry,
retry_if_exception,
stop_after_attempt,
wait_random_exponential,
)
from RPA.JSON import JSONType
from RPA.RobotLogListener import RobotLogListener
PathType = Union[Path, str]
DEBUG_ON = bool(os.getenv("RPA_DEBUG_API"))
log_to_console = BuiltIn().log_to_console
def url_join(*parts):
"""Join parts of URL and handle missing/duplicate slashes."""
return "/".join(str(part).strip("/") for part in parts)
def json_dumps(payload: JSONType, **kwargs):
"""Create JSON string in UTF-8 encoding."""
kwargs.setdefault("ensure_ascii", False)
return json.dumps(payload, **kwargs)
def is_json_equal(left: JSONType, right: JSONType):
"""Deep-compare two output JSONs."""
return json_dumps(left, sort_keys=True) == json_dumps(right, sort_keys=True)
def truncate(text: str, size: int):
"""Truncate a string from the middle."""
if len(text) <= size:
return text
ellipsis = " ... "
segment = (size - len(ellipsis)) // 2
return text[:segment] + ellipsis + text[-segment:]
def resolve_path(path: str) -> Path:
"""Resolve a string-based path, and replace variables."""
try:
safe = str(path).replace("\\", "\\\\")
path = BuiltIn().replace_variables(safe)
except RobotNotRunningError:
pass
return Path(path).expanduser().resolve()
def log_more(message, *args, func=logging.debug):
func(message, *args)
if DEBUG_ON:
log_to_console(str(message) % args)
def get_dot_value(source: Dict, key: str) -> Any:
"""Returns the end value from `source` dictionary given `key` traversal."""
keys = key.split(".")
value = source
for _key in keys:
value = value.get(_key)
return value
def set_dot_value(source: Dict, key: str, *, value: Any):
"""Sets the end `value` into `source` dictionary given `key` destination."""
keys = key.rsplit(".", 1) # one or at most two parts
if len(keys) == 2:
source = get_dot_value(source, keys[0])
source[keys[-1]] = value
class RequestsHTTPError(HTTPError):
"""Custom `requests` HTTP error with status code and message."""
def __init__(
self, *args, status_code: int = 0, status_message: str = "Error", **kwargs
):
super().__init__(*args, **kwargs)
self.status_code = status_code
self.status_message = status_message
class Requests:
"""Wrapper over `requests` 3rd-party with error handling and retrying support."""
def __init__(self, route_prefix: str, default_headers: Optional[dict] = None):
self._route_prefix = route_prefix
self._default_headers = default_headers
def handle_error(self, response: requests.Response):
resp_status_code = response.status_code
log_func = logging.critical if resp_status_code // 100 == 5 else logging.debug
log_more(
"API response: %s %r", resp_status_code, response.reason, func=log_func
)
if response.ok:
return
fields = {}
try:
fields = response.json()
while not isinstance(fields, dict):
# For some reason we might still get a string from the deserialized
# retrieved JSON payload. If a dictionary couldn't be obtained at all,
# it will end up raising `RequestsHTTPError`.
fields = json.loads(fields)
except (JSONDecodeError, ValueError, TypeError):
# No `fields` dictionary can be obtained at all.
log_more("No fields were returned by the server", func=logging.critical)
try:
response.raise_for_status()
except Exception as exc: # pylint: disable=broad-except
log_more(exc, func=logging.exception)
raise RequestsHTTPError(exc, status_code=resp_status_code) from exc
err_status_code = 0
status_message = "Error"
try:
err_status_code = int(fields.get("status", resp_status_code))
status_message = fields.get("error", {}).get("code", "Error")
reason = fields.get("message") or fields.get("error", {}).get(
"message", response.reason
)
raise HTTPError(f"{err_status_code} {status_message}: {reason}")
except Exception as exc: # pylint: disable=broad-except
log_more(exc, func=logging.exception)
raise RequestsHTTPError(
str(fields), status_code=err_status_code, status_message=status_message
) from exc
# pylint: disable=no-self-argument
def _needs_retry(exc: BaseException) -> bool:
# Don't retry on some specific error codes or messages.
# https://www.restapitutorial.com/httpstatuscodes.html
# 400 - payload is bad and needs to be changed
# 401 - missing auth bearer token
# 403 - auth is in place, but not allowed (insufficient privileges)
# 409 - payload not good for the affected resource
no_retry_codes = [400, 401, 403, 409]
no_retry_messages = []
if isinstance(exc, RequestsHTTPError):
if (
exc.status_code in no_retry_codes
or exc.status_message in no_retry_messages
):
return False
if exc.status_code == 429:
# We hit the rate limiter, so sleep extra.
seconds = random.uniform(1, 3)
log_more("Rate limit hit, sleeping: %fs", seconds, func=logging.warning)
time.sleep(seconds)
return True
# pylint: disable=no-self-argument,no-method-argument
def _before_sleep_log():
logger = logging.root
logger_log = logger.log
def extensive_log(level, msg, *args, **kwargs):
logger_log(level, msg, *args, **kwargs)
if DEBUG_ON:
log_to_console(str(msg) % args)
# Monkeypatch inner logging function so it produces an exhaustive log when
# used under the before-sleep logging utility in `tenacity`.
logger.log = extensive_log
return before_sleep_log(logger, logging.DEBUG, exc_info=True)
@retry(
# Retry until either succeed or trying for the fifth time and still failing.
# So sleep and retry for 4 times at most.
stop=stop_after_attempt(5),
# If the exception is no worth retrying or the number of tries is depleted,
# then re-raise the last raised exception.
reraise=True,
# Decide if the raised exception needs retrying or not.
retry=retry_if_exception(_needs_retry),
# Produce debugging logging prior to each time we sleep & re-try.
before_sleep=_before_sleep_log(),
# Sleep between the tries with a random float amount of seconds like so:
# 1. [0, 2]
# 2. [0, 4]
# 3. [0, 5]
# 4. [0, 5]
wait=wait_random_exponential(multiplier=2, max=5),
)
def _request(
self,
verb: Callable[..., requests.Response],
url: str,
*args,
_handle_error: Optional[Callable[[requests.Response], None]] = None,
_sensitive: bool = False,
headers: Optional[dict] = None,
**kwargs,
) -> requests.Response:
# Absolute URLs override the prefix, so they are safe to be sent as they'll be
# the same after joining.
url = urlparse.urljoin(self._route_prefix, url)
headers = headers if headers is not None else self._default_headers
handle_error = _handle_error or self.handle_error
url_for_log = url
if _sensitive:
# Omit query from the URL since might contain sensitive info.
split = urlparse.urlsplit(url_for_log)
url_for_log = urlparse.urlunsplit(
[split.scheme, split.netloc, split.path, "", split.fragment]
)
log_more("%s %r", verb.__name__.upper(), url_for_log)
response = verb(url, *args, headers=headers, **kwargs)
handle_error(response)
return response
# CREATE
def post(self, *args, **kwargs) -> requests.Response:
return self._request(requests.post, *args, **kwargs)
# RETRIEVE
def get(self, *args, **kwargs) -> requests.Response:
return self._request(requests.get, *args, **kwargs)
# UPDATE
def put(self, *args, **kwargs) -> requests.Response:
return self._request(requests.put, *args, **kwargs)
# DELETE
def delete(self, *args, **kwargs) -> requests.Response:
return self._request(requests.delete, *args, **kwargs)
def protect_keywords(base: str, keywords: List[str]):
"""Protects from logging a list of `keywords` relative to `base`."""
to_protect = [f"{base}.{keyword}" for keyword in keywords]
listener = RobotLogListener()
listener.register_protected_keywords(to_protect)
def get_output_dir(default: Optional[PathType] = "output") -> Path:
"""Returns the output directory path."""
try:
output_dir = BuiltIn().get_variable_value("${OUTPUT_DIR}", default=default)
except RobotNotRunningError:
output_dir = default
return Path(output_dir).expanduser().resolve() | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Robocorp/utils.py | 0.750781 | 0.160595 | utils.py | pypi |
from typing import Dict, List
from robocorp import storage
from robot.api.deco import keyword, library
@library
class Storage:
"""Control Room `Asset Storage` library operating with the cloud built-in key-value
store.
Library requires at the minimum `rpaframework` version **24.0.0**.
**Usage**
.. code-block:: robotframework
*** Tasks ***
Manage Assets
@{assets} = List Assets
Log List ${assets}
Set Text Asset my-asset My string asset value
${value} = Get Text Asset my-asset
Log Asset value: ${value}
Delete Asset my-asset
.. code-block:: python
import logging
from RPA.Robocorp.Storage import Storage
storage = Storage()
def manage_assets():
assets = storage.list_assets()
logging.info(assets)
storage.set_text_asset("my-asset", "My string asset value")
value = storage.get_text_asset("my-asset")
logging.info("Asset value: %s", value)
storage.delete_asset("my-asset")
**Caveats**
Currently, there's no local file adapter support, therefore you need to be linked
to Control Room and connected to a Workspace in VSCode before being able to develop
locally robots using this functionality.
While the content type can be controlled (during bytes and file setting), it is
currently disabled in this version of the library for simplicity reasons.
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
@keyword
def list_assets(self) -> List[str]:
"""List all the existing assets.
:returns: A list of available assets' names
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Print All Assets
@{assets} = List Assets
Log List ${assets}
**Example: Python**
.. code-block:: python
def print_all_assets():
print(storage.list_assets())
"""
return storage.list_assets()
@keyword
def set_bytes_asset(self, name: str, value: bytes, wait: bool = True):
"""Creates or updates an asset named `name` with the provided bytes `value`.
:param name: Name of the existing or new asset to create (if missing)
:param value: The new bytes value to set within the asset
:param wait: Wait for the value to be set successfully
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Set An Asset
${random_bytes} = Evaluate os.urandom(10) modules=os
Set Bytes Asset my-bytes-asset ${random_bytes}
**Example: Python**
.. code-block:: python
import os
def set_an_asset():
random_bytes = os.urandom(10)
storage.set_bytes_asset("my-bytes-asset", random_bytes)
"""
storage.set_bytes(name, data=value, wait=wait)
@keyword
def get_bytes_asset(self, name: str) -> bytes:
"""Get the asset's bytes value by providing its `name`.
:param name: Name of the asset
:raises AssetNotFound: Asset with the given name does not exist
:returns: The current value of this asset as bytes
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Retrieve An Asset
${value} = Get Bytes Asset my-bytes-asset
Log Asset bytes value: ${value}
**Example: Python**
.. code-block:: python
def retrieve_an_asset():
value = storage.get_bytes_asset("my-bytes-asset")
print(b"Asset bytes value:", value)
"""
return storage.get_bytes(name)
@keyword
def set_text_asset(self, name: str, value: str, wait: bool = True):
"""Creates or updates an asset named `name` with the provided text `value`.
:param name: Name of the existing or new asset to create (if missing)
:param value: The new text value to set within the asset
:param wait: Wait for the value to be set successfully
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Set An Asset
Set Text Asset my-text-asset My asset value as text
**Example: Python**
.. code-block:: python
def set_an_asset():
storage.set_text_asset("my-text-asset", "My asset value as text")
"""
storage.set_text(name, text=value, wait=wait)
@keyword
def get_text_asset(self, name: str) -> str:
"""Get the asset's text value by providing its `name`.
:param name: Name of the asset
:raises AssetNotFound: Asset with the given name does not exist
:returns: The current value of this asset as text
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Retrieve An Asset
${value} = Get Text Asset my-text-asset
Log Asset text value: ${value}
**Example: Python**
.. code-block:: python
def retrieve_an_asset():
value = storage.get_text_asset("my-text-asset")
print("Asset text value:", value)
"""
return storage.get_text(name)
@keyword("Set JSON Asset")
def set_json_asset(self, name: str, value: Dict, wait: bool = True):
"""Creates or updates an asset named `name` with the provided dictionary
`value`.
:param name: Name of the existing or new asset to create (if missing)
:param value: The new dictionary value to set within the asset
:param wait: Wait for the value to be set successfully
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Set An Asset
&{entries} = Create Dictionary dogs ${10}
Set JSON Asset my-json-asset ${entries}
**Example: Python**
.. code-block:: python
def set_an_asset():
entries = {"dogs": 10}
storage.set_json_asset("my-json-asset", entries)
"""
storage.set_json(name, value=value, wait=wait)
@keyword("Get JSON Asset")
def get_json_asset(self, name: str) -> Dict:
"""Get the asset's dictionary value by providing its `name`.
:param name: Name of the asset
:raises AssetNotFound: Asset with the given name does not exist
:returns: The current value of this asset as a dictionary
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Retrieve An Asset
&{value} = Get JSON Asset my-json-asset
Log Asset dictionary value: ${value}
**Example: Python**
.. code-block:: python
def retrieve_an_asset():
value = storage.get_json_asset("my-json-asset")
print("Asset dictionary value:", value)
"""
return storage.get_json(name)
@keyword
def set_file_asset(self, name: str, path: str, wait: bool = True):
"""Creates or updates an asset named `name` with the content of the given
`path` file.
:param name: Name of the existing or new asset to create (if missing)
:param path: The file path whose content to be set within the asset
:param wait: Wait for the value to be set successfully
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Set An Asset
Set File Asset my-file-asset report.pdf
**Example: Python**
.. code-block:: python
def set_an_asset():
storage.set_file_asset("my-file-asset", "report.pdf")
"""
storage.set_file(name, path=path, wait=wait)
@keyword
def get_file_asset(self, name: str, path: str, overwrite: bool = False) -> str:
"""Get the asset's content saved to disk by providing its `name`.
:param name: Name of the asset
:param path: Destination path to the downloaded file
:param overwrite: Replace destination file if it already exists (default False)
:raises AssetNotFound: Asset with the given name does not exist
:returns: A local path pointing to the retrieved file
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Retrieve An Asset
${path} = Get File Asset my-file-asset report.pdf
Log Asset file path: ${path}
**Example: Python**
.. code-block:: python
def retrieve_an_asset():
path = storage.get_file_asset("my-file-asset", "report.pdf")
print("Asset file path:", path)
"""
return str(storage.get_file(name, path=path, exist_ok=overwrite))
@keyword
def delete_asset(self, name: str):
"""Delete an asset by providing its `name`.
This operation cannot be undone.
:param name: Name of the asset to delete
:raises AssetNotFound: Asset with the given name does not exist
**Example: Robot Framework**
.. code-block:: robotframework
*** Tasks ***
Remove An Asset
Delete Asset my-asset
**Example: Python**
.. code-block:: python
def remove_an_asset():
storage.delete_asset("my-asset")
"""
storage.delete_asset(name) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Robocorp/Storage.py | 0.924686 | 0.39222 | Storage.py | pypi |
import base64
import binascii
import collections
import copy
import json
import logging
import os
import traceback
from abc import abstractmethod, ABCMeta
from typing import Tuple
import requests
import yaml
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from robot.libraries.BuiltIn import BuiltIn, RobotNotRunningError
from RPA.core.helpers import import_by_name, required_env
from .utils import url_join, resolve_path
class RobocorpVaultError(RuntimeError):
"""Raised when there's problem with reading from Robocorp Vault."""
class Secret(collections.abc.Mapping):
"""Container for a secret with name, description, and
multiple key-value pairs. Immutable and avoids logging
internal values when possible.
:param name: Name of secret
:param description: Human-friendly description for secret
:param values: Dictionary of key-value pairs stored in secret
"""
def __init__(self, name, description, values):
self._name = name
self._desc = description
self._dict = collections.OrderedDict(**values)
@property
def name(self):
return self._name
@property
def description(self):
return self._desc
def update(self, kvpairs):
self._dict.update(kvpairs)
def __getitem__(self, key):
return self._dict[key]
def __setitem__(self, key, value):
self._dict[key] = value
def __contains__(self, key):
return key in self._dict
def __iter__(self):
return iter(self._dict)
def __len__(self):
return len(self._dict)
def __repr__(self):
return "Secret(name={name}, keys=[{keys}])".format(
name=self.name, keys=", ".join(str(key) for key in self.keys())
)
class BaseSecretManager(metaclass=ABCMeta):
"""Abstract class for secrets management. Should be used as a
base-class for any adapter implementation.
"""
@abstractmethod
def get_secret(self, secret_name):
"""Return ``Secret`` object with given name."""
@abstractmethod
def set_secret(self, secret: Secret):
"""Set a secret with a new value."""
class FileSecrets(BaseSecretManager):
"""Adapter for secrets stored in a database file. Supports only
plaintext secrets, and should be used mainly for debugging.
The path to the secrets file can be set with the
environment variable ``RPA_SECRET_FILE``, or as
an argument to the library.
The format of the secrets file should be one of the following:
.. code-block:: JSON
{
"name1": {
"key1": "value1",
"key2": "value2"
},
"name2": {
"key1": "value1"
}
}
OR
.. code-block:: YAML
name1:
key1: value1
key2: value2
name2:
key1: value1
"""
SERIALIZERS = {
".json": (json.load, json.dump),
".yaml": (yaml.full_load, yaml.dump),
}
def __init__(self, secret_file="secrets.json"):
self.logger = logging.getLogger(__name__)
path = required_env("RPA_SECRET_FILE", secret_file)
self.logger.info("Resolving path: %s", path)
self.path = resolve_path(path)
extension = self.path.suffix
serializer = self.SERIALIZERS.get(extension)
# NOTE(cmin764): This will raise instead of returning an empty secrets object
# because it is wrong starting from the "env.json" configuration level.
if not serializer:
raise ValueError(
f"Not supported local vault secrets file extension {extension!r}"
)
self._loader, self._dumper = serializer
self.data = self.load()
def load(self):
"""Load secrets file."""
try:
with open(self.path, encoding="utf-8") as fd:
data = self._loader(fd)
if not isinstance(data, dict):
raise ValueError("Invalid content format")
return data
except (IOError, ValueError) as err:
self.logger.error("Failed to load secrets file: %s", err)
return {}
def save(self):
"""Save the secrets content to disk."""
try:
with open(self.path, "w", encoding="utf-8") as f:
if not isinstance(self.data, dict):
raise ValueError("Invalid content format")
self._dumper(self.data, f, indent=4)
except (IOError, ValueError) as err:
self.logger.error("Failed to save secrets file: %s", err)
def get_secret(self, secret_name):
"""Get secret defined with given name from file.
:param secret_name: Name of secret to fetch
:returns: Secret object
:raises KeyError: No secret with given name
"""
values = self.data.get(secret_name)
if values is None:
raise KeyError(f"Undefined secret: {secret_name}")
return Secret(secret_name, "", values)
def set_secret(self, secret: Secret) -> None:
"""Set the secret value in the local Vault
with the given ``Secret`` object.
:param secret: A ``Secret`` object.
:raises IOError, ValueError: Writing the local vault failed.
"""
self.data[secret.name] = dict(secret)
self.save()
class RobocorpVault(BaseSecretManager):
"""Adapter for secrets stored in Robocorp Vault.
The following environment variables should exist:
- RC_API_SECRET_HOST: URL to Robocorp Secrets API
- RC_API_SECRET_TOKEN: API token with access to Robocorp Secrets API
- RC_WORKSPACE_ID: Robocorp Workspace ID
If the robot run is started from the Robocorp Control Room these environment
variables will be configured automatically.
"""
ENCRYPTION_SCHEME = "robocloud-vault-transit-v2"
def __init__(self, *args, **kwargs):
# pylint: disable=unused-argument
self.logger = logging.getLogger(__name__)
# Environment variables set by runner
self._host = required_env("RC_API_SECRET_HOST")
self._token = required_env("RC_API_SECRET_TOKEN")
self._workspace = required_env("RC_WORKSPACE_ID")
# Generated lazily on request
self.__private_key = None
self.__public_bytes = None
@property
def headers(self):
"""Default request headers."""
return {"Authorization": f"Bearer {self._token}"}
@property
def params(self):
"""Default request parameters."""
return {
"encryptionScheme": self.ENCRYPTION_SCHEME,
"publicKey": self._public_bytes,
}
@property
def _private_key(self):
"""Cryptography private key object."""
if self.__private_key is None:
self.__private_key = rsa.generate_private_key(
public_exponent=65537, key_size=4096, backend=default_backend()
)
return self.__private_key
@property
def _public_bytes(self):
"""Serialized public key bytes."""
if self.__public_bytes is None:
self.__public_bytes = base64.b64encode(
self._private_key.public_key().public_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
)
return self.__public_bytes
def create_secret_url(self, name):
"""Create a URL for a specific secret."""
return url_join(
self._host, "secrets-v1", "workspaces", self._workspace, "secrets", name
)
def create_public_key_url(self):
"""Create a URL for encryption public key."""
return url_join(
self._host,
"secrets-v1",
"workspaces",
self._workspace,
"secrets",
"publicKey",
)
def get_secret(self, secret_name):
"""Get secret defined with given name from Robocorp Vault.
:param secret_name: Name of secret to fetch
:returns: Secret object
:raises RobocorpVaultError: Error with API request or response payload
"""
url = self.create_secret_url(secret_name)
try:
response = requests.get(url, headers=self.headers, params=self.params)
response.raise_for_status()
payload = response.json()
payload = self._decrypt_payload(payload)
except InvalidTag as e:
self.logger.debug(traceback.format_exc())
raise RobocorpVaultError("Failed to validate authentication tag") from e
except Exception as exc:
self.logger.debug(traceback.format_exc())
raise RobocorpVaultError from exc
return Secret(payload["name"], payload["description"], payload["values"])
def _decrypt_payload(self, payload):
payload = copy.deepcopy(payload)
fields = payload.pop("encryption", None)
if fields is None:
raise KeyError("Missing encryption fields from response")
scheme = fields["encryptionScheme"]
if scheme != self.ENCRYPTION_SCHEME:
raise ValueError(f"Unexpected encryption scheme: {scheme}")
aes_enc = base64.b64decode(fields["encryptedAES"])
aes_tag = base64.b64decode(fields["authTag"])
aes_iv = base64.b64decode(fields["iv"])
# Decrypt AES key using our private key
aes_key = self._private_key.decrypt(
aes_enc,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
),
)
# Decrypt actual value using decrypted AES key
ciphertext = base64.b64decode(payload.pop("value")) + aes_tag
data = AESGCM(aes_key).decrypt(binascii.hexlify(aes_iv), ciphertext, b"")
payload["values"] = json.loads(data)
return payload
def set_secret(self, secret: Secret) -> None:
"""Set the secret value in the Vault. Note that the secret possibly
consists of multiple key-value pairs, which will all be overwritten
with the values given here. So don't try to update only one item
of the secret, update all of them.
:param secret: A ``Secret`` object
"""
value, aes_iv, aes_key, aes_tag = self._encrypt_secret_value_with_aes(secret)
pub_key = self.get_publickey()
aes_enc = self._encrypt_aes_key_with_public_rsa(aes_key, pub_key)
payload = {
"description": secret.description,
"encryption": {
"authTag": aes_tag.decode(),
"encryptedAES": aes_enc.decode(),
"encryptionScheme": self.ENCRYPTION_SCHEME,
"iv": aes_iv.decode(),
},
"name": secret.name,
"value": value.decode(),
}
url = self.create_secret_url(secret.name)
try:
response = requests.put(url, headers=self.headers, json=payload)
response.raise_for_status()
except Exception as e:
self.logger.debug(traceback.format_exc())
if response.status_code == 403:
raise RobocorpVaultError(
"Failed to set secret value. Does your token have write access?"
) from e
raise RobocorpVaultError("Failed to set secret value.") from e
def get_publickey(self) -> bytes:
"""Get the public key for AES encryption with the existing token."""
url = self.create_public_key_url()
try:
response = requests.get(url, headers=self.headers)
response.raise_for_status()
except Exception as e:
self.logger.debug(traceback.format_exc())
raise RobocorpVaultError(
"Failed to fetch public key. Is your token valid?"
) from e
return response.content
@staticmethod
def _encrypt_secret_value_with_aes(
secret: Secret,
) -> Tuple[bytes, bytes, bytes, bytes]:
def generate_aes_key() -> Tuple[bytes, bytes]:
aes_key = AESGCM.generate_key(bit_length=256)
aes_iv = os.urandom(16)
return aes_key, aes_iv
def split_auth_tag_from_encrypted_value(
encrypted_value: bytes,
) -> Tuple[bytes, bytes]:
"""AES auth tag is the last 16 bytes of the AES encrypted value.
Split the tag from the value, as that is required for the API.
"""
aes_tag = encrypted_value[-16:]
trimmed_encrypted_value = encrypted_value[:-16]
return trimmed_encrypted_value, aes_tag
value = json.dumps(dict(secret)).encode()
aes_key, aes_iv = generate_aes_key()
encrypted_value = AESGCM(aes_key).encrypt(aes_iv, value, b"")
encrypted_value, aes_tag = split_auth_tag_from_encrypted_value(encrypted_value)
return (
base64.b64encode(encrypted_value),
base64.b64encode(aes_iv),
aes_key,
base64.b64encode(aes_tag),
)
@staticmethod
def _encrypt_aes_key_with_public_rsa(aes_key: bytes, public_rsa: bytes) -> bytes:
pub_decoded = base64.b64decode(public_rsa)
public_key = serialization.load_der_public_key(pub_decoded)
aes_enc = public_key.encrypt(
aes_key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
),
)
return base64.b64encode(aes_enc)
class Vault:
"""`Vault` is a library for interacting with secrets stored in the `Robocorp
Control Room Vault`_ (by default) or file-based secrets, which can be taken
into use by setting some environment variables.
Robocorp Vault relies on environment variables, which are normally set
automatically by the Robocorp Work Agent or Assistant when a run is
initialized by the Robocorp Control Room. When developing robots locally
in VSCode, you can use the `Robocorp Code Extension`_ to set these
variables automatically as well.
Alternatively, you may set these environment variable manually using
`rcc`_ or directly in some other fashion. The specific variables which
must exist are:
- ``RC_API_SECRET_HOST``: URL to Robocorp Vault API
- ``RC_API_SECRET_TOKEN``: API Token for Robocorp Vault API
- ``RC_WORKSPACE_ID``: Control Room Workspace ID
.. _Robocorp Control Room Vault: https://robocorp.com/docs/development-guide/variables-and-secrets/vault
.. _Robocorp Code Extension: https://robocorp.com/docs/developer-tools/visual-studio-code/extension-features#connecting-to-control-room-vault
.. _rcc: https://robocorp.com/docs/rcc/workflow
File-based secrets can be set by defining two environment variables.
- ``RPA_SECRET_MANAGER``: RPA.Robocorp.Vault.FileSecrets
- ``RPA_SECRET_FILE``: Absolute path to the secrets database file
Example content of local secrets file:
.. code-block:: json
{
"swaglabs": {
"username": "standard_user",
"password": "secret_sauce"
}
}
OR
.. code-block:: YAML
swaglabs:
username: standard_user
password: secret_sauce
**Examples of Using Secrets in a Robot**
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library Collections
Library RPA.Robocorp.Vault
*** Tasks ***
Reading secrets
${secret}= Get Secret swaglabs
Log Many ${secret}
Modifying secrets
${secret}= Get Secret swaglabs
${level}= Set Log Level NONE
Set To Dictionary ${secret} username nobody
Set Log Level ${level}
Set Secret ${secret}
**Python**
.. code-block:: python
from RPA.Robocorp.Vault import Vault
VAULT = Vault()
def reading_secrets():
print(f"My secrets: {VAULT.get_secret('swaglabs')}")
def modifying_secrets():
secret = VAULT.get_secret("swaglabs")
secret["username"] = "nobody"
VAULT.set_secret(secret)
""" # noqa: E501
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self, *args, **kwargs):
"""The selected adapter can be set with the environment variable
``RPA_SECRET_MANAGER``, or the keyword argument ``default_adapter``.
Defaults to Robocorp Vault if not defined.
All other library arguments are passed to the adapter.
:param default_adapter: Override default secret adapter
"""
self.logger = logging.getLogger(__name__)
default = kwargs.pop("default_adapter", RobocorpVault)
adapter = required_env("RPA_SECRET_MANAGER", default)
self._adapter_factory = self._create_factory(adapter, args, kwargs)
self._adapter = None
try:
BuiltIn().import_library("RPA.RobotLogListener")
except RobotNotRunningError:
pass
@property
def adapter(self):
if self._adapter is None:
self._adapter = self._adapter_factory()
return self._adapter
def _create_factory(self, adapter, args, kwargs):
if isinstance(adapter, str):
adapter = import_by_name(adapter, __name__)
if not issubclass(adapter, BaseSecretManager):
raise ValueError(
f"Adapter '{adapter}' does not inherit from BaseSecretManager"
)
def factory():
return adapter(*args, **kwargs)
return factory
def get_secret(self, secret_name: str) -> Secret:
"""Read a secret from the configured source, e.g. Robocorp Vault,
and return it as a ``Secret`` object.
:param secret_name: Name of secret
"""
return self.adapter.get_secret(secret_name)
def set_secret(self, secret: Secret) -> None:
"""Overwrite an existing secret with new values.
Note: Only allows modifying existing secrets, and replaces
all values contained within it.
:param secret: Secret as a ``Secret`` object, from e.g. ``Get Secret``
"""
self.adapter.set_secret(secret) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Robocorp/Vault.py | 0.852214 | 0.191422 | Vault.py | pypi |
from RPA.application import (
BaseApplication,
catch_com_error,
constants,
to_path,
to_str_path,
)
class Application(BaseApplication):
"""`Word.Application` is a library for controlling the Word application.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.Word.Application
Task Setup Open Application
Suite Teardown Quit Application
*** Tasks ***
Open existing file
Open File old.docx
Write Text Extra Line Text
Write Text Another Extra Line of Text
Save Document AS ${CURDIR}${/}new.docx
${texts}= Get all Texts
Close Document
**Python**
.. code-block:: python
from RPA.Word.Application import Application
app = Application()
app.open_application()
app.open_file('old.docx')
app.write_text('Extra Line Text')
app.save_document_as('new.docx')
app.quit_application()
"""
APP_DISPATCH = "Word.Application"
FILEFORMATS = {
"DEFAULT": "wdFormatDocumentDefault",
"PDF": "wdFormatPDF",
"RTF": "wdFormatRTF",
"HTML": "wdFormatHTML",
"WORD97": "wdFormatDocument97",
"OPENDOCUMENT": "wdFormatOpenDocumentText",
}
def open_file(self, filename: str, read_only: bool = True) -> None:
"""Open Word document with filename.
:param filename: Word document path
"""
path = to_path(filename)
if not path.is_file():
raise FileNotFoundError(f"{str(path)!r} doesn't exist")
state = "read-only" if read_only else "read-write"
self.logger.info("Opening document (%s): %s", state, path)
with catch_com_error():
doc = self.app.Documents.Open(
FileName=str(path),
ConfirmConversions=False,
ReadOnly=read_only,
AddToRecentFiles=False,
)
err_msg = None
if doc is None:
err_msg = (
"Got null object when opening the document, enable RDP connection if"
" running by Control Room through a Worker service"
)
elif not hasattr(doc, "Activate"):
err_msg = (
"The document can't be activated, open it manually and dismiss any"
" alert you may encounter first"
)
if err_msg:
raise IOError(err_msg)
doc.Activate()
self.app.ActiveWindow.View.ReadingLayout = False
def create_new_document(self) -> None:
"""Create new document for Word application"""
with catch_com_error():
self.app.Documents.Add()
def export_to_pdf(self, filename: str) -> None:
"""Export active document into PDF file.
:param filename: PDF to export WORD into
"""
path = to_str_path(filename)
with catch_com_error():
self._active_document.ExportAsFixedFormat(
OutputFileName=path, ExportFormat=constants.wdExportFormatPDF
)
def write_text(self, text: str, newline: bool = True) -> None:
"""Writes given text at the end of the document
:param text: string to write
:param newline: write text to newline if True, default to True
"""
self.app.Selection.EndKey(Unit=constants.wdStory)
if newline:
text = f"\n{text}"
self.app.Selection.TypeText(text)
def replace_text(self, find: str, replace: str) -> None:
"""Replace text in active document
:param find: text to replace
:param replace: new text
"""
self._active_document.Content.Find.Execute(FindText=find, ReplaceWith=replace)
def set_header(self, text: str) -> None:
"""Set header for the active document
:param text: header text to set
"""
for section in self._active_document.Sections:
for header in section.Headers:
header.Range.Text = text
def set_footer(self, text: str) -> None:
"""Set footer for the active document
:param text: footer text to set
"""
for section in self._active_document.Sections:
for footer in section.Footers:
footer.Range.Text = text
def save_document(self) -> None:
"""Save active document"""
# Accept all revisions
self._active_document.Revisions.AcceptAll()
# Delete all comments
if self._active_document.Comments.Count >= 1:
self._active_document.DeleteAllComments()
self._active_document.Save()
def save_document_as(self, filename: str, fileformat: str = None) -> None:
"""Save document with filename and optionally with given fileformat
:param filename: where to save document
:param fileformat: see @FILEFORMATS dictionary for possible format,
defaults to None
"""
path = to_str_path(filename)
# Accept all revisions
self._active_document.Revisions.AcceptAll()
# Delete all comments
if self._active_document.Comments.Count >= 1:
self._active_document.DeleteAllComments()
if fileformat and fileformat.upper() in self.FILEFORMATS:
self.logger.debug("Saving with file format: %s", fileformat)
format_name = self.FILEFORMATS[fileformat.upper()]
format_type = getattr(constants, format_name)
else:
format_type = constants.wdFormatDocumentDefault
try:
self._active_document.SaveAs2(path, FileFormat=format_type)
except AttributeError:
self._active_document.SaveAs(path, FileFormat=format_type)
self.logger.info("File saved to: %s", path)
def get_all_texts(self) -> str:
"""Get all texts from active document
:return: texts
"""
return self._active_document.Content.Text | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Word/Application.py | 0.761538 | 0.166743 | Application.py | pypi |
import logging
import platform
import pyperclip as clipboard
if platform.system() == "Windows":
import win32clipboard
class Clipboard:
"""*DEPRECATED!!* Use library RPA.Desktop's clipboard functionality instead.
`Clipboard` is a library for managing clipboard - **copy** text to,
**paste** text from, and **clear** clipboard contents.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.Desktop.Clipboard
*** Tasks ***
Clipping
Copy To Clipboard Text from Robot to clipboard
${var}= Paste From Clipboard
Clear Clipboard
**Python**
.. code-block:: python
from RPA.Desktop.Clipboard import Clipboard
clip = Clipboard()
clip.copy_to_clipboard('Text from Python to clipboard')
text = clip.paste_from_clipboard()
print(f"clipboard had text: '{text}'")
clip.clear_clipboard()
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self):
self.logger = logging.getLogger(__name__)
def copy_to_clipboard(self, text):
"""*DEPRECATED!!* Use `RPA.Desktop` library's `Copy to Clipboard` instead.
Copy text to clipboard
:param text: to copy
"""
self.logger.debug("copy_to_clipboard")
if platform.system() == "Windows":
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text)
win32clipboard.CloseClipboard()
else:
clipboard.copy(text)
def paste_from_clipboard(self):
"""*DEPRECATED!!* Use `RPA.Desktop` library's `Paste from Clipboard` instead.
:return: text
"""
self.logger.debug("paste_from_clipboard")
if platform.system() == "Windows":
win32clipboard.OpenClipboard()
if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_TEXT):
text = win32clipboard.GetClipboardData()
else:
text = None
win32clipboard.CloseClipboard()
return text
else:
return clipboard.paste()
def clear_clipboard(self):
"""*DEPRECATED!!* Use `RPA.Desktop` library's `Clear Clipboard` instead.
Clear clipboard contents"""
self.logger.debug("clear_clipboard")
if platform.system() == "Windows":
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.CloseClipboard()
else:
clipboard.copy("") | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Desktop/Clipboard.py | 0.648021 | 0.203015 | Clipboard.py | pypi |
from collections import OrderedDict
import datetime
import getpass
import logging
import os
import platform
import signal
import socket
from typing import Any
from RPA.core.decorators import operating_system_required
if platform.system() == "Windows":
import psutil
from psutil._common import bytes2human
else:
psutil = object
bytes2human = object
class OperatingSystem:
"""`OperatingSystem` is a cross-platform library for managing
computer properties and actions.
**Examples**
**Robot Framework**
.. code-block:: robotframework
*** Settings ***
Library RPA.Desktop.OperatingSystem
*** Tasks ***
Get computer information
${boot_time}= Get Boot Time as_datetime=${TRUE}
${machine}= Get Machine Name
${username}= Get Username
&{memory}= Get Memory Stats
Log Many ${memory}
**Python**
.. code-block:: python
from RPA.Desktop.OperatingSystem import OperatingSystem
def get_computer_information():
ops = OperatingSystem()
print(f"Boot time : { ops.get_boot_time(as_datetime=True) }"
f"Machine name : { ops.get_machine_name() }"
f"Username : { ops.get_username() }"
f"Memory : { ops.get_memory_stats() }")
if __name__ == "__main__":
get_computer_information()
"""
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self):
self.logger = logging.getLogger(__name__)
@operating_system_required("Windows")
def get_boot_time(
self, as_datetime: bool = False, datetime_format: str = "%Y-%m-%d %H:%M:%S"
) -> str:
"""Get computer boot time in seconds from Epoch or in datetime string.
:param as_datetime: if True returns datetime string, otherwise seconds,
defaults to False
:param datetime_format: datetime string format, defaults to "%Y-%m-%d %H:%M:%S"
:return: seconds from Epoch or datetime string
Example:
.. code-block:: robotframework
${boottime} Get Boot Time
${boottime} Get Boot Time as_datetime=True
${boottime} Get Boot Time as_datetime=True datetime_format=%d.%m.%Y
"""
btime = self.boot_time_in_seconds_from_epoch()
if as_datetime:
return datetime.datetime.fromtimestamp(btime).strftime(datetime_format)
return btime
@operating_system_required("Windows")
def boot_time_in_seconds_from_epoch(self) -> str:
"""Get machine boot time
:return: boot time in seconds from Epoch
Example:
.. code-block:: robotframework
${epoch} Boot Time In Seconds From Epoch
"""
return psutil.boot_time()
def get_machine_name(self) -> str:
"""Get machine name
:return: machine name as string
Example:
.. code-block:: robotframework
${machine} Get Machine Name
"""
return socket.gethostname()
def get_username(self) -> str:
"""Get username of logged in user
:return: username as string
Example:
.. code-block:: robotframework
${user} Get Username
"""
return getpass.getuser()
@operating_system_required("Darwin", "Linux")
def put_system_to_sleep(self) -> None:
"""Puts system to sleep mode
Example:
.. code-block:: robotframework
Put System To Sleep
"""
if platform.system() == "Darwin":
os.system("pmset sleepnow")
if platform.system() == "Linux":
os.system("systemctl suspend")
@operating_system_required("Windows")
def process_exists(self, process_name: str, strict: bool = True) -> Any:
"""Check if process exists by its name
:param process_name: search for this process
:param strict: defines how match is made, default `True`
which means that process name needs to be exact match
and `False` does inclusive matching
:return: process instance or False
Example:
.. code-block:: robotframework
${process} Process Exists calc
${process} Process Exists calc strict=False
"""
for p in psutil.process_iter():
p_name = p.name()
if strict and process_name.lower() == p_name.lower():
return p
elif not strict and process_name.lower() in p_name.lower():
return p
return False
@operating_system_required("Windows")
def process_id_exists(self, pid: int) -> Any:
"""Check if process exists by its id
:param pid: process identifier
:return: process instance or False
Example:
.. code-block:: robotframework
${process} Process ID Exists 4567
Run Keyword If ${process} Log Process exists
"""
for p in psutil.process_iter():
if p.pid == pid:
return p
return False
@operating_system_required("Windows")
def kill_process(self, process_name: str) -> bool:
"""Kill process by name
:param process_name: name of the process
:return: True if succeeds False if not
Example:
.. code-block:: robotframework
${process} Process Exists calc strict=False
${status} Kill Process ${process.name()}
"""
p = self.process_exists(process_name)
if p:
p.terminate()
return True
return False
@operating_system_required("Windows")
def kill_process_by_pid(self, pid: int) -> None:
"""Kill process by pid
:param pid: process identifier
Example:
.. code-block:: robotframework
${process} Process Exists calc strict=False
${status} Kill Process By PID ${process.pid}
"""
os.kill(pid, signal.SIGTERM)
@operating_system_required("Windows")
def get_memory_stats(self, humanized: bool = True) -> dict:
"""Get computer memory stats and return those in bytes
or in humanized memory format.
:param humanized: if False returns memory information in bytes, defaults to True
:return: memory information in dictionary format
Example:
.. code-block:: robotframework
&{mem} Get Memory Stats
&{mem} Get Memory Stats humanized=False
"""
meminfo = psutil.virtual_memory()
memdict = meminfo._asdict()
if humanized:
humandict = {}
for key, val in memdict.items():
if key == "percent":
humandict[key] = val
else:
humandict[key] = bytes2human(val)
return OrderedDict(humandict)
return memdict | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Desktop/OperatingSystem.py | 0.773986 | 0.206254 | OperatingSystem.py | pypi |
import logging
import platform
import warnings
from typing import Optional
if platform.system() == "Windows":
# Configure comtypes to not generate DLL bindings into
# current environment, instead keeping them in memory.
# Slower, but prevents dirtying environments.
import comtypes.client
comtypes.client.gen_dir = None
# Ignore pywinauto warning about threading mode,
# which comtypes initializes to STA instead of MTA on import.
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=UserWarning)
import pywinauto
# pylint: disable=wrong-import-position
from robotlibcore import DynamicCore
from RPA.Desktop.utils import Buffer
from RPA.Desktop.keywords import (
ElementNotFound,
MultipleElementsFound,
TimeoutException,
ApplicationKeywords,
ClipboardKeywords,
FinderKeywords,
KeyboardKeywords,
MouseKeywords,
ScreenKeywords,
TextKeywords,
)
class Desktop(DynamicCore):
"""`Desktop` is a cross-platform library for navigating and interacting with
desktop environments. It can be used to automate applications through
the same interfaces that are available to human users.
The library includes the following features:
- Mouse and keyboard input emulation
- Starting and stopping applications
- Finding elements through image template matching
- Scraping text from given regions
- Taking screenshots
- Clipboard management
.. warning:: Windows element selectors are not currently supported, and require the use of ``RPA.Desktop.Windows``
**Installation**
The basic features such as mouse and keyboard input and application
control work with a default ``rpaframework`` install.
Advanced computer-vision features such as image template matching and
OCR require an additional library called ``rpaframework-recognition``.
The dependency should be added separately by specifing it in your *conda.yaml*
as ``rpaframework-recognition==5.0.1`` for example. If installing recognition
through ``pip`` instead of ``conda``, the OCR feature also requires ``tesseract``.
**Locating elements**
To automate actions on the desktop, a robot needs to interact with various
graphical elements such as buttons or input fields. The locations of these
elements can be found using a feature called `locators`.
A locator describes the properties or features of an element. This information
can be later used to locate similar elements even when window positions or
states change.
The currently supported locator types are:
=========== ================================================ ===========
Name Arguments Description
=========== ================================================ ===========
alias name (str) A custom named locator from the locator database, the default.
image path (str) Image of an element that is matched to current screen content.
point x (int), y (int) Pixel coordinates as absolute position.
offset x (int), y (int) Pixel coordinates relative to current mouse position.
size width (int), height (int) Region of fixed size, around point or screen top-left
region left (int), top (int), right (int), bottom (int) Bounding coordinates for a rectangular region.
ocr text (str), confidence (float, optional) Text to find from the current screen.
=========== ================================================ ===========
A locator is defined by its type and arguments, divided by a colon.
Some example usages are shown below. Note that the prefix for ``alias`` can
be omitted as its the default type.
.. code-block:: robotframework
Click point:50,100
Click region:20,20,100,30
Move mouse image:%{ROBOT_ROOT}/logo.png
Move mouse offset:200,0
Click
Click alias:SpareBin.Login
Click SpareBin.Login
Click ocr:"Create New Account"
You can also pass internal ``region`` objects as locators:
.. code-block:: robotframework
${region}= Find Element ocr:"Customer name"
Click ${region}
**Locator chaining**
Often it is not enough to have one locator, but instead an element
is defined through a relationship of various locators. For this use
case the library supports a special syntax, which we will call
locator chaining.
An example of chaining:
.. code-block:: robotframework
# Read text from area on the right side of logo
Read text image:logo.png + offset:600,0 + size:400,200
The supported operators are:
========== =========================================
Operator Description
========== =========================================
then, + Base locator relative to the previous one
and, &&, & Both locators should be found
or, ||, | Either of the locators should be found
not, ! The locator should not be found
========== =========================================
Further examples:
.. code-block:: robotframework
# Click below either label
Click (image:name.png or image:email.png) then offset:0,300
# Wait until dialog disappears
Wait for element not image:cookie.png
**Named locators**
The library supports storing locators in a database, which contains
all of the required fields and various bits of metadata. This enables
having one source of truth, which can be updated if a website's or applications's
UI changes. Robot Framework scripts can then only contain a reference
to a stored locator by name.
The main way to create named locators is with `VSCode`_.
Read more on identifying elements and crafting locators:
- `Desktop automation and RPA <https://robocorp.com/docs/development-guide/desktop>`_
- `How to find user interface elements using locators and keyboard shortcuts in Windows applications <https://robocorp.com/docs/development-guide/desktop/how-to-find-user-interface-elements-using-locators-and-keyboard-shortcuts-in-windows-applications>`_
.. _VSCode: https://robocorp.com/docs/developer-tools/visual-studio-code/overview
**Keyboard and mouse**
Keyboard keywords can emulate typing text, but also pressing various function keys.
The name of a key is case-insensitive and spaces will be converted to underscores,
i.e. the key ``Page Down`` and ``page_down`` are equivalent.
The following function keys are supported:
=============== ===========
Key Description
=============== ===========
shift A generic Shift key. This is a modifier.
shift_l The left Shift key. This is a modifier.
shift_r The right Shift key. This is a modifier.
ctrl A generic Ctrl key. This is a modifier.
ctrl_l he left Ctrl key. This is a modifier.
ctrl_r The right Ctrl key. This is a modifier.
alt A generic Alt key. This is a modifier.
alt_l The left Alt key. This is a modifier.
alt_r The right Alt key. This is a modifier.
alt_gr The AltGr key. This is a modifier.
cmd A generic command button (Windows / Command / Super key). This may be a modifier.
cmd_l The left command button (Windows / Command / Super key). This may be a modifier.
cmd_r The right command button (Windows / Command / Super key). This may be a modifier.
up An up arrow key.
down A down arrow key.
left A left arrow key.
right A right arrow key.
enter The Enter or Return key.
space The Space key.
tab The Tab key.
backspace The Backspace key.
delete The Delete key.
esc The Esc key.
home The Home key.
end The End key.
page_down The Page Down key.
page_up The Page Up key.
caps_lock The Caps Lock key.
f1 to f20 The function keys.
insert The Insert key. This may be undefined for some platforms.
menu The Menu key. This may be undefined for some platforms.
num_lock The Num Lock key. This may be undefined for some platforms.
pause The Pause / Break key. This may be undefined for some platforms.
print_screen The Print Screen key. This may be undefined for some platforms.
scroll_lock The Scroll Lock key. This may be undefined for some platforms.
=============== ===========
When controlling the mouse, there are different types of actions that can be
done. Same formatting rules as function keys apply. They are as follows:
============ ===========
Action Description
============ ===========
click Click with left mouse button
left_click Click with left mouse button
double_click Double click with left mouse button
triple_click Triple click with left mouse button
right_click Click with right mouse button
============ ===========
The supported mouse button types are ``left``, ``right``, and ``middle``.
**Examples**
Both Robot Framework and Python examples follow.
The library must be imported first.
.. code-block:: robotframework
*** Settings ***
Library RPA.Desktop
.. code-block:: python
from RPA.Desktop import Desktop
desktop = Desktop()
The library can open applications and interact with them through
keyboard and mouse events.
.. code-block:: robotframework
*** Keywords ***
Write entry in accounting
[Arguments] ${entry}
Open application erp_client.exe
Click image:%{ROBOT_ROOT}/images/create.png
Type text ${entry}
Press keys ctrl s
Press keys enter
.. code-block:: python
def write_entry_in_accounting(entry):
desktop.open_application("erp_client.exe")
desktop.click(f"image:{ROBOT_ROOT}/images/create.png")
desktop.type_text(entry)
desktop.press_keys("ctrl", "s")
desktop.press_keys("enter")
Targeting can be currently done using coordinates (absolute or relative),
but using template matching is preferred.
.. code-block:: robotframework
*** Keywords ***
Write to field
[Arguments] ${text}
Move mouse image:input_label.png
Move mouse offset:200,0
Click
Type text ${text}
Press keys enter
.. code-block:: python
def write_to_field(text):
desktop.move_mouse("image:input_label.png")
desktop.move_mouse("offset:200,0")
desktop.click()
desktop.type_text(text)
desktop.press_keys("enter")
Elements can be found by text too.
.. code-block:: robotframework
*** Keywords ***
Click New
Click ocr:New
.. code-block:: python
def click_new():
desktop.click('ocr:"New"')
It is recommended to wait for the elements to be visible before
trying any interaction. You can also pass ``region`` objects as locators.
.. code-block:: robotframework
*** Keywords ***
Click New
${region}= Wait For element ocr:New
Click ${region}
.. code-block:: python
def click_new():
region = desktop.wait_for_element("ocr:New")
desktop.click(region)
Another way to find elements by offsetting from an anchor:
.. code-block:: robotframework
*** Keywords ***
Type Notes
[Arguments] ${text}
Click With Offset ocr:Notes 500 0
Type Text ${text}
.. code-block:: python
def type_notes(text):
desktop.click_with_offset("ocr:Notes", 500, 0)
desktop.type_text(text)
""" # noqa: E501
ROBOT_LIBRARY_SCOPE = "GLOBAL"
ROBOT_LIBRARY_DOC_FORMAT = "REST"
def __init__(self, locators_path: Optional[str] = None):
self.locators_path = locators_path
self.logger = logging.getLogger(__name__)
self.buffer = Buffer(self.logger)
# Register keyword libraries to LibCore
libraries = [
ApplicationKeywords(self),
ClipboardKeywords(self),
FinderKeywords(self),
KeyboardKeywords(self),
MouseKeywords(self),
ScreenKeywords(self),
TextKeywords(self),
]
super().__init__(libraries) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Desktop/__init__.py | 0.814864 | 0.404507 | __init__.py | pypi |
from typing import Any
from RPA.core.locators import LocatorType
from RPA.Desktop.keywords import LibraryContext, keyword
def to_key(key: str, escaped=False) -> Any:
"""Convert key string to correct enum value."""
# pylint: disable=C0415
from pynput_robocorp.keyboard import Key, KeyCode
if isinstance(key, (Key, KeyCode)):
return key
value = str(key).lower().strip()
# Check for modifier or function key, e.g. ctrl or f4
try:
return Key[value]
except KeyError:
pass
# Check for individual character
if len(value) == 1:
try:
return KeyCode.from_char(value, escaped=escaped)
except ValueError:
pass
raise ValueError(f"Invalid key: {key}")
class KeyboardKeywords(LibraryContext):
"""Keywords for sending inputs through an (emulated) keyboard."""
def __init__(self, ctx):
super().__init__(ctx)
try:
# pylint: disable=C0415
from pynput_robocorp.keyboard import Controller
self._keyboard = Controller()
self._error = None
except ImportError as exc:
self._error = exc
@keyword
def type_text(self, text: str, *modifiers: str, enter: bool = False) -> None:
"""Type text one letter at a time.
:param text: Text to write
:param modifiers: Modifier or functions keys held during typing
:param enter: Press Enter / Return key after typing text
Example:
.. code-block:: robotframework
Type text this text will be uppercase shift
"""
if self._error:
raise self._error
keys = [to_key(key) for key in modifiers]
with self.buffer():
with self._keyboard.pressed(*keys):
self._keyboard.type(text)
if enter:
self.press_keys("enter")
@keyword
def press_keys(self, *keys: str) -> None:
"""Press multiple keys down simultaneously.
:param keys: Keys to press
Example:
.. code-block:: robotframework
Press keys ctrl alt delete
Press keys ctrl a
Press keys ctrl c
${all_text}= Get clipboard value
Log Text box content was: ${all_text}
"""
if self._error:
raise self._error
keys = [to_key(key, escaped=True) for key in keys]
self.logger.info("Pressing keys: %s", ", ".join(str(key) for key in keys))
with self.buffer():
for key in keys:
self._keyboard.press(key)
for key in reversed(keys):
self._keyboard.release(key)
@keyword
def type_text_into(
self, locator: LocatorType, text: str, clear: bool = False, enter: bool = False
) -> None:
"""Type text at the position indicated by given locator.
:param locator: Locator of input element
:param text: Text to write
:param clear: Clear element before writing
:param enter: Press Enter / Return key after typing text
Example:
.. code-block:: robotframework
Type text into LoginForm.Name Marky Mark
Type text into LoginForm.Password ${PASSWORD}
"""
if self._error:
raise self._error
self.ctx.click(locator)
if clear:
self.press_keys("ctrl", "a")
self.press_keys("delete")
self.type_text(text, enter=enter) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Desktop/keywords/keyboard.py | 0.857097 | 0.223716 | keyboard.py | pypi |
import time
from typing import Callable, List, Optional, Union
from PIL import Image
from RPA.Desktop.keywords import (
LibraryContext,
keyword,
screen,
ElementNotFound,
MultipleElementsFound,
TimeoutException,
HAS_RECOGNITION,
)
from RPA.core.geometry import Point, Region, Undefined
from RPA.core.locators import (
Locator,
LocatorType,
PointLocator,
OffsetLocator,
RegionLocator,
SizeLocator,
ImageLocator,
OcrLocator,
syntax,
)
if HAS_RECOGNITION:
from RPA.recognition import templates, ocr # pylint: disable=no-name-in-module
Geometry = Union[Point, Region, Undefined]
def ensure_recognition():
if not HAS_RECOGNITION:
raise ValueError(
"Locator type not supported, please install the "
"rpaframework-recognition package"
)
def transform(
regions: List[Region], source: Region, destination: Region
) -> List[Region]:
"""Transform given regions from a local coordinate system to a
global coordinate system.
Takes into account location and scaling of the regions.
Assumes that the aspect ratio does not change.
:param regions: List of regions to transform
:param source: Dimensions of local coordinate system
:param destination: Position/scale of local coordinates in the global scope
"""
scale = float(destination.height) / float(source.height)
transformed = []
for region in regions:
region = region.scale(scale)
region = region.move(destination.left, destination.top)
transformed.append(region)
return transformed
def clamp(minimum: float, value: float, maximum: float) -> float:
"""Clamp value between given minimum and maximum."""
return max(minimum, min(value, maximum))
class FinderKeywords(LibraryContext):
"""Keywords for locating elements."""
def __init__(self, ctx):
super().__init__(ctx)
self._resolver = syntax.Resolver(self._find, self.locators_path)
self.timeout = 3.0
if HAS_RECOGNITION:
self.confidence = templates.DEFAULT_CONFIDENCE
else:
self.confidence = 80.0
def _find(self, base: Geometry, locator: LocatorType) -> List:
"""Internal method for resolving and searching locators."""
if isinstance(locator, (Region, Point)):
return [locator]
self.logger.debug("Finding locator: %s", locator)
finders = {
PointLocator: self._find_point,
OffsetLocator: self._find_offset,
RegionLocator: self._find_region,
SizeLocator: self._find_size,
ImageLocator: self._find_templates,
OcrLocator: self._find_ocr,
}
for klass, finder in finders.items():
if isinstance(locator, klass):
return finder(base, locator)
raise NotImplementedError(f"Unsupported locator: {locator}")
def _find_point(self, base: Geometry, point: PointLocator):
"""Find absolute point on screen. CAn not be based on existing value."""
if not isinstance(base, Undefined):
self.logger.warning("Using absolute point coordinates")
result = Point(point.x, point.y)
return [result]
def _find_offset(self, base: Geometry, offset: OffsetLocator):
"""Find pixel offset from given base value, or if no base,
offset from current mouse position.
"""
if isinstance(base, Undefined):
position = self.ctx.get_mouse_position()
elif isinstance(base, Region):
position = base.center
else:
position = base
result = position.move(offset.x, offset.y)
return [result]
def _find_region(self, base: Geometry, region: RegionLocator):
"""Find absolute region on screen. Can not be based on existing value."""
if not isinstance(base, Undefined):
self.logger.warning("Using absolute region coordinates")
position = Region(region.left, region.top, region.right, region.bottom)
return [position]
def _find_size(self, base: Geometry, size: SizeLocator):
"""Find region of fixed size around base, or origin if no base defined."""
if isinstance(base, Undefined):
return Region.from_size(0, 0, size.width, size.height)
if isinstance(base, Region):
center = base.center
else:
center = base
left = center.x - size.width // 2
top = center.y - size.height // 2
result = Region.from_size(left, top, size.width, size.height)
return [result]
def _find_templates(self, base: Geometry, locator: ImageLocator) -> List[Region]:
"""Find all regions that match given image template,
inside the combined virtual display.
"""
ensure_recognition()
if isinstance(base, Undefined):
region = None
elif isinstance(base, Region):
region = base
else:
raise ValueError(f"Unsupported search specifier for template: {base}")
confidence = locator.confidence or self.confidence
self.logger.info(
"Searching for image '%s' (region: %s, confidence: %.1f)",
locator.path,
region or "display",
confidence,
)
def finder(image: Image.Image) -> List[Region]:
try:
return templates.find(
image=image,
template=locator.path,
confidence=confidence,
region=region,
)
except templates.ImageNotFoundError:
return []
return self._find_from_displays(finder)
def _find_ocr(self, base: Geometry, locator: OcrLocator) -> List[Region]:
"""Find the position of all blocks of text that match the given string,
inside the combined virtual display.
"""
ensure_recognition()
if isinstance(base, Undefined):
region = None
elif isinstance(base, Region):
region = base
else:
raise ValueError(f"Unsupported search specifier for OCR: {base}")
confidence = locator.confidence or self.confidence
language = locator.language
self.logger.info(
"Searching for text '%s' (region: %s, confidence: %.1f, language: %s)",
locator.text,
region or "display",
confidence,
language or "Not set",
)
def finder(image: Image.Image) -> List[Region]:
matches = ocr.find(
image=image,
text=locator.text,
confidence=confidence,
region=region,
language=language,
)
return [match["region"] for match in matches]
return self._find_from_displays(finder)
def _find_from_displays(
self, finder: Callable[[Image.Image], List[Region]]
) -> List[Region]:
"""Call finder function for each display and return
a list of found regions.
:param finder: Callable that searches an image
"""
matches = []
screenshots = []
# Search all displays, and map results to combined virtual display
start_time = time.time()
for display in screen.displays():
image = screen.grab(display)
regions = finder(image)
for region in regions:
region = region.resize(5)
screenshot = image.crop(region.as_tuple())
screenshots.append(screenshot)
local = Region.from_size(0, 0, image.size[0], image.size[1])
regions = transform(regions, local, display)
matches.extend(regions)
# Log matches and preview images
duration = time.time() - start_time
plural = "es" if len(matches) != 1 else ""
self.logger.debug("Searched in %.2f seconds", duration)
self.logger.info("Found %d match%s", len(matches), plural)
for match, screenshot in zip(matches, screenshots):
screen.log_image(screenshot, size=400)
self.logger.info(match)
return matches
@keyword
def find_elements(self, locator: LocatorType) -> List[Geometry]:
"""Find all elements defined by locator, and return their positions.
:param locator: Locator string
Example:
.. code-block:: robotframework
${matches}= Find elements image:icon.png
FOR ${match} IN @{matches}
Log Found icon at ${match.right}, ${match.top}
END
"""
self.logger.info("Resolving locator: %s", locator)
if isinstance(locator, (Locator, Region, Point)):
return self._find(Undefined(), locator)
else:
return self._resolver.dispatch(str(locator))
@keyword
def find_element(self, locator: LocatorType) -> Geometry:
"""Find an element defined by locator, and return its position.
Raises ``ElementNotFound`` if` no matches were found, or
``MultipleElementsFound`` if there were multiple matches.
:param locator: Locator string
Example:
.. code-block:: robotframework
${match}= Find element image:logo.png
Log Found logo at ${match.right}, ${match.top}
"""
matches = self.find_elements(locator)
if not matches:
raise ElementNotFound(f"No matches found for: {locator}")
if len(matches) > 1:
# TODO: Add run-on-error support and maybe screenshotting matches?
raise MultipleElementsFound(
"Found {count} matches for: {locator} at locations {matches}".format(
count=len(matches), locator=locator, matches=matches
)
)
return matches[0]
@keyword
def wait_for_element(
self,
locator: LocatorType,
timeout: Optional[float] = None,
interval: float = 0.5,
) -> Geometry:
"""Wait for an element defined by locator to exist, or
raise a TimeoutException if none were found within timeout.
:param locator: Locator string
Example:
.. code-block:: robotframework
Wait for element alias:CookieConsent timeout=30
Click image:%{ROBOT_ROOT}/accept.png
"""
if timeout is None:
timeout = self.timeout
interval = float(interval)
end_time = time.time() + float(timeout)
error = "Operation timed out"
while time.time() <= end_time:
start = time.time()
try:
return self.find_element(locator)
except (ElementNotFound, MultipleElementsFound) as err:
error = err
duration = time.time() - start
if duration < interval:
time.sleep(interval - duration)
raise TimeoutException(error)
@keyword
def set_default_timeout(self, timeout: float = 3.0):
"""Set the default time to wait for elements.
:param timeout: Time in seconds
"""
self.timeout = max(0.0, float(timeout))
@keyword
def set_default_confidence(self, confidence: float = None):
"""Set the default template matching confidence.
:param confidence: Value from 1 to 100
"""
if confidence is None:
confidence = templates.DEFAULT_CONFIDENCE if HAS_RECOGNITION else 80.0
self.confidence = clamp(1.0, float(confidence), 100.0) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Desktop/keywords/finder.py | 0.919113 | 0.335705 | finder.py | pypi |
import base64
import os
from itertools import count
from io import BytesIO
from pathlib import Path
from typing import Optional, Union, List, Dict
import mss
from PIL import Image
from robot.api import logger as robot_logger
from robot.running.context import EXECUTION_CONTEXTS
from RPA.core.geometry import Point, Region
from RPA.core.locators import LocatorType
from RPA.Desktop import utils
from RPA.Desktop.keywords import LibraryContext, keyword
from RPA.Robocorp.utils import get_output_dir
if utils.is_windows():
import ctypes
from pywinauto import win32structures
from pywinauto import win32defines
from pywinauto import win32functions
def _draw_outline(region: Region):
"""Win32-based outline drawing for region."""
brush_struct = win32structures.LOGBRUSH()
brush_struct.lbStyle = win32defines.BS_NULL
brush_struct.lbHatch = win32defines.HS_DIAGCROSS
brush = win32functions.CreateBrushIndirect(ctypes.byref(brush_struct))
pen = win32functions.CreatePen(win32defines.PS_SOLID, 2, 0x0000FF)
dc = win32functions.CreateDC("DISPLAY", None, None, None)
try:
win32functions.SelectObject(dc, brush)
win32functions.SelectObject(dc, pen)
win32functions.Rectangle(
dc, region.left, region.top, region.right, region.bottom
)
finally:
win32functions.DeleteObject(brush)
win32functions.DeleteObject(pen)
win32functions.DeleteDC(dc)
def _create_unique_path(template: Union[Path, str]) -> Path:
"""Creates a unique path from template with `{index}` placeholder."""
template = str(template)
if "{index}" not in template:
return Path(template)
for index in count(1):
path = Path(str(template).format(index=index))
if not path.is_file():
return path
raise RuntimeError("Failed to generate unique path") # Should not reach here
def _monitor_to_region(monitor: Dict) -> Region:
"""Convert mss monitor to Region instance."""
return Region.from_size(
monitor["left"], monitor["top"], monitor["width"], monitor["height"]
)
def displays() -> List[Region]:
"""Returns list of display regions, without combined virtual display."""
with mss.mss() as sct:
return [_monitor_to_region(monitor) for monitor in sct.monitors[1:]]
def grab(region: Optional[Region] = None) -> Image.Image:
"""Take a screenshot of either the full virtual display,
or a cropped area of the given region.
"""
with mss.mss() as sct:
display = _monitor_to_region(sct.monitors[0])
if region is not None:
try:
region = region.clamp(display)
screenshot = sct.grab(region.as_tuple())
except ValueError as err:
raise ValueError("Screenshot region outside display bounds") from err
else:
# First monitor is combined virtual display of all monitors
screenshot = sct.grab(display.as_tuple())
return Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX")
def log_image(image: Image.Image, size=1024):
"""Embed image into Robot Framework log."""
if EXECUTION_CONTEXTS.current is None:
return
image = image.copy()
image.thumbnail((int(size), int(size)), Image.ANTIALIAS)
buf = BytesIO()
image.save(buf, format="PNG")
content = base64.b64encode(buf.getvalue()).decode("utf-8")
robot_logger.info(
'<img alt="screenshot" class="rpaframework-desktop-screenshot" '
f'src="data:image/png;base64,{content}" >',
html=True,
)
class ScreenKeywords(LibraryContext):
"""Keywords for reading screen information and content."""
@keyword
def take_screenshot(
self,
path: Optional[str] = None,
locator: Optional[LocatorType] = None,
embed: bool = True,
) -> str:
"""Take a screenshot of the whole screen, or an element
identified by the given locator.
:param path: Path to screenshot. The string ``{index}`` will be replaced with
an index number to avoid overwriting previous screenshots.
:param locator: Element to crop screenshot to
:param embed: Embed screenshot into Robot Framework log
"""
if locator is not None:
element = self.ctx.wait_for_element(locator)
if not isinstance(element, Region):
raise ValueError("Locator must resolve to a region")
image = grab(element)
else:
image = grab()
if path is None:
dirname = get_output_dir(default=Path.cwd())
path = dirname / "desktop-screenshot-{index}.png"
path: Path = _create_unique_path(path).with_suffix(".png")
os.makedirs(path.parent, exist_ok=True)
image.save(path)
self.logger.info("Saved screenshot as '%s'", path)
if embed:
log_image(image)
return str(path)
@keyword
def get_display_dimensions(self) -> Region:
"""Returns the dimensions of the current virtual display,
which is the combined size of all physical monitors.
"""
with mss.mss() as sct:
return _monitor_to_region(sct.monitors[0])
@keyword
def highlight_elements(self, locator: LocatorType):
"""Draw an outline around all matching elements."""
if not utils.is_windows():
raise NotImplementedError("Not supported on non-Windows platforms")
matches = self.ctx.find_elements(locator)
for match in matches:
if isinstance(match, Region):
_draw_outline(match)
elif isinstance(match, Point):
# TODO: Draw a circle instead?
region = Region(match.x - 5, match.y - 5, match.x + 5, match.y + 5)
_draw_outline(region)
else:
raise TypeError(f"Unknown location type: {match}")
@keyword
def define_region(self, left: int, top: int, right: int, bottom: int) -> Region:
"""
Return a new ``Region`` with the given dimensions.
:param left: Left edge coordinate.
:param top: Top edge coordinate.
:param right: Right edge coordinate.
:param bottom: Bottom edge coordinate.
Usage examples:
.. code-block:: robotframework
${region}= Define Region 10 10 50 30
.. code-block:: python
region = desktop.define_region(10, 10, 50, 30)
"""
return Region(left, top, right, bottom)
@keyword
def move_region(self, region: Region, left: int, top: int) -> Region:
"""
Return a new ``Region`` with an offset from the given region.
:param region: The region to move.
:param left: Amount of pixels to move left/right.
:param top: Amount of pixels to move up/down.
Usage examples:
.. code-block:: robotframework
${region}= Find Element ocr:"Net Assets"
${moved_region}= Move Region ${region} 500 0
.. code-block:: python
region = desktop.find_element('ocr:"Net Assets"')
moved_region = desktop.move_region(region, 500, 0)
"""
return region.move(left, top)
@keyword
def resize_region(
self,
region: Region,
left: int = 0,
top: int = 0,
right: int = 0,
bottom: int = 0,
) -> Region:
"""
Return a resized new ``Region`` from a given region.
Extends edges the given amount outward from the center,
i.e. positive left values move the left edge to the left.
:param region: The region to resize.
:param left: Amount of pixels to resize left edge.
:param top: Amount of pixels to resize top edge.
:param right: Amount of pixels to resize right edge.
:param bottom: Amount of pixels to resize bottom edge.
Usage examples:
.. code-block:: robotframework
${region}= Find Element ocr:"Net Assets"
${resized_region}= Resize Region ${region} bottom=10
.. code-block:: python
region = desktop.find_element('ocr:"Net Assets"')
resized_region = desktop.resize_region(region, bottom=10)
"""
return region.resize(left, top, right, bottom) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Desktop/keywords/screen.py | 0.819713 | 0.288644 | screen.py | pypi |
from enum import Enum
from typing import Optional, Any, Union
from RPA.core.locators import LocatorType
from RPA.core.helpers import delay
from RPA.core.geometry import Point, Region
from RPA.Desktop.keywords import LibraryContext, keyword
class Action(Enum):
"""Possible mouse click actions."""
click = 0
left_click = 0
double_click = 1
triple_click = 2
right_click = 3
def to_action(value):
"""Convert value to Action enum."""
if isinstance(value, Action):
return value
sanitized = str(value).lower().strip().replace(" ", "_")
try:
return Action[sanitized]
except KeyError as err:
raise ValueError(f"Unknown mouse action: {value}") from err
def to_button(value):
"""Convert value to Button enum."""
# pylint: disable=C0415
from pynput_robocorp.mouse import Button
if isinstance(value, Button):
return value
sanitized = str(value).lower().strip().replace(" ", "_")
try:
return Button[sanitized]
except KeyError as err:
raise ValueError(f"Unknown mouse button: {value}") from err
def to_point(location):
"""Converted resolved location to single point, for clicking."""
if isinstance(location, Point):
return location
elif isinstance(location, Region):
return location.center
else:
raise TypeError(f"Unknown location type: {location}")
class MouseKeywords(LibraryContext):
"""Keywords for sending inputs through an (emulated) mouse."""
def __init__(self, ctx):
super().__init__(ctx)
try:
# pylint: disable=C0415
from pynput_robocorp.mouse import Controller
self._mouse = Controller()
self._error = None
except ImportError as exc:
self._error = exc
def _move(self, location: Union[Point, Region]) -> None:
"""Move mouse to given location."""
# TODO: Clamp to screen dimensions?
point = to_point(location)
with self.buffer():
self.logger.info("Moving mouse to (%d, %d)", *point)
self._mouse.position = point.as_tuple()
def _click(
self,
action: Action = Action.click,
location: Optional[Union[Point, Region]] = None,
) -> None:
"""Perform defined mouse action, and optionally move to given point first."""
# pylint: disable=C0415
from pynput_robocorp.mouse import Button
action = to_action(action)
if location:
self._move(location)
delay(0.05)
with self.buffer():
self.logger.info("Performing mouse action: %s", action)
if action is Action.click:
self._mouse.click(Button.left)
elif action is Action.double_click:
self._mouse.click(Button.left, 2)
elif action is Action.triple_click:
self._mouse.click(Button.left, 3)
elif action is Action.right_click:
self._mouse.click(Button.right)
else:
# TODO: mypy should handle enum exhaustivity validation
raise ValueError(f"Unsupported action: {action}")
@keyword
def click(
self,
locator: Optional[LocatorType] = None,
action: Action = Action.click,
) -> None:
"""Click at the element indicated by locator.
:param locator: Locator for click position
:param action: Click action, e.g. right click
Example:
.. code-block:: robotframework
Click
Click LoginForm.Button
Click coordinates:500,200 triple click
"""
if self._error:
raise self._error
action = to_action(action)
if locator:
match = self.ctx.wait_for_element(locator)
self._click(action, match)
else:
self._click(action)
@keyword
def click_with_offset(
self,
locator: Optional[LocatorType] = None,
x: int = 0,
y: int = 0,
action: Action = Action.click,
) -> None:
"""Click at a given pixel offset from the given locator.
:param locator: Locator for click start position
:param x: Click horizontal offset in pixels
:param y: Click vertical offset in pixels
:param action: Click action, e.g. right click
Example:
.. code-block:: robotframework
Click with offset Robocorp.Logo y=400
"""
if self._error:
raise self._error
action = to_action(action)
if locator:
position = self.ctx.wait_for_element(locator)
position = to_point(position)
else:
position = self.get_mouse_position()
position = position.move(int(x), int(y))
self._click(action, position)
@keyword
def get_mouse_position(self) -> Point:
"""Get current mouse position in pixel coordinates.
Example:
.. code-block:: robotframework
${position}= Get mouse position
Log Current mouse position is ${position.x}, ${position.y}
"""
if self._error:
raise self._error
x, y = self._mouse.position
return Point(x, y)
@keyword
def move_mouse(self, locator: LocatorType) -> None:
"""Move mouse to given coordinates.
:param locator: Locator for mouse position
Example:
.. code-block:: robotframework
Move mouse Robocorp.Logo
Move mouse offset:0,400
"""
if self._error:
raise self._error
match = self.ctx.wait_for_element(locator)
self._move(match)
@keyword
def press_mouse_button(self, button: Any = "left") -> None:
"""Press down mouse button and keep it pressed."""
if self._error:
raise self._error
button = to_button(button)
with self.buffer():
self.logger.info("Pressing down mouse button: %s", button)
self._mouse.press(button)
@keyword
def release_mouse_button(self, button: Any = "left") -> None:
"""Release mouse button that was previously pressed."""
if self._error:
raise self._error
button = to_button(button)
with self.buffer():
self.logger.info("Releasing mouse button: %s", button)
self._mouse.release(button)
@keyword
def drag_and_drop(
self,
source: LocatorType,
destination: LocatorType,
start_delay: float = 2.0,
end_delay: float = 0.5,
) -> None:
"""Drag mouse from source to destination while holding the left mouse button.
:param source: Locator for start position
:param destination: Locator for destination position
:param start_delay: Delay in seconds after pressing down mouse button
:param end_delay: Delay in seconds before releasing mouse button
"""
if self._error:
raise self._error
src = self.ctx.wait_for_element(source)
dst = self.ctx.wait_for_element(destination)
src = to_point(src)
dst = to_point(dst)
self.logger.info("Dragging from (%d, %d) to (%d, %d)", *src, *dst)
self._move(src)
self.press_mouse_button()
with self.buffer(start_delay):
self._move(dst)
with self.buffer(end_delay):
self.release_mouse_button() | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Desktop/keywords/mouse.py | 0.865878 | 0.257926 | mouse.py | pypi |
import pyperclip
from RPA.core.locators import LocatorType
from RPA.Desktop import utils
from RPA.Desktop.keywords import LibraryContext, keyword
class ClipboardKeywords(LibraryContext):
"""Keywords for interacting with the system clipboard."""
@keyword
def copy_to_clipboard(self, locator: LocatorType) -> str:
"""Read value to system clipboard from given input element.
:param locator: Locator for element
:returns: Current clipboard value
Example:
.. code-block:: robotframework
${value}= Copy to clipboard ResultPage.Counter
Log Copied text: ${value}
"""
if utils.is_macos():
self.ctx.click(locator, "triple click")
self.ctx.press_keys("cmd", "c")
else:
self.ctx.click(locator, "triple click")
self.ctx.press_keys("ctrl", "c")
return self.get_clipboard_value()
@keyword
def paste_from_clipboard(self, locator: LocatorType) -> None:
"""Paste value from system clipboard into given element.
:param locator: Locator for element
Example:
.. code-block:: robotframework
Copy to clipboard coordinates:401,198
Paste from clipboard coordinates:822,710
"""
match = self.ctx.wait_for_element(locator)
text = pyperclip.paste()
self.ctx.click(match)
self.ctx.type_text(str(text))
@keyword
def clear_clipboard(self) -> None:
"""Clear the system clipboard."""
pyperclip.copy("")
@keyword
def get_clipboard_value(self) -> str:
"""Read current value from system clipboard.
Example:
.. code-block:: robotframework
Copy to clipboard coordinates:401,198
${text}= Get clipboard value
Log We just copied '${text}'
"""
return pyperclip.paste()
@keyword
def set_clipboard_value(self, text: str) -> None:
"""Write given value to system clipboard.
Example:
.. code-block:: robotframework
Set clipboard value This is some text.
Paste from clipboard coordinates:822,710
"""
if not isinstance(text, str):
self.logger.debug(f"Non-string input value {text} for clipboard")
pyperclip.copy(str(text)) | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Desktop/keywords/clipboard.py | 0.846197 | 0.333151 | clipboard.py | pypi |
import time
from typing import Optional
from PIL import ImageOps
from RPA.core.geometry import Region
from RPA.Desktop.keywords import LibraryContext, keyword, screen, HAS_RECOGNITION
if HAS_RECOGNITION:
from RPA.recognition import ocr # pylint: disable=no-name-in-module
def ensure_recognition():
if not HAS_RECOGNITION:
raise ValueError(
"Keyword requires OCR features, please install the "
"rpaframework-recognition package"
)
class TextKeywords(LibraryContext):
"""Keywords for reading screen information and content."""
@keyword
def read_text(self, locator: Optional[str] = None, invert: bool = False):
"""Read text using OCR from the screen, or an area of the
screen defined by the given locator.
:param locator: Location of element to read text from
:param invert: Invert image colors, useful for reading white text
on dark background
Usage examples:
.. code-block:: robotframework
${label_region}= Find Element image:label.png
${value_region}= Move Region ${label_region} 100 0
${text}= Read Text ${value_region}
.. code-block:: python
label_region = desktop.find_element("image:label.png")
value_region = desktop.move_region(label_region, 100, 0)
text = desktop.read_text(value_region)
"""
ensure_recognition()
if locator is not None:
element = self.ctx.wait_for_element(locator)
if not isinstance(element, Region):
raise ValueError("Locator must resolve to a region")
self.logger.info("Reading text from element: %s", element)
image = screen.grab(element)
else:
self.logger.info("Reading text from screen")
image = screen.grab()
screen.log_image(image)
if invert:
image = ImageOps.invert(image)
start_time = time.time()
text = ocr.read(image)
self.logger.info("Read text in %.2f seconds", time.time() - start_time)
return text | /rpaframework-26.1.0.tar.gz/rpaframework-26.1.0/src/RPA/Desktop/keywords/text.py | 0.882921 | 0.173236 | text.py | pypi |
from __future__ import print_function
from argparse import ArgumentParser
from plyplus import Grammar, STransformer, \
ParseError, TokenizeError
try:
# Python 2.x and pypy
from itertools import imap as map
from itertools import ifilter as filter
except ImportError:
# Python 3.x already have lazy map
pass
__all__ = [
"parse"
]
__version__ = "0.2.0"
grammar = Grammar(r"""
@start : package ;
package : name extras? specs? comment?;
name : string ;
specs : comparison version (',' comparison version)* ;
comparison : '<' | '<=' | '!=' | '==' | '>=' | '>' | '~=' | '===' ;
version : string ;
extras : '\[' (extra (',' extra)*)? '\]' ;
extra : string ;
comment : '\#.+' ;
@string : '[-A-Za-z0-9_\.]+' ;
SPACES: '[ \t\n]+' (%ignore) (%newline);
""")
class Requirement(object):
def __init__(self, name=None, extras=None, specs=None, comment=None):
self.name = name
self.extras = extras
self.specs = specs
self.comment = comment
def __str__(self):
return "<{0}(name='{1}'>".format(self.__class__.__name__, self.name)
class RTransformer(STransformer):
def package(self, node):
requirement = Requirement()
for key, value in node.tail:
setattr(requirement, key, value)
return requirement
def name(self, node):
return ("name", node.tail[0])
def specs(self, node):
comparisons, versions = node.tail[0::2], node.tail[1::2]
return ("specs", list(zip(comparisons, versions)))
def comparison(self, node):
return node.tail[0]
def version(self, node):
return node.tail[0]
def extras(self, node):
return ("extras", [name for name in node.tail])
def extra(self, node):
return node.tail[0]
def comment(self, node):
return ("comment", node.tail[0])
def _parse(line, g=grammar):
line = line.strip()
if line.startswith("#"):
return None
try:
if line:
return g.parse(line)
else:
return None
except (ParseError, TokenizeError):
message = "Invalid requirements line: '{0}'".format(line)
raise ValueError(message)
def parse(requirements):
"""
Parses given requirements line-by-line.
"""
transformer = RTransformer()
return map(transformer.transform, filter(None, map(_parse, requirements.splitlines())))
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("path", help="path to requirements.txt file")
args = parser.parse_args()
with open(args.path) as source:
requirements = source.read()
for requirement in parse(requirements):
print("Package: {0}".format(requirement.name))
print("Version Specifier: {0}".format(requirement.specs))
print("Extras: {0}".format(requirement.extras))
print("Comment: {0}".format(requirement.comment))
print("-" * 64) | /rparse-0.2.0.tar.gz/rparse-0.2.0/rparse.py | 0.603698 | 0.160694 | rparse.py | pypi |
from __future__ import unicode_literals
import contextlib
import functools
import io
import ntpath
import os
import posixpath
import re
import shutil
import sys
import tempfile
__all__ = ["unicode", "Path", "PY3", "PosixPath", "WindowsPath"]
__version__ = '1.0.0'
PY3 = sys.version_info[0] == 3
if PY3:
unicode = str
else:
unicode = unicode
backend_types = (unicode, bytes)
MAX_CACHE = 128
if hasattr(functools, 'lru_cache'):
memoize1 = functools.lru_cache(MAX_CACHE)
else:
def memoize1(f):
_cache = {}
@functools.wraps(f)
def wrapped(arg):
if arg in _cache:
return _cache[arg]
else:
res = f(arg)
if len(_cache) > MAX_CACHE:
_cache.clear()
_cache[arg] = res
return res
return wrapped
def supports_unicode_filenames(lib):
# Python is bugged; lib.supports_unicode_filenames is wrong
return lib is ntpath
def dict_union(*dcts):
dct = {}
for dct2 in dcts:
dct.update(dct2)
return dct
class AbstractPath(object):
"""An abstract representation of a path.
This represents a path on a system that may not be the current one. It
doesn't provide any way to actually interact with the local file system.
"""
_lib = None
def _to_backend(self, p):
"""Converts something to the correct path representation.
If given a Path, this will simply unpack it, if it's the correct type.
If given the correct backend, it will return that.
If given bytes for unicode of unicode for bytes, it will encode/decode
with a reasonable encoding. Note that these operations can raise
UnicodeError!
"""
if isinstance(p, self._cmp_base):
return p.path
elif isinstance(p, self._backend):
return p
elif self._backend is unicode and isinstance(p, bytes):
return p.decode(self._encoding)
elif self._backend is bytes and isinstance(p, unicode):
return p.encode(self._encoding,
'surrogateescape' if PY3 else 'strict')
else:
raise TypeError("Can't construct a %s from %r" % (
self.__class__.__name__, type(p)))
def __init__(self, *parts):
"""Creates a path from one or more components.
"""
if self._lib is None: # pragma: no cover
raise RuntimeError("Can't create an AbstractPath directly!")
self._backend = (unicode if supports_unicode_filenames(self._lib)
else bytes)
self._sep = self._lib.sep
if self._backend is unicode and isinstance(self._sep, bytes):
self._sep = self._sep.decode('ascii')
elif self._backend is bytes and isinstance(self._sep, unicode):
self._sep = self._sep.encode('ascii')
self.path = self._normpath(
self._lib.join(*[self._to_backend(p) for p in parts]))
@classmethod
def _normpath(cls, p):
"""This gets a pathname into the proper form it will be stored as.
"""
return cls._lib.normpath(p)
@classmethod
def _normcase(cls, p):
"""This gets a pathname into the proper form for equality testing.
"""
return cls._lib.normcase(p)
def __div__(self, other):
"""Joins two paths.
"""
return self.__class__(self, other)
__truediv__ = __div__
def __add__(self, other):
"""Adds a suffix to some path (for example, '.bak').
"""
if not isinstance(other, backend_types):
raise TypeError("+ operator expects a str or bytes object, "
"got %r" % type(other))
other = self._to_backend(other)
if self._to_backend('/') in other or self._sep in other:
raise ValueError("Can't add separators to filename with +, use /")
return self.__class__(self.path + other)
def __eq__(self, other):
"""Compares two paths.
This will ignore the case on systems where it is not relevant. Note
that if two paths are equal, they represent the same file, but the
opposite might not be true.
"""
try:
other = self._to_backend(other)
except TypeError:
return NotImplemented
else:
return (self._normcase(self.path) == self._normcase(other))
# functools.total_ordering is broken (cf http://bugs.python.org/issue10042)
# so we don't use it
def __ne__(self, other):
return not (self == other)
def __lt__(self, other):
"""Compares two paths.
This will ignore the case on systems where it is not relevant.
"""
try:
other = self._to_backend(other)
except TypeError:
return NotImplemented
else:
return self._normcase(self.path) < self._normcase(other)
def __le__(self, other):
"""Compares two paths.
This will ignore the case on systems where it is not relevant.
"""
try:
other = self._to_backend(other)
except TypeError:
return NotImplemented
else:
return self._normcase(self.path) <= self._normcase(other)
def __gt__(self, other):
"""Compares two paths.
This will ignore the case on systems where it is not relevant.
"""
try:
other = self._to_backend(other)
except TypeError:
return NotImplemented
else:
return self._normcase(self.path) > self._normcase(other)
def __ge__(self, other):
"""Compares two paths.
This will ignore the case on systems where it is not relevant.
"""
try:
other = self._to_backend(other)
except TypeError:
return NotImplemented
else:
return self._normcase(self.path) >= self._normcase(other)
def __hash__(self):
return hash(self._normcase(self.path))
def __repr__(self):
"""Prints a representation of the path.
Returns WindowsPath(u'C:\\somedir') or PosixPath(b'/tmp').
It always puts the 'b' or 'u' prefix (nobody likes Python 3.2 anyway).
"""
if self._backend is unicode:
s = repr(self.path)
if PY3:
s = s.encode('ascii', 'backslashreplace').decode('ascii')
if s[0] != 'u':
s = 'u' + s
else:
s = repr(self.path)
if s[0] != 'b':
s = 'b' + s
return '%s(%s)' % (self.__class__.__name__, s)
def __bytes__(self):
"""Gives a bytestring version of the path.
Note that if the path is unicode and contains international characters,
this function will not raise, but the pathname will not be valid. It is
meant for display purposes only; use the ``path`` attribute for a
correct path (which might be bytes or unicode, depending on the
system).
"""
if self._backend is unicode:
return self.path.encode(self._encoding, 'replace')
else:
return self.path
def __unicode__(self):
"""Gives a unicode version of the path.
Note that if the path is binary and contains invalid byte sequences,
this function will not raise, but the pathname will not be valid. It is
meant for display purposes only; use the ``path`` attribute for a
correct path (which might be bytes or unicode, depending on the
system).
"""
if self._backend is bytes:
if PY3:
return self.path.decode(self._encoding, 'surrogateescape')
else:
return self.path.decode(self._encoding, 'replace')
else:
return self.path
if PY3:
__str__ = __unicode__
else:
__str__ = __bytes__
def expand_user(self):
"""Replaces ``~`` or ``~user`` by that user's home directory.
"""
return self.__class__(self._lib.expanduser(self.path))
def expand_vars(self):
"""Expands environment variables in the path.
They might be of the form ``$name`` or ``${name}``; references to
non-existing variables are kept unchanged.
"""
return self.__class__(self._lib.expandvars(self.path))
@property
def parent(self):
"""The parent directory of this path.
"""
p = self._lib.dirname(self.path)
p = self.__class__(p)
return p
@property
def name(self):
"""The name of this path, i.e. the final component without directories.
"""
return self._lib.basename(self.path)
@property
def unicodename(self):
"""The name of this path as unicode.
"""
n = self._lib.basename(self.path)
if self._backend is unicode:
return n
else:
return n.decode(self._encoding, 'replace')
@property
def stem(self):
"""The name of this path without the extension.
"""
return self._lib.splitext(self.name)[0]
@property
def ext(self):
"""The extension of this path.
"""
return self._lib.splitext(self.path)[1]
def split_root(self):
"""Splits this path into a pair (drive, location).
Note that, because all paths are normalized, a root of ``'.'`` will be
returned for relative paths.
"""
if not PY3 and hasattr(self._lib, 'splitunc'):
root, rest = self._lib.splitunc(self.path)
if root:
if rest.startswith(self._sep):
root += self._sep
rest = rest[1:]
return self.__class__(root), self.__class__(rest)
root, rest = self._lib.splitdrive(self.path)
if root:
if rest.startswith(self._sep):
root += self._sep
rest = rest[1:]
return self.__class__(root), self.__class__(rest)
if self.path.startswith(self._sep):
return self.__class__(self._sep), self.__class__(rest[1:])
return self.__class__(''), self
@property
def root(self):
"""The root of this path.
This will be either a root (with optionally a drive name or UNC share)
or ``'.'`` for relative paths.
"""
return self.split_root()[0]
@property
def components(self):
"""Splits this path into its components.
The first component will be the root if this path is relative, then
each component leading to the filename.
"""
return [self.__class__(p) for p in self._components()]
def _components(self):
root, loc = self.split_root()
if root.path != self._to_backend('.'):
components = [root.path]
else:
components = []
if loc.path != self._to_backend('.'):
components.extend(loc.path.split(self._sep))
return components
def ancestor(self, n):
"""Goes up `n` directories.
"""
p = self
for i in range(n):
p = p.parent
return p
def norm_case(self):
"""Removes the case if this flavor of paths is case insensitive.
"""
return self.__class__(self._normcase(self.path))
@property
def is_absolute(self):
"""Indicates whether this path is absolute or relative.
"""
return self.root.path != self._to_backend('.')
def rel_path_to(self, dest):
"""Builds a relative path leading from this one to the given `dest`.
Note that these paths might be both relative, in which case they'll be
assumed to start from the same directory.
"""
dest = self.__class__(dest)
orig_list = self.norm_case()._components()
dest_list = dest._components()
i = -1
for i, (orig_part, dest_part) in enumerate(zip(orig_list, dest_list)):
if orig_part != self._normcase(dest_part):
up = ['..'] * (len(orig_list) - i)
return self.__class__(*(up + dest_list[i:]))
if len(orig_list) <= len(dest_list):
if len(dest_list) > i + 1:
return self.__class__(*dest_list[i + 1:])
else:
return self.__class__('')
else:
up = ['..'] * (len(orig_list) - i - 1)
return self.__class__(*up)
def lies_under(self, prefix):
"""Indicates if the `prefix` is a parent of this path.
"""
orig_list = self.norm_case()._components()
pref_list = self.__class__(prefix).norm_case()._components()
return (len(orig_list) >= len(pref_list) and
orig_list[:len(pref_list)] == pref_list)
class WindowsPath(AbstractPath):
"""An abstract representation of a Windows path.
It is safe to build and use objects of this class even when not running on
Windows.
"""
_lib = ntpath
_encoding = 'windows-1252'
WindowsPath._cmp_base = WindowsPath
class PosixPath(AbstractPath):
"""An abstract representation of a POSIX path.
It is safe to build and use objects of this class even when running on
Windows.
"""
_lib = posixpath
_encoding = 'utf-8'
PosixPath._cmp_base = PosixPath
DefaultAbstractPath = WindowsPath if os.name == 'nt' else PosixPath
try:
import unicodedata
except ImportError:
pass
else:
class MacOSPath(PosixPath):
"""An abstract representation of a path on Mac OS X.
The filesystem on Mac OS X (HFS) normalizes unicode sequences (NFC).
"""
@classmethod
def _normpath(cls, p):
return unicodedata.normalize('NFC',
p.decode('utf-8')).encode('utf-8')
if sys.platform == 'darwin':
DefaultAbstractPath = MacOSPath
class Path(DefaultAbstractPath):
"""A concrete representation of an actual path on this system.
This extends either :class:`~rpaths.WindowsPath` or
:class:`~rpaths.PosixPath` depending on the current system. It adds
concrete filesystem operations.
"""
@property
def _encoding(self):
return sys.getfilesystemencoding()
@classmethod
def cwd(cls):
"""Returns the current directory.
"""
return cls(os.getcwd())
def chdir(self):
"""Changes the current directory to this path.
"""
os.chdir(self.path)
@contextlib.contextmanager
def in_dir(self):
"""Context manager that changes to this directory then changes back.
"""
previous_dir = self.cwd()
self.chdir()
try:
yield
finally:
previous_dir.chdir()
@classmethod
def tempfile(cls, suffix='', prefix=None, dir=None, text=False):
"""Returns a new temporary file.
The return value is a pair (fd, path) where fd is the file descriptor
returned by :func:`os.open`, and path is a :class:`~rpaths.Path` to it.
:param suffix: If specified, the file name will end with that suffix,
otherwise there will be no suffix.
:param prefix: Is specified, the file name will begin with that prefix,
otherwise a default prefix is used.
:param dir: If specified, the file will be created in that directory,
otherwise a default directory is used.
:param text: If true, the file is opened in text mode. Else (the
default) the file is opened in binary mode. On some operating
systems, this makes no difference.
The file is readable and writable only by the creating user ID.
If the operating system uses permission bits to indicate whether a
file is executable, the file is executable by no one. The file
descriptor is not inherited by children of this process.
The caller is responsible for deleting the file when done with it.
"""
if prefix is None:
prefix = tempfile.template
if dir is not None:
# Note that this is not safe on Python 2
# There is no work around, apart from not using the tempfile module
dir = str(Path(dir))
fd, filename = tempfile.mkstemp(suffix, prefix, dir, text)
return fd, cls(filename).absolute()
@classmethod
def tempdir(cls, suffix='', prefix=None, dir=None):
"""Returns a new temporary directory.
Arguments are as for :meth:`~rpaths.Path.tempfile`, except that the
`text` argument is not accepted.
The directory is readable, writable, and searchable only by the
creating user.
The caller is responsible for deleting the directory when done with it.
"""
if prefix is None:
prefix = tempfile.template
if dir is not None:
# Note that this is not safe on Python 2
# There is no work around, apart from not using the tempfile module
dir = str(Path(dir))
dirname = tempfile.mkdtemp(suffix, prefix, dir)
return cls(dirname).absolute()
def absolute(self):
"""Returns a normalized absolutized version of the path.
"""
return self.__class__(self._lib.abspath(self.path))
def rel_path_to(self, dest):
"""Builds a relative path leading from this one to another.
Note that these paths might be both relative, in which case they'll be
assumed to be considered starting from the same directory.
Contrary to :class:`~rpaths.AbstractPath`'s version, this will also
work if one path is relative and the other absolute.
"""
return super(Path, self.absolute()).rel_path_to(Path(dest).absolute())
def relative(self):
"""Builds a relative version of this path from the current directory.
This is the same as ``Path.cwd().rel_path_to(thispath)``.
"""
return self.cwd().rel_path_to(self)
def resolve(self):
"""Expands the symbolic links in the path.
"""
return self.__class__(self._lib.realpath(self.path))
def listdir(self, pattern=None):
"""Returns a list of all the files in this directory.
The special entries ``'.'`` and ``'..'`` will not be returned.
:param pattern: A pattern to match directory entries against.
:type pattern: NoneType | Callable | Pattern | unicode | bytes
"""
files = [self / self.__class__(p) for p in os.listdir(self.path)]
if pattern is None:
pass
elif callable(pattern):
files = filter(pattern, files)
else:
if isinstance(pattern, backend_types):
if isinstance(pattern, bytes):
pattern = pattern.decode(self._encoding, 'replace')
start, full_re, _int_re = pattern2re(pattern)
elif isinstance(pattern, Pattern):
start, full_re = pattern.start_dir, pattern.full_regex
else:
raise TypeError("listdir() expects pattern to be a callable, "
"a regular expression or a string pattern, "
"got %r" % type(pattern))
# If pattern contains slashes (other than first and last chars),
# listdir() will never match anything
if start:
return []
files = [f for f in files if full_re.search(f.unicodename)]
return files
def recursedir(self, pattern=None, top_down=True, follow_links=False,
handle_errors=None):
"""Recursively lists all files under this directory.
:param pattern: An extended patterns, where:
* a slash '/' always represents the path separator
* a backslash '\' escapes other special characters
* an initial slash '/' anchors the match at the beginning of the
(relative) path
* a trailing '/' suffix is removed
* an asterisk '*' matches a sequence of any length (including 0)
of any characters (except the path separator)
* a '?' matches exactly one character (except the path separator)
* '[abc]' matches characters 'a', 'b' or 'c'
* two asterisks '**' matches one or more path components (might
match '/' characters)
:type pattern: NoneType | Callable | Pattern | unicode | bytes
:param follow_links: If False, symbolic links will not be followed (the
default). Else, they will be followed, but directories reached
through different names will *not* be listed multiple times.
:param handle_errors: Can be set to a callback that will be called when
an error is encountered while accessing the filesystem (such as a
permission issue). If set to None (the default), exceptions will be
propagated.
"""
if not self.is_dir():
raise ValueError("recursedir() called on non-directory %s" % self)
start = ''
int_pattern = None
if pattern is None:
pattern = lambda p: True
elif callable(pattern):
pass
else:
if isinstance(pattern, backend_types):
if isinstance(pattern, bytes):
pattern = pattern.decode(self._encoding, 'replace')
start, full_re, int_re = pattern2re(pattern)
elif isinstance(pattern, Pattern):
start, full_re, int_re = \
pattern.start_dir, pattern.full_regex, pattern.int_regex
else:
raise TypeError("recursedir() expects pattern to be a "
"callable, a regular expression or a string "
"pattern, got %r" % type(pattern))
if self._lib.sep != '/':
pattern = lambda p: full_re.search(
unicode(p).replace(self._lib.sep, '/'))
if int_re is not None:
int_pattern = lambda p: int_re.search(
unicode(p).replace(self._lib.sep, '/'))
else:
pattern = lambda p: full_re.search(unicode(p))
if int_re is not None:
int_pattern = lambda p: int_re.search(unicode(p))
if not start:
path = self
else:
path = self / start
if not path.exists():
return []
elif not path.is_dir():
return [path]
return path._recursedir(pattern=pattern, int_pattern=int_pattern,
top_down=top_down, seen=set(),
path=self.__class__(start),
follow_links=follow_links,
handle_errors=handle_errors)
def _recursedir(self, pattern, int_pattern, top_down, seen, path,
follow_links=False, handle_errors=None):
real_dir = self.resolve()
if real_dir in seen:
return
seen.add(real_dir)
try:
dir_list = os.listdir(self.path)
except OSError:
if handle_errors is not None:
handle_errors(self.path)
return
raise
for child in dir_list:
newpath = path / child
child = self / child
is_dir = child.is_dir() and (not child.is_link() or follow_links)
# Fast failing thanks to int_pattern here: if we don't match
# int_pattern, don't try inner files either
matches_pattern = pattern(newpath)
if (not matches_pattern and
int_pattern is not None and not int_pattern(newpath)):
continue
if is_dir and not top_down:
for grandkid in child._recursedir(pattern, int_pattern,
top_down, seen, newpath,
follow_links, handle_errors):
yield grandkid
if matches_pattern:
yield child
if is_dir and top_down:
for grandkid in child._recursedir(pattern, int_pattern,
top_down, seen, newpath,
follow_links, handle_errors):
yield grandkid
def exists(self):
"""True if the file exists, except for broken symlinks where it's
False.
"""
return self._lib.exists(self.path)
def lexists(self):
"""True if the file exists, even if it's a broken symbolic link.
"""
return self._lib.lexists(self.path)
def is_file(self):
"""True if this file exists and is a regular file.
"""
return self._lib.isfile(self.path)
def is_dir(self):
"""True if this file exists and is a directory.
"""
return self._lib.isdir(self.path)
def is_link(self):
"""True if this file exists and is a symbolic link.
"""
return self._lib.islink(self.path)
def is_mount(self):
"""True if this file is a mount point.
"""
return self._lib.ismount(self.path)
def atime(self):
"""Returns the time of last access to this path.
This returns a number of seconds since the epoch.
"""
return self._lib.getatime(self.path)
def ctime(self):
"""Returns the ctime of this path.
On some systems, this is the time of last metadata change, and on
others (like Windows), it is the creation time for path. In any case,
it is a number of seconds since the epoch.
"""
return self._lib.getctime(self.path)
def mtime(self):
"""Returns the time of last modification of this path.
This returns a number of seconds since the epoch.
"""
return self._lib.getmtime(self.path)
def size(self):
"""Returns the size, in bytes, of the file.
"""
return self._lib.getsize(self.path)
if hasattr(os.path, 'samefile'):
def same_file(self, other):
"""Returns True if both paths refer to the same file or directory.
In particular, this identifies hard links.
"""
return self._lib.samefile(self.path, self._to_backend(other))
def stat(self):
return os.stat(self.path)
def lstat(self):
return os.lstat(self.path)
if hasattr(os, 'statvfs'):
def statvfs(self):
return os.statvfs(self.path)
if hasattr(os, 'chmod'):
def chmod(self, mode):
"""Changes the mode of the path to the given numeric `mode`.
"""
return os.chmod(self.path, mode)
if hasattr(os, 'chown'):
def chown(self, uid=-1, gid=-1):
"""Changes the owner and group id of the path.
"""
return os.chown(self.path, uid, gid)
def mkdir(self, name=None, parents=False, mode=0o777):
"""Creates that directory, or a directory under this one.
``path.mkdir(name)`` is a shortcut for ``(path/name).mkdir()``.
:param name: Path component to append to this path before creating the
directory.
:param parents: If True, missing directories leading to the path will
be created too, recursively. If False (the default), the parent of
that path needs to exist already.
:param mode: Permissions associated with the directory on creation,
without race conditions.
"""
if name is not None:
return (self / name).mkdir(parents=parents, mode=mode)
if self.exists():
return
if parents:
os.makedirs(self.path, mode)
else:
os.mkdir(self.path, mode)
return self
def rmdir(self, parents=False):
"""Removes this directory, provided it is empty.
Use :func:`~rpaths.Path.rmtree` if it might still contain files.
:param parents: If set to True, it will also destroy every empty
directory above it until an error is encountered.
"""
if parents:
os.removedirs(self.path)
else:
os.rmdir(self.path)
def remove(self):
"""Removes this file.
"""
os.remove(self.path)
def rename(self, new, parents=False):
"""Renames this path to the given new location.
:param new: New path where to move this one.
:param parents: If set to True, it will create the parent directories
of the target if they don't exist.
"""
if parents:
os.renames(self.path, self._to_backend(new))
else:
os.rename(self.path, self._to_backend(new))
if hasattr(os, 'link'):
def hardlink(self, newpath):
"""Creates a hard link to this path at the given `newpath`.
"""
os.link(self.path, self._to_backend(newpath))
if hasattr(os, 'symlink'):
def symlink(self, target):
"""Create a symbolic link here, pointing to the given `target`.
"""
os.symlink(self._to_backend(target), self.path)
if hasattr(os, 'readlink'):
def read_link(self, absolute=False):
"""Returns the path this link points to.
If `absolute` is True, the target is made absolute.
"""
p = self.__class__(os.readlink(self.path))
if absolute:
return (self.parent / p).absolute()
else:
return p
def copyfile(self, target):
"""Copies this file to the given `target` location.
"""
shutil.copyfile(self.path, self._to_backend(target))
def copymode(self, target):
"""Copies the mode of this file on the `target` file.
The owner is not copied.
"""
shutil.copymode(self.path, self._to_backend(target))
def copystat(self, target):
"""Copies the permissions, times and flags from this to the `target`.
The owner is not copied.
"""
shutil.copystat(self.path, self._to_backend(target))
def copy(self, target):
"""Copies this file the `target`, which might be a directory.
The permissions are copied.
"""
shutil.copy(self.path, self._to_backend(target))
def copytree(self, target, symlinks=False):
"""Recursively copies this directory to the `target` location.
The permissions and times are copied (like
:meth:`~rpaths.Path.copystat`).
If the optional `symlinks` flag is true, symbolic links in the source
tree result in symbolic links in the destination tree; if it is false,
the contents of the files pointed to by symbolic links are copied.
"""
shutil.copytree(self.path, self._to_backend(target), symlinks)
def rmtree(self, ignore_errors=False):
"""Deletes an entire directory.
If ignore_errors is True, failed removals will be ignored; else,
an exception will be raised.
"""
shutil.rmtree(self.path, ignore_errors)
def move(self, target):
"""Recursively moves a file or directory to the given target location.
"""
shutil.move(self.path, self._to_backend(target))
def open(self, mode='r', name=None, **kwargs):
"""Opens this file, or a file under this directory.
``path.open(mode, name)`` is a shortcut for ``(path/name).open(mode)``.
Note that this uses :func:`io.open()` which behaves differently from
:func:`open()` on Python 2; see the appropriate documentation.
:param name: Path component to append to this path before opening the
file.
"""
if name is not None:
return io.open((self / name).path, mode=mode, **kwargs)
else:
return io.open(self.path, mode=mode, **kwargs)
@contextlib.contextmanager
def rewrite(self, mode='r', name=None, temp=None, tempext='~', **kwargs):
r"""Replaces this file with new content.
This context manager gives you two file objects, (r, w), where r is
readable and has the current content of the file, and w is writable
and will replace the file at the end of the context (unless an
exception is raised, in which case it is rolled back).
Keyword arguments will be used for both files, unless they are prefixed
with ``read_`` or ``write_``. For instance::
with Path('test.txt').rewrite(read_newline='\n',
write_newline='\r\n') as (r, w):
w.write(r.read())
:param name: Path component to append to this path before opening the
file.
:param temp: Temporary file name to write, and then move over this one.
By default it's this filename with a ``~`` suffix.
:param tempext: Extension to add to this file to get the temporary file
to write then move over this one. Defaults to ``~``.
"""
if name is not None:
pathr = self / name
else:
pathr = self
for m in 'war+':
mode = mode.replace(m, '')
# Build options
common_kwargs = {}
readable_kwargs = {}
writable_kwargs = {}
for key, value in kwargs.items():
if key.startswith('read_'):
readable_kwargs[key[5:]] = value
elif key.startswith('write_'):
writable_kwargs[key[6:]] = value
else:
common_kwargs[key] = value
readable_kwargs = dict_union(common_kwargs, readable_kwargs)
writable_kwargs = dict_union(common_kwargs, writable_kwargs)
with pathr.open('r' + mode, **readable_kwargs) as readable:
if temp is not None:
pathw = Path(temp)
else:
pathw = pathr + tempext
try:
pathw.remove()
except OSError:
pass
writable = pathw.open('w' + mode, **writable_kwargs)
try:
yield readable, writable
except Exception:
# Problem, delete writable
writable.close()
pathw.remove()
raise
else:
writable.close()
# Alright, replace
pathr.copymode(pathw)
pathr.remove()
pathw.rename(pathr)
class Pattern(object):
"""A pattern that paths can be matched against.
You can check if a filename matches this pattern by using `matches()`, or
pass it to the `Path.listdir` and `Path.recursedir` methods.
`may_contain_matches()` is a special method which you can feed directories
to; if it returns False, no path under that one will match the pattern.
>>> pattern = Pattern('/usr/l*/**.so')
>>> pattern.matches('/usr/local/irc/mod_user.so')
True
>>> pattern.matches('/usr/bin/thing.so')
False
>>> pattern.may_contain_matches('/usr')
True
>>> pattern.may_contain_matches('/usr/lib')
True
>>> pattern.may_contain_matches('/usr/bin')
False
"""
def __init__(self, pattern):
if isinstance(pattern, bytes):
pattern = pattern.decode(sys.getfilesystemencoding())
self.start_dir, self.full_regex, self.int_regex = pattern2re(pattern)
@staticmethod
def _prepare_path(path):
# Here we want to force the use of replacement characters.
# The __unicode__ implementation might use 'surrogateescape'
replace = False
if isinstance(path, AbstractPath):
replace = path._lib.sep if path._lib.sep != '/' else None
path = path.path
else:
replace = Path._lib.sep if Path._lib.sep != '/' else None
if isinstance(path, bytes):
path = path.decode(sys.getfilesystemencoding(), 'replace')
elif not isinstance(path, unicode):
raise TypeError("Expected a path, got %r" % type(path))
if path.startswith('/'):
path = path[1:]
if replace is not None:
path = path.replace(replace, '/')
return path
def matches(self, path):
"""Tests if the given path matches the pattern.
Note that the unicode translation of the patch is matched, so
replacement characters might have been added.
"""
path = self._prepare_path(path)
return self.full_regex.search(path) is not None
def may_contain_matches(self, path):
"""Tests whether it's possible for paths under the given one to match.
If this method returns None, no path under the given one will match the
pattern.
"""
path = self._prepare_path(path)
return self.int_regex.search(path) is not None
no_special_chars = re.compile(r'^(?:[^\\*?\[\]]|\\.)*$')
def patterncomp2re(component):
if component == '**':
return '.*'
i, n = 0, len(component)
regex = ''
while i < n:
c = component[i]
if c == '\\':
i += 1
if i < n:
regex += re.escape(component[i])
elif c == '*':
regex += '[^/]*'
elif c == '?':
regex += '[^/]'
elif c == '[':
i += 1
regex += '['
c = component[i]
while c != ']':
if c == '/':
raise ValueError("Slashes not accepted in [] classes")
regex += re.escape(c)
i += 1
c = component[i]
regex += ']'
else:
regex += re.escape(c)
i += 1
return regex
@memoize1
def pattern2re(pattern):
"""Makes a unicode regular expression from a pattern.
Returns ``(start, full_re, int_re)`` where:
* `start` is either empty or the subdirectory in which to start searching,
* `full_re` is a regular expression object that matches the requested
files, i.e. a translation of the pattern
* `int_re` is either None of a regular expression object that matches
the requested paths or their ancestors (i.e. if a path doesn't match
`int_re`, no path under it will match `full_re`)
This uses extended patterns, where:
* a slash '/' always represents the path separator
* a backslash '\' escapes other special characters
* an initial slash '/' anchors the match at the beginning of the
(relative) path
* a trailing '/' suffix is removed
* an asterisk '*' matches a sequence of any length (including 0) of any
characters (except the path separator)
* a '?' matches exactly one character (except the path separator)
* '[abc]' matches characters 'a', 'b' or 'c'
* two asterisks '**' matches one or more path components (might match '/'
characters)
"""
pattern_segs = filter(None, pattern.split('/'))
# This anchors the first component either at the start of the string or at
# the start of a path component
if not pattern:
return '', re.compile(''), None
elif '/' in pattern:
full_regex = '^' # Start at beginning of path
int_regex = []
int_regex_done = False
start_dir = []
start_dir_done = False
else:
full_regex = '(?:^|/)' # Skip any number of full components
int_regex = None
int_regex_done = True
start_dir = []
start_dir_done = True
# Handles each component
for pnum, pat in enumerate(pattern_segs):
comp = patterncomp2re(pat)
# The first component is already anchored
if pnum > 0:
full_regex += '/'
full_regex += comp
if not int_regex_done:
if pat == '**':
int_regex_done = True
else:
int_regex.append(comp)
if not start_dir_done and no_special_chars.match(pat):
start_dir.append(pat)
else:
start_dir_done = True
full_regex = re.compile(full_regex.rstrip('/') + '$')
if int_regex is not None:
n = len(int_regex)
int_regex_s = ''
for i, c in enumerate(reversed(int_regex)):
if i == n - 1: # Last iteration (first component)
int_regex_s = '^(?:%s%s)?' % (c, int_regex_s)
elif int_regex_s:
int_regex_s = '(?:/%s%s)?' % (c, int_regex_s)
else: # First iteration (last component)
int_regex_s = '(?:/%s)?' % c
int_regex = re.compile(int_regex_s + '$')
start_dir = '/'.join(start_dir)
return start_dir, full_regex, int_regex | /rpaths-1.0.0.tar.gz/rpaths-1.0.0/rpaths.py | 0.506836 | 0.166913 | rpaths.py | pypi |
class ListFile(object):
def __init__(self, file_):
super(ListFile, self).__init__()
self.file = file_
self.positions = []
self.eof = 0
self.step = 1
self.lazy = True
def __iter__(self):
idx = 0
while True:
try:
yield self[idx]
except IndexError:
break
idx += 1
def __len__(self):
if not self.lazy:
return len(self.positions)
idx = len(self.positions)
while True:
try:
self[idx]
except IndexError:
break
idx += 1
self.lazy = False
return idx
def __getitem__(self, key):
if isinstance(key, slice):
result = ListFile(self.file)
if key.start < 0 or key.stop < 0:
len(self)
result.positions = self.positions[key]
result.eof = self.eof
result.lazy = False
elif key.stop < len(self.positions):
result.positions = self.positions[key]
result.eof = self.eof
result.lazy = False
elif key.start < len(self.positions):
result.positions = self.positions[
key.start:len(self.positions)-1:key.step]
result.eof = self.eof
return result
if not self.lazy:
self.file.seek(self.positions[key])
return self.file.readline()
if key < 0:
# For negative indexes the whole file must be stepped
# through anyways. Use len() to do so and then delegate to
# the non-lazy version
len(self)
return self[key]
idx = len(self.positions)-1
if idx < key:
self.file.seek(self.eof)
idx += 1
while idx < key:
self.positions.append(self.file.tell())
for step in xrange(self.step):
self.file.readline()
idx += 1
pos = self.file.tell()
line = self.file.readline()
self.eof = self.file.tell()
if line == '':
self.lazy = False
raise IndexError('Reached EOF')
self.positions.append(pos)
return line
else:
self.file.seek(self.positions[key])
return self.file.readline() | /rpatterson.listfile-0.1.tar.gz/rpatterson.listfile-0.1/rpatterson/listfile/__init__.py | 0.410284 | 0.193128 | __init__.py | pypi |
import sys
import itertools
import optparse
import logging
import difflib
import re
from rpatterson import listfile
def compile_value(option, opt, value, parser):
value = re.compile(value)
setattr(parser.values, option.dest, value)
parser = optparse.OptionParser(description=__doc__)
parser.add_option(
"-m", "--min", metavar="NUM", default=0.01, type="float",
help="Minimum length of duplicated sequence. "
"If NUM is less than one, use a proportion of the total "
"number of lines, otherwise NUM is a number of lines. "
"[default: %default]")
parser.add_option(
"-p", "--pattern", metavar="REGEXP", default=re.compile(r'\s+'),
action="callback", type="string", callback=compile_value,
help="Regular expression pattern used to normalize strings in "
"sequences of strings. The default matches all whitespace. "
"Use an empty string to disable. [default: '\s+']")
parser.add_option(
"-r", "--repl", metavar="STRING", default=' ',
help="String to replace matches of pattern with for normalizing "
"strings in sequences of strings. [default: '%default']")
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('rpatterson.stripdupes')
class ReSubString(str):
def __new__(self, object_, pattern=parser.defaults['pattern'],
repl=parser.defaults['repl'], **kw):
return super(ReSubString, self).__new__(self, object_, **kw)
def __init__(self, object_, pattern=parser.defaults['pattern'],
repl=parser.defaults['repl'], **kw):
super(ReSubString, self).__init__(**kw)
self.sub = pattern.sub(repl, self)
def __hash__(self):
return hash(self.sub)
def __eq__(self, other):
return self.sub.__eq__(other.sub)
class SeqWrapper(object):
def __init__(self, seq, factory=ReSubString):
self.seq = seq
self.factory = factory
def __getitem__(self, key):
return self.factory(self.seq[key])
def __len__(self):
return len(self.seq)
class SequenceMatcher(difflib.SequenceMatcher, object):
def __init__(self, min_=parser.defaults['min'],
pattern=parser.defaults['pattern'],
repl=parser.defaults['repl'], **kw):
self.min = min_
self.pattern = pattern
self.repl = repl
super(SequenceMatcher, self).__init__(**kw)
def set_seq2(self, b):
if self.pattern:
b = SeqWrapper(
b, factory=lambda object_: ReSubString(
object_, pattern=self.pattern, repl=self.repl))
super(SequenceMatcher, self).set_seq2(b)
def get_matching_blocks(self):
sorted_ = self.get_sorted_duplicates()
matches = []
append = matches.append
if sorted_:
logger.info('Finding longest from %s duplicated sequences'
% len(sorted_))
else:
logger.info('No duplicated sequences found')
# prefer longest matches, then latter matches
for k, j in sorted_:
i = j-k+1
for match_i, match_j in matches:
if match_i <= j < match_j:
break
else:
append((i, j+1))
return matches
def get_sorted_duplicates(self):
if self.min < 1:
min_ = int(round(len(self.b)*self.min))
else:
min_ = int(round(self.min))
return sorted(
itertools.imap(tuple, itertools.imap(
reversed, (
item for item in
itertools.chain(*itertools.imap(
dict.iteritems,
self.get_duplicates_by_len().itervalues()))
if item[1] >= min_)
)),
reverse=True)
def get_duplicates_by_len(self):
# optimizations
islice = itertools.islice
b, b2j, i2j2k = self.b, self.b2j, {}
b2j_get = b2j.get
i2j2k_pop = i2j2k.pop
b_len = len(b)
info = logger.info
default = []
for i, item in enumerate(b):
n = i+1
if n%10000 == 0:
info('Processing #%s of %s (%s%%)'
% (n, b_len, n*100/b_len))
js = b2j_get(item, default)
if len(js) <= 1:
continue
# we have at least one match, advance i2j2k
j2k = i2j2k[i] = i2j2k_pop(i-1, {}) # per i
# optimizations
j2k_pop = j2k.pop
new_j2k = {}
# the first item is i itself, skip
for j in islice(js, 1, None):
# prev is used to avoid doing two dict lookups
prev = j2k_pop(j-1, default)
if prev is default:
k = 1
else:
k = prev + 1
if j < i+k:
# ignore duplicates that overlap with the first
if prev is not default:
j2k[j-1] = prev
continue
new_j2k[j] = k
j2k.update(new_j2k)
return i2j2k
def omit_ranges(seq, ranges):
i = 0
for j, k in ranges:
yield seq[i:j]
i = k
yield seq[i:]
def strip(seq, min_=parser.defaults['min'],
pattern=parser.defaults['pattern'],
repl=parser.defaults['repl']):
matcher = SequenceMatcher(min_=min_, pattern=pattern, repl=repl)
matcher.set_seq2(seq)
matches = sorted(matcher.get_matching_blocks())
if matches:
logger.info(
('Removing the following %s duplicate sequences: '
% len(matches)) +
' '.join(repr(match) for match in matches))
return itertools.chain(*omit_ranges(seq, matches))
def main(args=None):
options, args = parser.parse_args(args=args)
if args:
parser.error(
'Does not accept arguments, use standard input and outpt')
sys.stdout.writelines(
strip(listfile.ListFile(sys.stdin), options.min))
if __name__ == '__main__':
main() | /rpatterson.stripdupes-0.1.tar.gz/rpatterson.stripdupes-0.1/rpatterson/stripdupes/__init__.py | 0.47171 | 0.157008 | __init__.py | pypi |
from collections import ChainMap
from functools import partial
import re
from schema import And, Optional, Or, Regex, Schema
def sorted_versions(versions):
return sorted(
versions,
key=lambda v: version_key(v["version"]),
reverse=True,
)
def is_sorted_versions(versions):
return versions == sorted_versions(versions)
def is_value_unique(key):
def fn(data):
values = [v[key] for v in data]
return len(values) == len(set(values))
fn.__name__ = "is_{value}_unique".format(value=key)
return fn
def is_version_ids_unique(releases):
is_version_unique = is_value_unique("version")
return is_version_unique((v for r in releases for v in r["versions"]))
sha_regex = r"^[0-9a-f]{40}$"
version_regex = (
r"^(?P<version>r?"
r"(?P<major>[0-9]+)\."
r"(?P<minor>[0-9]+)\."
r"(?P<patch>[0-9]+)"
r"(-(?P<prerelease>alpha|beta|rc)\."
r"(?P<prerelease_version>[0-9]+))?)$"
)
version_id_schema = Regex(version_regex)
version_sha_schema = Regex(sha_regex)
version_schema = Schema(
{
"version": version_id_schema,
"sha": version_sha_schema,
},
)
comparison_added_version_schema = Schema(
And(
{
And(str, len): {
"added": {
"releases": And(
[
{
Optional("series"): And(str, len),
"versions": And(
[version_schema],
lambda vs: len(vs) == 1,
),
}
],
lambda rs: len(rs) == 1,
)
},
"deleted": {},
}
},
lambda cs: len(cs) == 1,
)
)
repo_url_schema = Regex(r"^https://github.com/.+")
comparison_operator_regex = r"(?P<comparison_operator>(=|!)=|(<|>)=?)"
constraint_regex = (
r"(?P<version>r?(?P<major>[0-9]+)"
r"(\.(?P<minor>[0-9]+)"
r"(\.(?P<patch>[0-9]+)"
r"(-(?P<prerelease>alpha|beta|rc)\."
r"(?P<prerelease_version>[0-9]+))?)?)?)"
)
version_constraint_regex = r"^version{op}{version}$".format(
op=comparison_operator_regex,
version=constraint_regex,
)
branch_constraint_regex = r"^branch==(?P<branch_name>.+)$"
branch_constraints_schema = And(
[Regex(branch_constraint_regex)],
lambda cs: len(cs) == 1,
)
constraints_schema = Or(
[Regex(version_constraint_regex)],
branch_constraints_schema,
)
component_single_version_schema = Schema(
{
"name": And(str, len),
"repo_url": repo_url_schema,
"is_product": bool,
"release": {
"series": And(str, len),
"version": version_id_schema,
"sha": version_sha_schema,
},
Optional("artifact_stores", default=[]): And(
[
{
"description": Or(str, None),
"name": And(str, len),
"public_url": And(str, len),
"type": And(str, len),
},
],
is_value_unique("name"),
),
}
)
component_schema = Schema(
{
"name": And(str, len),
"repo_url": repo_url_schema,
"is_product": bool,
"releases": And(
[
{
"series": And(str, len),
"versions": And(
[
version_schema,
],
is_sorted_versions,
),
},
],
is_value_unique("series"),
is_version_ids_unique,
),
Optional("artifact_stores", default=[]): And(
[
{
"description": Or(str, None),
"name": And(str, len),
"public_url": And(str, len),
"type": And(str, len),
},
],
is_value_unique("name"),
),
}
)
dependencies_schema = Schema(
{
Optional("dependencies"): And(
[
{
"name": And(str, len),
"constraints": constraints_schema,
},
],
is_value_unique("name"),
)
}
)
artifacts_file_schema = Schema(
{
"type": "file",
"source": And(str, len),
Optional("dest"): And(str, len),
Optional("expire_after"): And(int, lambda n: n > 0)
}
)
artifacts_log_schema = Schema(
{
"type": "log",
"source": And(str, len)
}
)
artifacts_schema = Schema(
{
Optional("artifacts"):
[
Or(artifacts_file_schema, artifacts_log_schema)
]
}
)
jenkins_schema = Schema(
{
Optional("jenkins"): {
Optional("jjb_paths"): [And(str, len)],
}
}
)
component_metadata_schema = Schema(
dict(
ChainMap(
*(s._schema for s in
(
dependencies_schema,
artifacts_schema,
jenkins_schema,
)
)
)
)
)
component_requirements_schema = Schema(
{
"dependencies": And(
[
{
"name": And(str, len),
"ref": Or(And(str, len), None),
"ref_type": Or(lambda r: r in ("branch", "tag"), None),
"repo_url": repo_url_schema,
"sha": version_sha_schema,
"version": Or(version_id_schema, None),
}
],
is_value_unique("name"),
),
}
)
comparison_added_component_schema = Schema(
And(
{
And(str, len): {
"added": And(component_schema),
"deleted": {},
}
},
lambda cs: len(cs) == 1,
)
)
comparison_added_artifact_stores_schema = Schema(
And(
{
And(str, len): {
"added": {
"artifact_stores": And(
[
{
"description": Or(str, None),
"name": And(str, len),
"public_url": And(str, len),
"type": And(str, len),
},
],
is_value_unique("name"),
),
},
"deleted": {},
}
},
lambda s: len(s) == 1,
)
)
def _version_key(version_id, regex=None):
prerelease_map = {
"alpha": 0,
"beta": 1,
"rc": 2,
None: 3,
}
def int_or_none(x): return x if x is None else int(x)
v = re.match(regex, version_id)
major = int(v.group("major"))
minor = int_or_none(v.group("minor"))
patch = int_or_none(v.group("patch"))
prerelease = prerelease_map[v.group("prerelease")]
prerelease_version = int(v.group("prerelease_version") or 0)
return (major, minor, patch, prerelease, prerelease_version)
version_key = partial(_version_key, regex=version_regex)
constraint_key = partial(_version_key, regex=constraint_regex) | /rpc_component-0.0.2-py3-none-any.whl/rpc_component/schemata.py | 0.722527 | 0.431734 | schemata.py | pypi |
from typing import Optional, Awaitable, Any
import asyncio
import pickle
import json
from aiohttp import web
from rpc_gateway import messages_pb2, errors
SERIALIZABLE_TYPES = (dict, list, tuple, str, int, float, bool, type(None))
def await_sync(awaitable: Awaitable, loop: Optional[asyncio.AbstractEventLoop] = None, timeout: Optional[float] = None) -> Any:
loop = loop or asyncio.get_event_loop()
if loop.is_running():
future = asyncio.run_coroutine_threadsafe(awaitable, loop or asyncio.get_event_loop())
return future.result(timeout=timeout)
else:
try:
return loop.run_until_complete(awaitable)
except asyncio.CancelledError:
pass
def encode_data(data: Any, encoding: messages_pb2.Encoding) -> bytes:
if encoding == messages_pb2.Encoding.PICKLE:
return pickle.dumps(data)
if encoding == messages_pb2.Encoding.JSON:
return json.dumps(data).encode()
raise errors.InvalidEncodingError(f'Invalid message encoding: {encoding}')
def encode_error(error: Exception, encoding: messages_pb2.Encoding) -> bytes:
if encoding == messages_pb2.Encoding.PICKLE:
return pickle.dumps(error)
if encoding == messages_pb2.Encoding.JSON:
return json.dumps(str(error)).encode()
raise errors.InvalidEncodingError(f'Invalid message encoding: {encoding}')
def decode_data(data: bytes, encoding: messages_pb2.Encoding) -> Any:
if len(data) == 0:
return None
if encoding == messages_pb2.Encoding.PICKLE:
return pickle.loads(data)
if encoding == messages_pb2.Encoding.JSON:
return json.loads(data.decode())
raise errors.InvalidEncodingError(f'Invalid message encoding: {encoding}')
def build_response(data: Optional[Any] = None, serialized_data: Optional[bytes] = None, status: Optional['messages_pb2.Status.V'] = messages_pb2.Status.SUCCESS,
id: Optional[int] = None, encoding: Optional['messages_pb2.Encoding.V'] = None):
message = messages_pb2.Message(encoding=encoding)
message.response.status = status
if data is not None:
message.data = pickle.dumps(data)
if serialized_data is not None:
message.data = serialized_data
if id is not None:
message.id = id
return message
def build_error_response(error: Optional[Exception]) -> messages_pb2.Message:
return build_response(status=messages_pb2.Status.ERROR, data=error)
def build_request(method: str, instance: Optional[str] = None, attribute: Optional[str] = None, id: Optional[int] = None,
data: Any = None, encoding: Optional['messages_pb2.Encoding.V'] = None) -> messages_pb2.Message:
request = messages_pb2.Request(method=method, instance=instance, attribute=attribute)
return messages_pb2.Message(id=id, data=data, encoding=encoding, request=request)
def build_http_response(response: messages_pb2.Message) -> web.Response:
data = decode_data(response.data, response.encoding)
return web.json_response(data, status=http_status(response.response.status), headers={'RPC-Status': str(response.response.status)})
def http_status(response_status: 'messages_pb2.Status.V') -> int:
if response_status == messages_pb2.Status.NOT_FOUND:
return 404
if response_status == messages_pb2.Status.LOCKED:
return 423
if response_status == messages_pb2.Status.ERROR:
return 503
return 200
def serializable(data: Any) -> bool:
return isinstance(data, SERIALIZABLE_TYPES) | /rpc_gateway-0.5.2.tar.gz/rpc_gateway-0.5.2/rpc_gateway/utils.py | 0.815122 | 0.217088 | utils.py | pypi |
import argparse
import numpy as np
import matplotlib.pyplot as plt
import pathlib
import sys
import textwrap
from typing import Optional
from rpc_reader.rpc_reader import ReadRPC
class ViewRPC(object):
"""
Plot content of RPC III files using MatPlotLib
Lukas Stockmann
2022-04-24
"""
def __init__(self, _file, debug: bool = False):
"""
:param _file: Path to a rpc file
:param debug: Flag for extra debugging output
"""
# The file the data is stored in
self.file: Optional[pathlib.Path, str] = None
# The measurement data array stored in the file
self.data: Optional[np.arrray] = None
# Time array corresponding to the measurement data
self.time: Optional[np.arrray] = None
# End time of measurement
self.end_time: Optional[float] = None
# Complete Header of RPC file
self.headers: Optional[dict] = None
# Header for the individual channels
self.channels: dict = dict()
# Debug mode parameter
self.debug = debug
# Check received _file
if not isinstance(_file, pathlib.Path):
_file = pathlib.Path(_file)
if not _file.is_file():
sys.exit("ERROR: The PRC test_data data file is invalid")
self.file = _file
# Instantiate instance
data_object = ReadRPC(self.file, debug=True)
# Check if the rpc file has been stored as a compressed numpy file
file_path_data = self.file.with_suffix('.npz')
if file_path_data.is_file():
# Import data from compressed numpy file
data_object.import_npy_data_from_file()
else:
# Import data from rpc_file
data_object.import_rpc_data_from_file()
# Export data as compressed numpy file
data_object.save_npy_data_to_file(overwrite=False)
self.data = data_object.get_data()
self.time, self.end_time = data_object.get_time()
self.headers = data_object.get_headers()
self.channels = data_object.get_channels()
# Verify that the un-pickled data is of dict type
if isinstance(self.channels, np.ndarray):
self.channels = self.channels.tolist()
if isinstance(self.headers, np.ndarray):
self.headers = self.headers.tolist()
def plot_channel(self, channel):
try:
channel_metadata = self.channels[channel]
except KeyError:
print(f' ERROR: Requested channel is not available: {channel}')
return
# Create an empty figure with one axis
fig, ax = plt.subplots()
# Plot some data on the axes.
ax.plot(self.time, self.data[:, channel])
if 'Channel' in channel_metadata and 'Description' in channel_metadata:
desc = f"{channel_metadata['Channel']} - {channel_metadata['Description']}"
plt.suptitle(desc)
if 'Units' in channel_metadata:
desc = f"{channel_metadata['Units']}"
plt.ylabel = desc
# Add time legend
plt.xlabel = 'Time [s]'
# Show plot
plt.show()
def visualize_data(self, show=True):
# Create a dict to assign an axes to each unit type
unit_axes: [dict] = dict()
# Iterate through all channels and sort by Unit
for channel_no, channel_data in self.channels.items():
if 'Units' in channel_data and channel_data['Units'] not in unit_axes:
unit_axes[channel_data['Units']] = list()
if 'Units' in channel_data:
unit_axes[channel_data['Units']].append(channel_no)
if unit_axes:
# Create figure with as many axes as there are different measurement units
fig, axs = plt.subplots(len(unit_axes), 1)
else:
print(' WARNING: No Units for the measurements were found!')
return
for unit in unit_axes:
# Get the index position of the measurement unit that's being plotted
i = list(unit_axes).index(unit)
for channel in unit_axes[unit]:
# Plot the graph
graph, = axs[i].plot(self.time, self.data[:, channel])
# Label the graph
graph.set_label(self.channels[channel]['Description'])
# Label x-axis with unit
axs[i].set_ylabel(unit)
# Label y axis
axs[i].set_xlabel('time in [s]')
# Use the graphs' labels to create a legend for the plot
axs[i].legend()
# Optionally show plot
if show:
plt.show()
# Return figure fir further use
return fig
def get_data_to_visualize(self):
# Create storage dict
figure_data_dict: dict = dict()
figure_data_dict['time'] = self.time
# Create a dict to assign an axes to each unit type
unit_axes: [dict] = dict()
# Iterate through all channels and sort by Unit
for channel_no, channel_data in self.channels.items():
if 'Units' in channel_data and channel_data['Units'] not in unit_axes:
unit_axes[channel_data['Units']] = list()
if 'Units' in channel_data:
unit_axes[channel_data['Units']].append(channel_no)
for unit in unit_axes:
figure_data_dict[unit] = dict()
for channel_no in unit_axes[unit]:
figure_data_dict[unit][channel_no] = dict()
figure_data_dict[unit][channel_no]['channel_data'] = self.data[:, channel_no]
figure_data_dict[unit][channel_no]['channel_description'] = self.channels[channel_no]['Description']
return figure_data_dict
def print_channel_header_data(self):
for _channel, data in self.channels.items():
print(f' Channel: {_channel + 1}')
for key, value in data.items():
print(f' \t {key:20s} : {value}')
def main():
def argparse_check_file(_file):
"""
'Type' for argparse - checks that file exists
"""
# If = is in the path, split and use the right side only
if '=' in _file:
_file = _file.split('=')[1]
_file = pathlib.Path(_file)
if not _file.is_file():
# Argparse uses the ArgumentTypeError to give a rejection message like:
# error: argument input: x does not exist
raise argparse.ArgumentTypeError("{0} is not a valid file".format(_file.as_posix()))
return _file
# Set-up parsing of input arguments
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''
Description:
-----------------------------------------------------------------------------------------------------------
Application for reading PRC 3 data files into numpy arrays. In the command line version, the provided file
is converted into a numpy .npz file. To load the data use the numpy.load module which will load the numpy
data as a dictionary with the following keys:
s
header - Header data
time - Time array
channels - Channel data
data - The actual measurement data
Written by: Niklas Melin
Syntax examples:
rpc_reader my_data_file.rpc
'''))
parser.add_argument("input_path",
type=argparse_check_file,
metavar='INPUT_PATH',
help="Select file containing something important \
\n\t /path/to/my/input/file.rpc")
parser.add_argument("--debug", "--d",
action="store_true",
help="If debug is set, significant additional output is requested.\n")
# Parse arguments into a dictionary
cmd_line_args = vars(parser.parse_args())
# Get arguments
input_path = cmd_line_args['input_path']
debug = cmd_line_args['debug']
# Start batch process
reader_object = ReadRPC(input_path, debug=debug)
reader_object.import_rpc_data_from_file()
reader_object.save_npy_data_to_file()
if __name__ == '__main__':
main() | /rpc_viewer-0.4-py3-none-any.whl/rpc_viewer/rpc_viewer.py | 0.738763 | 0.417153 | rpc_viewer.py | pypi |
import json
import pickle
import typing
from abc import ABCMeta, abstractmethod
try:
import msgpack
except ImportError: # pragma: no cover
msgpack = None # type: ignore
try:
import cbor2 as cbor
except ImportError: # pragma: no cover
cbor = None # type: ignore
from rpcpy.exceptions import SerializerNotFound
class BaseSerializer(metaclass=ABCMeta):
"""
Base Serializer
"""
name: str
content_type: str
@abstractmethod
def encode(self, data: typing.Any) -> bytes:
raise NotImplementedError()
@abstractmethod
def decode(self, raw_data: bytes) -> typing.Any:
raise NotImplementedError()
class JSONSerializer(BaseSerializer):
name = "json"
content_type = "application/json"
def __init__(
self,
default_encode: typing.Callable = None,
default_decode: typing.Callable = None,
) -> None:
self.default_encode = default_encode
self.default_decode = default_decode
def encode(self, data: typing.Any) -> bytes:
return json.dumps(
data,
ensure_ascii=False,
default=self.default_encode,
).encode("utf8")
def decode(self, data: bytes) -> typing.Any:
return json.loads(
data.decode("utf8"),
object_hook=self.default_decode,
)
class PickleSerializer(BaseSerializer):
name = "pickle"
content_type = "application/x-pickle"
def encode(self, data: typing.Any) -> bytes:
return pickle.dumps(data)
def decode(self, data: bytes) -> typing.Any:
return pickle.loads(data)
class MsgpackSerializer(BaseSerializer):
"""
Msgpack: https://github.com/msgpack/msgpack-python
"""
name = "msgpack"
content_type = "application/x-msgpack"
def __init__(
self,
default_encode: typing.Callable = None,
default_decode: typing.Callable = None,
) -> None:
self.default_encode = default_encode
self.default_decode = default_decode
def encode(self, data: typing.Any) -> bytes:
return msgpack.packb(data, default=self.default_encode)
def decode(self, data: bytes) -> typing.Any:
return msgpack.unpackb(data, object_hook=self.default_decode)
class CBORSerializer(BaseSerializer):
"""
CBOR: https://tools.ietf.org/html/rfc7049
"""
name = "cbor"
content_type = "application/x-cbor"
def encode(self, data: typing.Any) -> bytes:
return cbor.dumps(data)
def decode(self, data: bytes) -> typing.Any:
return cbor.loads(data)
SERIALIZER_NAMES = {
JSONSerializer.name: JSONSerializer(),
PickleSerializer.name: PickleSerializer(),
MsgpackSerializer.name: MsgpackSerializer(),
CBORSerializer.name: CBORSerializer(),
}
SERIALIZER_TYPES = {
JSONSerializer.content_type: JSONSerializer(),
PickleSerializer.content_type: PickleSerializer(),
MsgpackSerializer.content_type: MsgpackSerializer(),
CBORSerializer.content_type: CBORSerializer(),
}
def get_serializer(headers: typing.Mapping) -> BaseSerializer:
"""
parse header and try find serializer
"""
serializer_name = headers.get("serializer", None)
if serializer_name:
if serializer_name not in SERIALIZER_NAMES:
raise SerializerNotFound(f"Serializer `{serializer_name}` not found")
return SERIALIZER_NAMES[serializer_name]
serializer_type = headers.get("content-type", None)
if serializer_type:
if serializer_type not in SERIALIZER_TYPES:
raise SerializerNotFound(f"Serializer for `{serializer_type}` not found")
return SERIALIZER_TYPES[serializer_type]
raise SerializerNotFound(
"You must set a value for header `serializer` or `content-type`"
) | /rpc.py-0.6.0.tar.gz/rpc.py-0.6.0/rpcpy/serializers.py | 0.716318 | 0.161155 | serializers.py | pypi |
from TProtocol import *
from struct import pack, unpack
__all__ = ['TCompactProtocol', 'TCompactProtocolFactory']
CLEAR = 0
FIELD_WRITE = 1
VALUE_WRITE = 2
CONTAINER_WRITE = 3
BOOL_WRITE = 4
FIELD_READ = 5
CONTAINER_READ = 6
VALUE_READ = 7
BOOL_READ = 8
def make_helper(v_from, container):
def helper(func):
def nested(self, *args, **kwargs):
assert self.state in (v_from, container), (self.state, v_from, container)
return func(self, *args, **kwargs)
return nested
return helper
writer = make_helper(VALUE_WRITE, CONTAINER_WRITE)
reader = make_helper(VALUE_READ, CONTAINER_READ)
def makeZigZag(n, bits):
checkIntegerLimits(n, bits)
return (n << 1) ^ (n >> (bits - 1))
def fromZigZag(n):
return (n >> 1) ^ -(n & 1)
def writeVarint(trans, n):
out = []
while True:
if n & ~0x7f == 0:
out.append(n)
break
else:
out.append((n & 0xff) | 0x80)
n = n >> 7
trans.write(''.join(map(chr, out)))
def readVarint(trans):
result = 0
shift = 0
while True:
x = trans.readAll(1)
byte = ord(x)
result |= (byte & 0x7f) << shift
if byte >> 7 == 0:
return result
shift += 7
class CompactType:
STOP = 0x00
TRUE = 0x01
FALSE = 0x02
BYTE = 0x03
I16 = 0x04
I32 = 0x05
I64 = 0x06
DOUBLE = 0x07
BINARY = 0x08
LIST = 0x09
SET = 0x0A
MAP = 0x0B
STRUCT = 0x0C
CTYPES = {TType.STOP: CompactType.STOP,
TType.BOOL: CompactType.TRUE, # used for collection
TType.BYTE: CompactType.BYTE,
TType.I16: CompactType.I16,
TType.I32: CompactType.I32,
TType.I64: CompactType.I64,
TType.DOUBLE: CompactType.DOUBLE,
TType.STRING: CompactType.BINARY,
TType.STRUCT: CompactType.STRUCT,
TType.LIST: CompactType.LIST,
TType.SET: CompactType.SET,
TType.MAP: CompactType.MAP
}
TTYPES = {}
for k, v in CTYPES.items():
TTYPES[v] = k
TTYPES[CompactType.FALSE] = TType.BOOL
del k
del v
class TCompactProtocol(TProtocolBase):
"""Compact implementation of the Thrift protocol driver."""
PROTOCOL_ID = 0x82
VERSION = 1
VERSION_MASK = 0x1f
TYPE_MASK = 0xe0
TYPE_BITS = 0x07
TYPE_SHIFT_AMOUNT = 5
def __init__(self, trans):
TProtocolBase.__init__(self, trans)
self.state = CLEAR
self.__last_fid = 0
self.__bool_fid = None
self.__bool_value = None
self.__structs = []
self.__containers = []
def __writeVarint(self, n):
writeVarint(self.trans, n)
def writeMessageBegin(self, name, type, seqid):
assert self.state == CLEAR
self.__writeUByte(self.PROTOCOL_ID)
self.__writeUByte(self.VERSION | (type << self.TYPE_SHIFT_AMOUNT))
self.__writeVarint(seqid)
self.__writeString(name)
self.state = VALUE_WRITE
def writeMessageEnd(self):
assert self.state == VALUE_WRITE
self.state = CLEAR
def writeStructBegin(self, name):
assert self.state in (CLEAR, CONTAINER_WRITE, VALUE_WRITE), self.state
self.__structs.append((self.state, self.__last_fid))
self.state = FIELD_WRITE
self.__last_fid = 0
def writeStructEnd(self):
assert self.state == FIELD_WRITE
self.state, self.__last_fid = self.__structs.pop()
def writeFieldStop(self):
self.__writeByte(0)
def __writeFieldHeader(self, type, fid):
delta = fid - self.__last_fid
if 0 < delta <= 15:
self.__writeUByte(delta << 4 | type)
else:
self.__writeByte(type)
self.__writeI16(fid)
self.__last_fid = fid
def writeFieldBegin(self, name, type, fid):
assert self.state == FIELD_WRITE, self.state
if type == TType.BOOL:
self.state = BOOL_WRITE
self.__bool_fid = fid
else:
self.state = VALUE_WRITE
self.__writeFieldHeader(CTYPES[type], fid)
def writeFieldEnd(self):
assert self.state in (VALUE_WRITE, BOOL_WRITE), self.state
self.state = FIELD_WRITE
def __writeUByte(self, byte):
self.trans.write(pack('!B', byte))
def __writeByte(self, byte):
self.trans.write(pack('!b', byte))
def __writeI16(self, i16):
self.__writeVarint(makeZigZag(i16, 16))
def __writeSize(self, i32):
self.__writeVarint(i32)
def writeCollectionBegin(self, etype, size):
assert self.state in (VALUE_WRITE, CONTAINER_WRITE), self.state
if size <= 14:
self.__writeUByte(size << 4 | CTYPES[etype])
else:
self.__writeUByte(0xf0 | CTYPES[etype])
self.__writeSize(size)
self.__containers.append(self.state)
self.state = CONTAINER_WRITE
writeSetBegin = writeCollectionBegin
writeListBegin = writeCollectionBegin
def writeMapBegin(self, ktype, vtype, size):
assert self.state in (VALUE_WRITE, CONTAINER_WRITE), self.state
if size == 0:
self.__writeByte(0)
else:
self.__writeSize(size)
self.__writeUByte(CTYPES[ktype] << 4 | CTYPES[vtype])
self.__containers.append(self.state)
self.state = CONTAINER_WRITE
def writeCollectionEnd(self):
assert self.state == CONTAINER_WRITE, self.state
self.state = self.__containers.pop()
writeMapEnd = writeCollectionEnd
writeSetEnd = writeCollectionEnd
writeListEnd = writeCollectionEnd
def writeBool(self, bool):
if self.state == BOOL_WRITE:
if bool:
ctype = CompactType.TRUE
else:
ctype = CompactType.FALSE
self.__writeFieldHeader(ctype, self.__bool_fid)
elif self.state == CONTAINER_WRITE:
if bool:
self.__writeByte(CompactType.TRUE)
else:
self.__writeByte(CompactType.FALSE)
else:
raise AssertionError("Invalid state in compact protocol")
writeByte = writer(__writeByte)
writeI16 = writer(__writeI16)
@writer
def writeI32(self, i32):
self.__writeVarint(makeZigZag(i32, 32))
@writer
def writeI64(self, i64):
self.__writeVarint(makeZigZag(i64, 64))
@writer
def writeDouble(self, dub):
self.trans.write(pack('<d', dub))
def __writeString(self, s):
self.__writeSize(len(s))
self.trans.write(s)
writeString = writer(__writeString)
def readFieldBegin(self):
assert self.state == FIELD_READ, self.state
type = self.__readUByte()
if type & 0x0f == TType.STOP:
return (None, 0, 0)
delta = type >> 4
if delta == 0:
fid = self.__readI16()
else:
fid = self.__last_fid + delta
self.__last_fid = fid
type = type & 0x0f
if type == CompactType.TRUE:
self.state = BOOL_READ
self.__bool_value = True
elif type == CompactType.FALSE:
self.state = BOOL_READ
self.__bool_value = False
else:
self.state = VALUE_READ
return (None, self.__getTType(type), fid)
def readFieldEnd(self):
assert self.state in (VALUE_READ, BOOL_READ), self.state
self.state = FIELD_READ
def __readUByte(self):
result, = unpack('!B', self.trans.readAll(1))
return result
def __readByte(self):
result, = unpack('!b', self.trans.readAll(1))
return result
def __readVarint(self):
return readVarint(self.trans)
def __readZigZag(self):
return fromZigZag(self.__readVarint())
def __readSize(self):
result = self.__readVarint()
if result < 0:
raise TException("Length < 0")
return result
def readMessageBegin(self):
assert self.state == CLEAR
proto_id = self.__readUByte()
if proto_id != self.PROTOCOL_ID:
raise TProtocolException(TProtocolException.BAD_VERSION,
'Bad protocol id in the message: %d' % proto_id)
ver_type = self.__readUByte()
type = (ver_type >> self.TYPE_SHIFT_AMOUNT) & self.TYPE_BITS
version = ver_type & self.VERSION_MASK
if version != self.VERSION:
raise TProtocolException(TProtocolException.BAD_VERSION,
'Bad version: %d (expect %d)' % (version, self.VERSION))
seqid = self.__readVarint()
name = self.__readString()
return (name, type, seqid)
def readMessageEnd(self):
assert self.state == CLEAR
assert len(self.__structs) == 0
def readStructBegin(self):
assert self.state in (CLEAR, CONTAINER_READ, VALUE_READ), self.state
self.__structs.append((self.state, self.__last_fid))
self.state = FIELD_READ
self.__last_fid = 0
def readStructEnd(self):
assert self.state == FIELD_READ
self.state, self.__last_fid = self.__structs.pop()
def readCollectionBegin(self):
assert self.state in (VALUE_READ, CONTAINER_READ), self.state
size_type = self.__readUByte()
size = size_type >> 4
type = self.__getTType(size_type)
if size == 15:
size = self.__readSize()
self.__containers.append(self.state)
self.state = CONTAINER_READ
return type, size
readSetBegin = readCollectionBegin
readListBegin = readCollectionBegin
def readMapBegin(self):
assert self.state in (VALUE_READ, CONTAINER_READ), self.state
size = self.__readSize()
types = 0
if size > 0:
types = self.__readUByte()
vtype = self.__getTType(types)
ktype = self.__getTType(types >> 4)
self.__containers.append(self.state)
self.state = CONTAINER_READ
return (ktype, vtype, size)
def readCollectionEnd(self):
assert self.state == CONTAINER_READ, self.state
self.state = self.__containers.pop()
readSetEnd = readCollectionEnd
readListEnd = readCollectionEnd
readMapEnd = readCollectionEnd
def readBool(self):
if self.state == BOOL_READ:
return self.__bool_value == CompactType.TRUE
elif self.state == CONTAINER_READ:
return self.__readByte() == CompactType.TRUE
else:
raise AssertionError("Invalid state in compact protocol: %d" %
self.state)
readByte = reader(__readByte)
__readI16 = __readZigZag
readI16 = reader(__readZigZag)
readI32 = reader(__readZigZag)
readI64 = reader(__readZigZag)
@reader
def readDouble(self):
buff = self.trans.readAll(8)
val, = unpack('<d', buff)
return val
def __readString(self):
len = self.__readSize()
return self.trans.readAll(len)
readString = reader(__readString)
def __getTType(self, byte):
return TTYPES[byte & 0x0f]
class TCompactProtocolFactory:
def __init__(self):
pass
def getProtocol(self, trans):
return TCompactProtocol(trans) | /rpc_thrift-0.9.9.tar.gz/rpc_thrift-0.9.9/src/protocol/TCompactProtocol.py | 0.531939 | 0.256774 | TCompactProtocol.py | pypi |
# aggregate_rpc
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.com/d5277/aggregate_rpc.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.com/d5277/aggregate_rpc/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
| /rpcaggregation-0.0.13.tar.gz/rpcaggregation-0.0.13/README.md | 0.57523 | 0.818483 | README.md | pypi |
import argparse
import os
import time
import torch
from torch import nn
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import DistributedSampler, RandomSampler
from torchvision import transforms
from torchvision.datasets import ImageFolder
from torchvision.models import get_model
from rpcdataloader import RPCDataloader, RPCDataset
def main():
argparser = argparse.ArgumentParser()
argparser.add_argument("--data-path")
argparser.add_argument("--model", default="resnet50")
argparser.add_argument("--workers", type=str, nargs="+")
argparser.add_argument("--batch-size", default=2, type=int)
argparser.add_argument("--lr", default=0.1, type=float)
argparser.add_argument("--momentum", default=0.9, type=float)
argparser.add_argument("--weight-decay", default=1e-4, type=float)
argparser.add_argument("--epochs", default=100, type=int)
argparser.add_argument("--amp", action="store_true")
args = argparser.parse_args()
# Distributed
if "RANK" in os.environ and "WORLD_SIZE" in os.environ: # torchrun launch
rank = int(os.environ["RANK"])
local_rank = int(os.environ["LOCAL_RANK"])
world_size = int(os.environ["WORLD_SIZE"])
elif int(os.environ.get("SLURM_NPROCS", 1)) > 1: # srun launch
rank = int(os.environ["SLURM_PROCID"])
local_rank = int(os.environ["SLURM_LOCALID"])
world_size = int(os.environ["SLURM_NPROCS"])
else: # single gpu & process launch
rank = 0
local_rank = 0
world_size = 0
if world_size > 0:
torch.distributed.init_process_group(
backend="nccl", world_size=world_size, rank=rank
)
# split workers between GPUs (optional but recommended)
if len(args.workers) > 0:
args.workers = args.workers[rank::world_size]
print(args)
# Device
device = torch.device("cuda", index=local_rank)
# Preprocessing
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
train_transform = transforms.Compose(
[
transforms.RandomResizedCrop(224),
transforms.RandAugment(),
transforms.ToTensor(),
normalize,
]
)
# Datasets
train_dataset = RPCDataset(
args.workers,
ImageFolder,
root=args.data_path + "/train",
transform=train_transform,
)
# Data loading
if torch.distributed.is_initialized():
train_sampler = DistributedSampler(train_dataset)
else:
train_sampler = RandomSampler(train_dataset)
train_loader = RPCDataloader(
train_dataset,
batch_size=args.batch_size,
sampler=train_sampler,
pin_memory=True,
)
# Model
model = get_model(args.model, num_classes=1000)
model.to(device)
if torch.distributed.is_initialized():
model = nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[local_rank]
)
# Optimization
optimizer = torch.optim.SGD(
model.parameters(),
args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay,
)
scaler = torch.cuda.amp.GradScaler(enabled=args.amp)
scheduler = StepLR(optimizer, step_size=30, gamma=0.1)
loss_fn = nn.CrossEntropyLoss().to(device)
# Training
for epoch in range(args.epochs):
if isinstance(train_sampler, DistributedSampler):
train_sampler.set_epoch(epoch)
for it, (images, targets) in enumerate(train_loader):
t0 = time.monotonic()
optimizer.zero_grad(set_to_none=True)
images = images.to(device, non_blocking=True)
targets = targets.to(device, non_blocking=True)
with torch.cuda.amp.autocast(enabled=args.amp):
predictions = model(images)
loss = loss_fn(predictions, targets)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
if (it + 1) % 20 == 0 and rank == 0:
t1 = time.monotonic()
print(
f"[epoch {epoch:<3d}"
f" it {it:-5d}/{len(train_loader)}]"
f" loss: {loss.item():2.3f}"
f" time: {t1 - t0:.1f}"
)
scheduler.step()
if __name__ == "__main__":
main() | /rpcdataloader-0.2.1.tar.gz/rpcdataloader-0.2.1/docs/example_rpc.py | 0.764892 | 0.230227 | example_rpc.py | pypi |
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Gaussian(Distribution):
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
def __init__(self, mu=0, sigma=1):
Distribution.__init__(self, mu, sigma)
def calculate_mean(self):
"""Function to calculate the mean of the data set.
Args:
None
Returns:
float: mean of the data set
"""
avg = 1.0 * sum(self.data) / len(self.data)
self.mean = avg
return self.mean
def calculate_stdev(self, sample=True):
"""Function to calculate the standard deviation of the data set.
Args:
sample (bool): whether the data represents a sample or population
Returns:
float: standard deviation of the data set
"""
if sample:
n = len(self.data) - 1
else:
n = len(self.data)
mean = self.calculate_mean()
sigma = 0
for d in self.data:
sigma += (d - mean) ** 2
sigma = math.sqrt(sigma / n)
self.stdev = sigma
return self.stdev
def plot_histogram(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.hist(self.data)
plt.title('Histogram of Data')
plt.xlabel('data')
plt.ylabel('count')
def pdf(self, x):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2)
def plot_histogram_pdf(self, n_spaces = 50):
"""Function to plot the normalized histogram of the data and a plot of the
probability density function along the same range
Args:
n_spaces (int): number of data points
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
mu = self.mean
sigma = self.stdev
min_range = min(self.data)
max_range = max(self.data)
# calculates the interval between x values
interval = 1.0 * (max_range - min_range) / n_spaces
x = []
y = []
# calculate the x values to visualize
for i in range(n_spaces):
tmp = min_range + interval*i
x.append(tmp)
y.append(self.pdf(tmp))
# make the plots
fig, axes = plt.subplots(2,sharex=True)
fig.subplots_adjust(hspace=.5)
axes[0].hist(self.data, density=True)
axes[0].set_title('Normed Histogram of Data')
axes[0].set_ylabel('Density')
axes[1].plot(x, y)
axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation')
axes[0].set_ylabel('Density')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Gaussian distributions
Args:
other (Gaussian): Gaussian instance
Returns:
Gaussian: Gaussian distribution
"""
result = Gaussian()
result.mean = self.mean + other.mean
result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2)
return result
def __repr__(self):
"""Function to output the characteristics of the Gaussian instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}".format(self.mean, self.stdev) | /rpdsnd_distributions-1.0.tar.gz/rpdsnd_distributions-1.0/rpdsnd_distributions/Gaussiandistribution.py | 0.688364 | 0.853058 | Gaussiandistribution.py | pypi |
import importlib.util
import inspect
import sys
from dataclasses import asdict
from rpe.policy import Evaluation, EvaluationResult, Policy
class PythonPolicyEngine:
counter = 0
def __init__(self, package_path):
self._policies = {}
self.package_path = package_path
PythonPolicyEngine.counter += 1
self.package_name = "rpe.plugins.policies.py_" + str(PythonPolicyEngine.counter)
self._load_policies()
def _load_policies(self):
spec = importlib.util.spec_from_file_location(
self.package_name, "{}/__init__.py".format(self.package_path)
)
module = importlib.util.module_from_spec(spec)
sys.modules[self.package_name] = module
spec.loader.exec_module(module)
for name, obj in inspect.getmembers(module):
if (
inspect.isclass(obj)
and hasattr(obj, "applies_to")
and isinstance(obj.applies_to, list)
):
self._policies[name] = obj
def policies(self):
"""
Returns:
A list of names of configured policies
"""
policies = [
Policy(
policy_id=policy_name,
engine=self,
applies_to=policy_cls.applies_to,
description=policy_cls.description,
policy_attributes=getattr(policy_cls, "policy_attributes", {}),
)
for policy_name, policy_cls in self._policies.items()
]
return policies
def evaluate(self, resource):
matched_policies = dict(
filter(
lambda policy: resource.type() in policy[1].applies_to,
self._policies.items(),
)
)
# Loop over policy and build evals, so we can catch exceptions
evals = []
for policy_name, policy_cls in matched_policies.items():
try:
if hasattr(policy_cls, "evaluate"):
eval_result = policy_cls.evaluate(resource)
if not isinstance(eval_result, EvaluationResult):
raise ValueError(
'Python policy "evaluate" function must return an EvaluationResult object'
)
full_eval = Evaluation(
resource=resource,
engine=self,
policy_id=policy_name,
**asdict(eval_result),
)
evals.append(full_eval)
else:
evals.append(self._legacy_eval(resource, policy_name, policy_cls))
# These are user-provided modules, we need to catch any exception
except Exception as e:
print(f"Evaluation exception. Policy: {policy_name}, Message: {str(e)}")
return evals
def _legacy_eval(self, resource, policy_name, policy_cls):
compliant = policy_cls.compliant(resource) is True
eval_attr = {"excluded": policy_cls.excluded(resource) is True}
ev = Evaluation(
resource=resource,
engine=self,
policy_id=policy_name,
compliant=compliant,
remediable=hasattr(policy_cls, "remediate"),
evaluation_attributes=eval_attr,
)
return ev
def remediate(self, resource, policy_id):
policy_cls = self._policies[policy_id]
policy_cls.remediate(resource) | /rpe-lib-3.0.2.tar.gz/rpe-lib-3.0.2/rpe/engines/python.py | 0.474875 | 0.168823 | python.py | pypi |
import json
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Optional
from pydantic import BaseModel
import dateutil.parser
import jmespath
from rpe.exceptions import ExtractorException
from rpe.extractors import Extractor
from rpe.extractors.models import ExtractedMetadata, ExtractedResources
from rpe.resources.gcp import GoogleAPIResource
class OperationEnum(str, Enum):
create = "create"
read = "read"
update = "update"
delete = "delete"
class GCPAuditLogMetadata(ExtractedMetadata):
id: str
timestamp: datetime
principal: Optional[str]
method_name: Optional[str]
operation: Optional[OperationEnum]
class GCPAuditLog(Extractor):
@classmethod
def extract(cls, log_message):
# Attempt to load it like a pubsub message, without requiring the pubsub client to be installed
if not isinstance(log_message, dict):
message_data = json.loads(log_message.data)
else:
message_data = log_message
if not cls.is_audit_log(message_data):
raise ExtractorException("Not an audit log")
metadata = cls.get_metadata(message_data)
resources = cls.get_resources(message_data)
return ExtractedResources(
resources=resources,
metadata=metadata,
)
@classmethod
def is_audit_log(cls, message_data):
log_type = jmespath.search('protoPayload."@type"', message_data)
log_name = message_data.get("logName", "")
# normal activity logs have logName in this form:
# projects/<p>/logs/cloudaudit.googleapis.com%2Factivity
# data access logs have a logName field that looks like:
# projects/<p>/logs/cloudaudit.googleapis.com%2Fdata_access
return all(
[
log_type == "type.googleapis.com/google.cloud.audit.AuditLog",
log_name.split("/")[-1].startswith("cloudaudit.googleapis.com"),
]
)
@classmethod
def get_metadata(cls, message_data):
method_name = jmespath.search("protoPayload.methodName", message_data)
insert_id = message_data.get("insertId")
log_timestamp = message_data.get("timestamp")
timestamp = dateutil.parser.parse(log_timestamp)
principal_email = jmespath.search(
"protoPayload.authenticationInfo.principalEmail", message_data
)
operation = cls.get_operation_type(method_name)
return GCPAuditLogMetadata(
id=insert_id,
timestamp=timestamp,
method_name=method_name,
operation=operation,
principal=principal_email,
)
@classmethod
def get_operation_type(cls, method_name):
last = method_name.split(".")[-1].lower()
# For batch methods, look for the verb after the word 'batch'
if last.startswith("batch"):
last = last[5:]
read_prefixes = ("get", "list")
if last.startswith(read_prefixes):
return "read"
update_prefixes = (
"update",
"patch",
"set",
"debug",
"enable",
"disable",
"expand",
"deactivate",
"activate",
"switch",
)
if last.startswith(update_prefixes):
return "update"
create_prefixes = (
"create",
"insert",
)
if last.startswith(create_prefixes):
return "create"
delete_prefixes = ("delete",)
if last.startswith(delete_prefixes):
return "delete"
return None
@classmethod
def get_resources(cls, message):
resources = []
res_type = jmespath.search("resource.type", message)
if res_type is None:
return resources
# just shortening the many calls to jmespath throughout this function
# this sub-function saves us from passing the message each time
def prop(exp):
return jmespath.search(exp, message)
def add_resource():
r = resource_data.copy()
res = GoogleAPIResource.from_resource_data(**r)
resources.append(res)
method_name = prop("protoPayload.methodName")
if res_type == "cloudsql_database" and method_name.startswith(
"cloudsql.instances"
):
resource_data = {
"resource_type": "sqladmin.googleapis.com/Instance",
# CloudSQL logs are inconsistent. See https://issuetracker.google.com/issues/137629452
"name": (
prop("resource.labels.database_id").split(":")[-1]
or prop("protoPayload.request.body.name")
or prop("protoPayload.request.resource.instanceName.instanceId")
),
"location": prop("resource.labels.region"),
"project_id": prop("resource.labels.project_id"),
}
add_resource()
elif res_type == "gcs_bucket" and method_name.startswith(
("storage.buckets", "storage.setIamPermissions")
):
resource_data = {
"resource_type": "storage.googleapis.com/Bucket",
"name": prop("resource.labels.bucket_name"),
"location": prop("resource.labels.location"),
"project_id": prop("resource.labels.project_id"),
}
add_resource()
elif res_type == "bigquery_dataset":
if "DatasetService" in method_name or "etIamPolicy" in method_name:
resource_data = {
"resource_type": "bigquery.googleapis.com/Dataset",
"name": prop("resource.labels.dataset_id"),
"project_id": prop("resource.labels.project_id"),
}
add_resource()
elif res_type == "project" and "etIamPolicy" in method_name:
resource_data = {
"resource_type": "cloudresourcemanager.googleapis.com/Project",
"name": prop("resource.labels.project_id"),
"project_id": prop("resource.labels.project_id"),
}
add_resource()
elif res_type == "pubsub_subscription" and "etIamPolicy" in method_name:
resource_data = {
"resource_type": "pubsub.googleapis.com/Subscription",
"name": prop("resource.labels.subscription_id").split("/")[-1],
"project_id": prop("resource.labels.project_id"),
}
add_resource()
elif res_type == "pubsub_topic" and "etIamPolicy" in method_name:
resource_data = {
"resource_type": "pubsub.googleapis.com/Topic",
"name": prop("resource.labels.topic_id").split("/")[-1],
"project_id": prop("resource.labels.project_id"),
}
add_resource()
elif res_type == "audited_resource" and (
"EnableService" in method_name
or "DisableService" in method_name
or "ctivateService" in method_name
):
resource_data = {
"resource_type": "serviceusage.googleapis.com/Service",
"project_id": prop("resource.labels.project_id"),
}
# Check if multiple services were included in the request
# The Google Cloud Console generates (De)activate calls that logs a different format so we check both
# known formats
services = prop("protoPayload.request.serviceIds") or prop(
"protoPayload.request.serviceNames"
)
if services:
for s in services:
resource_data["name"] = s
add_resource()
else:
resource_data["name"] = prop("protoPayload.resourceName").split("/")[-1]
add_resource()
elif res_type == "audited_resource" and "DeactivateServices" in method_name:
resource_data = {
"resource_type": "serviceusage.googleapis.com/Service",
"name": prop("resource.labels.service"),
"project_id": prop("resource.labels.project_id"),
}
add_resource()
elif res_type == "gce_network":
resource_data = {
"resource_type": "compute.googleapis.com/Network",
"name": prop("protoPayload.resourceName").split("/")[-1],
"project_id": prop("resource.labels.project_id"),
}
add_resource()
elif res_type == "gce_subnetwork":
resource_data = {
"resource_type": "compute.googleapis.com/Subnetwork",
"name": prop("resource.labels.subnetwork_name"),
"project_id": prop("resource.labels.project_id"),
"location": prop("resource.labels.location"),
}
add_resource()
elif res_type == "gce_firewall_rule":
resource_data = {
"resource_type": "compute.googleapis.com/Firewall",
"name": prop("protoPayload.resourceName").split("/")[-1],
"project_id": prop("resource.labels.project_id"),
}
add_resource()
elif res_type == "gae_app" and "DebugInstance" in method_name:
instance_data = prop("protoPayload.resourceName").split("/")
resource_data = {
"resource_type": "appengine.googleapis.com/Instance",
"name": instance_data[-1],
"app": instance_data[1],
"service": instance_data[3],
"version": instance_data[5],
}
add_resource()
elif res_type == "gce_instance":
instance_name = prop("protoPayload.resourceName").split("/")[-1]
resource_data = {
"resource_type": "compute.googleapis.com/Instance",
"name": instance_name,
"location": prop("resource.labels.zone"),
"project_id": prop("resource.labels.project_id"),
}
# Logs are sent for some resources that are hidden by the compute API. We've found that some of these
# start with reserved prefixes. If the instance looks like a hidden resource, stop looking for
# resources and return immediately
compute_reserved_prefixes = ("aef-", "aet-")
if resource_data["name"].startswith(compute_reserved_prefixes):
return resources
add_resource()
# Also add disk resources since theres not a separate log message for these
disks = prop("protoPayload.request.disks") or []
for disk in disks:
# The name of the disk is complicated. If the diskName is set in initParams use that
# If not AND its the boot disk, use the instance name
# Otherwise use the device name
disk_name = jmespath.search("initializeParams.diskName", disk)
device_name = jmespath.search("deviceName", disk)
boot = jmespath.search("boot", disk)
actual_disk_name = disk_name or (boot and instance_name) or device_name
resource_data = {
"resource_type": "compute.googleapis.com/Disk",
"name": actual_disk_name,
"location": prop("resource.labels.zone"),
"project_id": prop("resource.labels.project_id"),
}
add_resource()
elif res_type == "cloud_function":
resource_data = {
"name": prop("resource.labels.function_name"),
"project_id": prop("resource.labels.project_id"),
"location": prop("resource.labels.region"),
"resource_type": "cloudfunctions.googleapis.com/CloudFunction",
}
add_resource()
elif res_type == "cloud_dataproc_cluster":
resource_data = {
"resource_type": "dataproc.googleapis.com/Cluster",
"project_id": prop("resource.labels.project_id"),
"name": prop("resource.labels.cluster_name"),
"location": prop("resource.labels.region"),
}
add_resource()
elif res_type == "gke_cluster":
resource_data = {
"resource_type": "container.googleapis.com/Cluster",
"name": prop("resource.labels.cluster_name"),
"project_id": prop("resource.labels.project_id"),
"location": prop("resource.labels.location"),
}
add_resource()
# add node pool resources for eval on new cluster creation
if (
"create" in method_name.lower()
and prop("protoPayload.request.cluster.nodePools") is not None
):
resource_data["resource_type"] = "container.googleapis.com/NodePool"
resource_data["cluster"] = prop("resource.labels.cluster_name")
for pool in prop("protoPayload.request.cluster.nodePools"):
resource_data["name"] = pool.get("name")
add_resource()
elif res_type == "gke_nodepool":
resource_data = {
"resource_type": "container.googleapis.com/NodePool",
"cluster": prop("resource.labels.cluster_name"),
"name": prop("resource.labels.nodepool_name"),
"project_id": prop("resource.labels.project_id"),
"location": prop("resource.labels.location"),
}
add_resource()
elif res_type == "audited_resource" and "BigtableInstanceAdmin" in method_name:
resource_data = {
"name": prop("protoPayload.resourceName").split("/")[-1],
"project_id": prop("resource.labels.project_id"),
}
resource_data["resource_type"] = "bigtableadmin.googleapis.com/Instance"
add_resource()
elif res_type == "dataflow_step" and "create" in method_name:
# The endpoint expects the job id instead of name
resource_data = {
"name": prop("protoPayload.request.job_id"),
"project_id": prop("resource.labels.project_id"),
"location": prop("resource.labels.region"),
}
resource_data["resource_type"] = "dataflow.googleapis.com/Job"
add_resource()
elif res_type == "audited_resource" and "CloudRedis" in method_name:
resource_data = {
"name": prop("protoPayload.resourceName").split("/")[-1],
"project_id": prop("resource.labels.project_id"),
"location": prop("protoPayload.resourceLocation.currentLocations")[0],
}
resource_data["resource_type"] = "redis.googleapis.com/Instance"
add_resource()
elif (
res_type == "audited_resource"
and prop("resource.labels.service") == "datafusion.googleapis.com"
):
name_bits = prop("protoPayload.resourceName").split("/")
resource_data = {
"name": name_bits[5],
"project_id": name_bits[1],
"location": name_bits[3],
"resource_type": "datafusion.googleapis.com/Instance",
}
add_resource()
return resources | /rpe-lib-3.0.2.tar.gz/rpe-lib-3.0.2/rpe/extractors/gcp_auditlogs.py | 0.72662 | 0.150278 | gcp_auditlogs.py | pypi |
import argparse
import csv
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
import pkg_resources
numbers = []
observation_names = []
amount_of_observations = []
risk_rating = []
mylabels = []
x_coords = []
y_coords = []
amount_high = 0
amount_medium = 0
amount_low = 0
def get_args():
""" Get arguments """
parser = argparse.ArgumentParser(
description='Converting scanning reports to a tabular format')
parser.add_argument(
'-g', '--grid', action='store_true', help='generate a risk grid plot.')
parser.add_argument(
'-d', '--donut', action='store_true', help='generate a risk donut.')
parser.add_argument(
'-r', '--recommendations', action='store_true',
help='generate a risk recommendations plot.')
parser.add_argument(
'-iC', '--input-csv-file', required=True,
help='specify an input CSV file (e.g. data.csv).')
parser.add_argument(
'-oP', '--output-png-file',
help='specify an output PNG file (e.g. risk.png).')
parser.add_argument(
'--axis-labels', help='specify to print the axis labels')
parser.add_argument(
'--axis-arrows', help='specify to print arrows along the axis')
parser.add_argument(
'--legend', help='specify to print the legend')
return parser.parse_args()
def load_risk_csv(args, amount_high, amount_medium, amount_low):
""" Import CSV and translate Likelihood and Impact to numbers """
with open(args.input_csv_file, newline='') as csvfile:
data = csv.reader(csvfile, delimiter=',')
next(data)
for row in data:
numbers.append(row[0])
observation_names.append(row[1])
risk_rating.append(row[4])
if row[2] == "H":
x = 450
elif row[2] == "M":
x = 300
elif row[2] == "L":
x = 150
if row[3] == "H":
y = 300
elif row[3] == "M":
y = 200
elif row[3] == "L":
y = 100
if row[4] == "H":
amount_high += 1
elif row[4] == "M":
amount_medium += 1
elif row[4] == "L":
amount_low += 1
x_coords.append(x)
y_coords.append(y)
for row in enumerate(observation_names):
amount_of_observations.append(row[0])
def load_recommendations_csv(args):
""" Import CSV and translate Likelihood and Impact to numbers """
with open(args.input_csv_file, newline='') as csvfile:
data = csv.reader(csvfile, delimiter=',')
next(data)
for row in data:
numbers.append(row[0])
observation_names.append(row[1])
if row[2] == "H":
x = 450
elif row[2] == "M":
x = 300
elif row[2] == "L":
x = 150
if row[3] == "H":
y = 300
elif row[3] == "M":
y = 200
elif row[3] == "L":
y = 100
x_coords.append(x)
y_coords.append(y)
for row in enumerate(observation_names):
amount_of_observations.append(row[0])
def donut(args):
""" Ring functions """
fig, ax = plt.subplots(subplot_kw=dict(aspect="equal"))
# Ring width size
size = 0.25
data = amount_high, amount_medium, amount_low
labels = ["High", "Medium", "Low"]
colors = ["red", "orange", "yellow"]
# Plot wedges
ax.pie(
data, wedgeprops=dict(width=size, edgecolor="black", linewidth=1),
startangle=90, colors=colors, labels=data)
# Determine exposure_level
largest_index = data.index(max(data))
if largest_index == 0:
exposure_level = "High"
elif largest_index == 1:
exposure_level = "Medium"
elif largest_index == 2:
exposure_level = "Low"
# Print exposure level
ax.text(
0.5, 0.53, "Exposure level", transform=ax.transAxes, fontsize=16,
horizontalalignment='center', verticalalignment='center')
ax.text(
0.5, 0.45, exposure_level, transform=ax.transAxes, fontsize=24,
horizontalalignment='center', verticalalignment='center',
weight='bold')
# Print legend
if args.legend:
ax.legend(labels, loc="center left", bbox_to_anchor=(1, 0.5), ncol=1)
# Output
if not args.output_png_file:
plt.show()
else:
plt.savefig(
args.output_png_file, transparent=True, dpi=200,
bbox_inches='tight')
def grid(args):
""" Grid function """
# Background
grid_bg = pkg_resources.resource_stream(__name__, 'data/grid-bg.png')
img = plt.imread(grid_bg)
# Axis spacing values
x_axis_spacing = plticker.MultipleLocator(base=150)
y_axis_spacing = plticker.MultipleLocator(base=100)
fig, ax = plt.subplots()
ax.imshow(img, extent=[0, 450, 0, 300])
# Plot observations with a sequential offset inside their quadrant
if x_coords and y_coords:
# Build list of sequential x and y offsets
x_seq = list(reversed(range(15, 150, 20)))
y_seq = list(range(15, 80, 20))
full_row = 0
for number, i, name, risk in zip(
numbers, amount_of_observations, observation_names,
risk_rating):
full_row += 1
x_seq.append(x_seq[0])
y_seq.append(y_seq[0])
x = x_coords.pop(0)-x_seq.pop(0)
# Modulo 7 to jump to new row if current row is full
if full_row % 7 == 0:
y = y_coords.pop(0)-y_seq.pop(0)
else:
y = y_coords.pop(0)-y_seq[0]
# Actual plotting of observations
if risk == 'H':
ax.scatter(
x, y, marker='o', c='#e20000', s=200, edgecolors='black')
ax.text(
x+0, y-3, number, fontsize=7, horizontalalignment='center',
color='white', weight='bold')
elif risk == 'M':
ax.scatter(
x, y, marker='o', c='#fecb00', s=200, edgecolors='black')
ax.text(
x+0, y-3, number, fontsize=7, horizontalalignment='center',
color='white', weight='bold')
elif risk == 'L':
ax.scatter(
x, y, marker='o', c='#ffff00', s=200, edgecolors='black')
ax.text(
x+0, y-3, number, fontsize=7, horizontalalignment='center',
color='black', weight='bold')
# Print legend
if args.legend:
for item in zip(numbers, observation_names):
mylabels.append(' '.join(item))
ax.legend(
observation_names, labels=mylabels, loc="upper left", ncol=1,
bbox_to_anchor=(1, 1.02))
# Hide axis numbers
ax.set_yticklabels([])
ax.set_xticklabels([])
# Grid spacing
ax.xaxis.set_major_locator(x_axis_spacing)
ax.yaxis.set_major_locator(y_axis_spacing)
# Print arrows along axis
if args.axis_arrows:
ax.annotate(
'High', va="center", xy=(0, -0.07), xycoords='axes fraction',
xytext=(1, -0.07), arrowprops=dict(arrowstyle="<-", color='black'))
ax.annotate(
'High', ha="center", xy=(-0.05, 0), xycoords='axes fraction',
xytext=(-0.05, 1), arrowprops=dict(arrowstyle="<-", color='black'))
# Print axis labels
if args.axis_labels:
plt.xlabel("Likelihood", labelpad=20)
plt.ylabel("Impact", labelpad=20)
# Print grid
plt.grid(color='black', alpha=0.5, linestyle='--')
# Output
if not args.output_png_file:
plt.show()
else:
plt.savefig(
args.output_png_file, transparent=True, dpi=200,
bbox_inches='tight')
def recommendations(args):
""" Grid function """
# Background
recommendations_bg = pkg_resources.resource_stream(
__name__, 'data/recommendations-bg.png')
img = plt.imread(recommendations_bg)
# Axis spacing values
x_axis_spacing = plticker.MultipleLocator(base=150)
y_axis_spacing = plticker.MultipleLocator(base=100)
fig, ax = plt.subplots()
ax.imshow(img, extent=[0, 450, 0, 300])
# Plot recommendations with a sequential offset inside their quadrant
if x_coords and y_coords:
# Build list of sequential x and y offsets
x_seq = list(reversed(range(25, 140, 25)))
y_seq = list(range(20, 80, 25))
full_row = 0
for number, i, name in zip(
numbers, amount_of_observations, observation_names):
full_row += 1
x_seq.append(x_seq[0])
y_seq.append(y_seq[0])
x = x_coords.pop(0)-x_seq.pop(0)
# Modulo 5 to jump to new row if current row is full
if full_row % 5 == 0:
y = y_coords.pop(0)-y_seq.pop(0)
else:
y = y_coords.pop(0)-y_seq[0]
# Actual plotting of recommendations
ax.scatter(
x, y, marker='o', c='#4f81bd', s=250, edgecolors='black')
ax.text(
x+0, y-3, number, fontsize=6, horizontalalignment='center',
color='white', weight='bold')
# Print legend
if args.legend:
for item in zip(numbers, observation_names):
mylabels.append(' '.join(item))
ax.legend(
observation_names, labels=mylabels, loc="upper left", ncol=1,
bbox_to_anchor=(1, 1.02))
# Hide axis numbers
ax.set_yticklabels([])
ax.set_xticklabels([])
# Grid spacing
ax.xaxis.set_major_locator(x_axis_spacing)
ax.yaxis.set_major_locator(y_axis_spacing)
# Print arrows along axis
if args.axis_arrows:
ax.annotate(
'High', va="center", xy=(0, -0.07), xycoords='axes fraction',
xytext=(1, -0.07), arrowprops=dict(arrowstyle="<-", color='black'))
ax.annotate(
'High', ha="center", xy=(-0.05, 0), xycoords='axes fraction',
xytext=(-0.05, 1), arrowprops=dict(arrowstyle="<-", color='black'))
# Print axis labels
if args.axis_labels:
plt.xlabel("Likelihood", labelpad=20)
plt.ylabel("Impact", labelpad=20)
# Print grid
plt.grid(color='black', alpha=0.5, linestyle='--')
# Output
if not args.output_png_file:
plt.show()
else:
plt.savefig(
args.output_png_file, transparent=True, dpi=200,
bbox_inches='tight')
def main():
""" Main function """
args = get_args()
if args.donut or args.grid:
load_risk_csv(args, amount_high, amount_medium, amount_low)
elif args.recommendations:
load_recommendations_csv(args)
if args.donut:
donut(args)
if args.grid:
grid(args)
if args.recommendations:
recommendations(args)
if __name__ == '__main__':
main() | /rpg-0bs1d1an-0.0.1.tar.gz/rpg-0bs1d1an-0.0.1/rpg/rpg.py | 0.678859 | 0.466481 | rpg.py | pypi |
# Name Generator written by Pointon:
# http://www.uselesspython.com/showcontent.php?author=27
# Adapted by Arne Babenhauserheide 2007
## I got sick of the absence of plain weird and quirky name generators out there. This comes up with unpronounceable results about 1/5th of the time.
## The namegen function has three parameters: lower_limit and upper_limit govern the length. ratio governs the vowels:consonants ratio. The lower the ratio, the less vowels per consonant.
import random
result = ""
fricatives = ["j", "ch", "h", "s", "sh", "th", "f", "v", "z"]
vowels = ["a", "e", "i", "o", "u", "y", "ya", "ye", "yi", "yo", "yu", "wa", "we", "wi", "wo", "wu", "ae", "au", "ei", "ie", "io", "iu", "ou", "uo", "oi", "oe", "ea"]
consonantsNormal = ["c", "g", "t", "d", "p", "b", "x", "k", "ck", "ch"]
consonantsNasal = ["n", "m", "ng", "nc"]
randomLength = 0
vowelSyllables = 0
vowelRatio = 0
def namegen(ratio=5, lower_limit=3, upper_limit=11):
ratio = ratio + 3
if ratio < 4:
ratio = 4
elif ratio > 14:
ratio = 14
global result, vowelSyllables, randomLength, vowelRatio
vowelRatio = ratio
result = ""
vowelSyllables = 0
randomLength = random.randrange(lower_limit, upper_limit)
sylgen()
return result.capitalize()
def sylgen():
global result, vowelSyllables, randomLength, syllableOnlyVowels, vowelRatio
syllableOnlyVowels = 1
maincongen()
if vowelSyllables < (vowelRatio/4):
vowgen()
maincongen()
if syllableOnlyVowels == 1:
vowelSyllables = vowelSyllables + 1
if len(result) < randomLength:
sylgen()
def fricgen():
global result, vowelSyllables, syllableOnlyVowels, fricatives
result = result + fricatives[random.randrange(0, len(fricatives))]
syllableOnlyVowels = 0
vowelSyllables = 0
def vowgen():
global result, vowels
result = result + vowels[random.randrange(0, len(vowels))]
def congen():
global result, vowelSyllables, randomLength, syllableOnlyVowels, consonantsNormal
result = result + consonantsNormal[random.randrange(0, len(consonantsNormal), 1)]
syllableOnlyVowels = 0
vowelSyllables = 0
def con2gen():
global result, vowelSyllables, syllableOnlyVowels
if random.randrange(0, 2) == 0:
result = result + "r"
else:
result = result + "l"
syllableOnlyVowels = 0
vowelSyllables = 0
def con3gen():
global result, vowelSyllables, syllableOnlyVowels, consonantsNasal
result = result + consonantsNasal[random.randrange(0, len(consonantsNasal))]
syllableOnlyVowels = 0
vowelSyllables = 0
def maincongen():
global result, randomLength, vowelRatio
if len(result) < randomLength:
randomNumber = random.randrange(0, vowelRatio)
if randomNumber == 0:
fricgen()
if len(result) < randomLength:
randomNumber = random.randrange(0, vowelRatio/4 * 3)
if randomNumber == 0:
congen()
if len(result) < randomLength:
randomNumber = random.randrange(0, vowelRatio/2)
if randomNumber == 0:
con2gen()
elif randomNumber == 1:
con2gen()
elif randomNumber == 2:
con3gen()
elif randomNumber == 1:
congen()
if len(result) < randomLength:
randomNumber = random.randrange(0, vowelRatio/2)
if randomNumber == 0:
con2gen()
elif randomNumber == 2:
con2gen()
elif randomNumber == 3:
con3gen() | /rpg-1d6-0.1.tar.gz/rpg-1d6-0.1/ews/random_phonetic_name_generator_von_Pointon/random_phonetic_name_generator.py | 0.446736 | 0.284719 | random_phonetic_name_generator.py | pypi |
import logging
from pathlib import Path
import click
from subtitle_filter import Subtitles
from tqdm import tqdm
@click.command(name="strip-hi")
@click.argument("path", type=Path)
@click.option("-f", "--fonts", is_flag=True, default=False,
help="Do not remove font tags and text contained within.")
@click.option("-a", "--ast", is_flag=True, default=False,
help="Do not remove captions containing asterisks: (*).")
@click.option("-m", "--music", is_flag=True, default=False,
help="Do not remove captions containing 1 or more \"♪\" or \"#\" symbols.")
@click.option("-e", "--effects", is_flag=True, default=False,
help="Do not remove captions between and including parenthesis \"()\" or brackets \"[]\".")
@click.option("-n", "--names", is_flag=True, default=False,
help="Do not replace names in captions with \"-\".")
@click.option("-c", "--credit", is_flag=True, default=False,
help="Do not remove captions with author tags, e.g., `Subtitles by PwnedDude967`.")
def strip_hi(path: Path, fonts: bool, ast: bool, music: bool, effects: bool, names: bool, credit: bool) -> None:
"""
\b
Batch strip text for Hearing Impaired from SRT subtitles.
You may provide either a Folder containing .SRT subtitles, or a direct
path to a single .SRT subtitle.
\b
All filtering is done by mattlyon93's subtitle-filter:
https://github.com/mattlyon93/filter-subs
\b
All parameters specify filtering to keep. All filtering is enabled by
default. Filters are applied in the order listed.
\b
The following filters and fixes are also applied at the very end:
- Erroneous comma spacing, e.g., `Hey , what's up? Nothing,my man.`
- Lone symbols such as `?`, `-`, `#`, `_`.
These cannot be disabled.
\b
The `--ast` filter may need to be disabled depending on the captioning.
Some services or captions may use `*` for non-Hearing-Impaired uses.
Adversely, some use it as a censorship symbol, e.g. `F*** you!`. The
asterisk may also be used for effects instead of brackets.
\b
The `--credit` parameter is useful to remove annoying old P2P or DDL
Subtitle Author captions, but is not extensive. General fair authorship is
not filtered, e.g. `Captioning sponsored by NICKELODEON.` is not removed.
"""
log = logging.getLogger("strip-hi")
if not path.exists():
log.error(f"Provided path does not exist: {path}")
if path.is_file():
subtitles = [path]
else:
subtitles = list(path.glob("*.srt"))
log.info(f"Found {len(subtitles)} SRT subtitle{['s', ''][len(subtitles) == 1]}")
for subtitle in tqdm(subtitles, unit="subs"):
sub = Subtitles(subtitle)
sub.filter(
rm_fonts=not fonts,
rm_ast=not ast,
rm_music=not music,
rm_effects=not effects,
rm_names=not names,
rm_author=not credit
)
sub.save()
log.info("Done! All subtitles have been filtered.") | /rpg-handbook-0.1.0.tar.gz/rpg-handbook-0.1.0/rpg_handbook/commands/strip-hi.py | 0.587115 | 0.200656 | strip-hi.py | pypi |
from rpg_icon_generator.utils.vector import Vector
import math
from rpg_icon_generator.generator.__generator import Generator
class Blade_Generator(Generator):
def generate(self, seed, dimension, render_scale, output_directory, complexity):
self.reset_canvas(dimension, render_scale, output_directory)
self.set_seed(seed)
self.set_drawing_bound(dimension, complexity)
# length of the pommel
pommelLength = math.ceil(self.random.float_low() * 2 * self.dscale)
# length of the hilt
hiltLength = math.ceil(self.random.range(6, 11) * self.dscale)
# width of the xguard
xguardWidth = math.ceil(self.random.range(1, 4) * self.dscale)
bladeResults = self._draw_blade_helper(pommelLength + hiltLength + xguardWidth)
# draw the hilt
hiltStartDiag = math.floor((pommelLength * math.sqrt(2)))
hiltParams = {
"startDiag": hiltStartDiag,
"lengthDiag": math.floor(bladeResults["startOrtho"] - hiltStartDiag),
"maxRadius": bladeResults["startRadius"]
}
self._draw_grip_helper(hiltParams)
# draw the crossguard
crossguardParams = {
"positionDiag": bladeResults["startOrtho"],
"halfLength": bladeResults["startRadius"] * (1 + 2 * self.random.float_low()) + 1
}
crossguardResults = self._draw_crossguard_helper(crossguardParams)
# draw the pommel
pommelRadius = pommelLength * math.sqrt(2) / 2
pommelParams = {
"center": Vector(math.floor(pommelRadius + self.turtle_bound.x), math.ceil(self.drawing_bound.h - (pommelRadius + self.turtle_bound.y))),
"radius": pommelRadius,
"colorLight": crossguardResults["colorLight"],
"colorDark": crossguardResults["colorDark"]
}
self._draw_round_ornament_helper(pommelParams)
self._draw_border()
self._draw_rarity_border(complexity)
self.export(seed) | /rpg_icon_generator-0.5.0-py3-none-any.whl/rpg_icon_generator/generator/blade.py | 0.700792 | 0.254295 | blade.py | pypi |
from rpg_icon_generator.utils.vector import Vector
import math
from rpg_icon_generator.utils.color import Color
from rpg_icon_generator.generator.__generator import Generator
class Potion_Generator(Generator):
def generate(self, seed, dimension, render_scale, output_directory, complexity):
self.reset_canvas(dimension, render_scale, output_directory)
self.set_seed(seed)
self.set_drawing_bound(dimension, complexity)
width = self.turtle_bound.w
height = self.turtle_bound.h
centerXL = (width/2-1) + self.turtle_bound.x
# height of bottle lip
lipHeight = math.ceil(self.random.range(2, 5) * self.dscale)
# height of stopper sticking out of bottle
stopperTopHeight = math.ceil(self.random.range(2, 5) * self.dscale)
# depth of stopper into the bottle
stopperDepth = self.random.range(lipHeight + 1, lipHeight + math.floor(4 * self.dscale))
# width of stopper inside bottle
stopperWidth = math.ceil(self.random.range(2, 6) * self.dscale) * 2
# width of bottle neck
neckWidth = stopperWidth + 2
# width of bottle lip
lipWidth = neckWidth + math.ceil(self.random.range(2, 4) * self.dscale) * 2
# width of outer stopper
stopperTopWidth = min(stopperWidth + 2, lipWidth - 2)
# top of stopper
stopperTop = self.turtle_bound.y
# top of lip
lipTop = stopperTop + stopperTopHeight
# top of neck
neckTop = lipTop + lipHeight
# bottom of bottle
bottleBottom = self.turtle_bound.y + height
# fluid start
fluidTop = neckTop + \
self.random.range_float(height/8, (bottleBottom-neckTop)*0.6)
# min dist between contour changes
contourInterval = math.floor(4 * self.dscale)
stopperLight = Color(222, 152, 100)
stopperDark = Color(118, 49, 0)
innerBorderLight = Color(213, 226, 239)
innerBorderDark = Color(181, 196, 197)
glassLight = Color(227, 244, 248, 165/255)
glassDark = Color(163, 187, 199, 165/255)
fluidColor = Color.random_color(self.random)
fluidColor2 = fluidColor.copy().randomize(300, self.random)
# generate shape of neck/body
contour = [None for i in range(bottleBottom+1)]
contour[neckTop] = neckWidth/2
velocity = 0
acceleration = 0
direction = 1
bodyTop = neckTop + 1
for b in range(bodyTop, bottleBottom+1):
d = math.floor(velocity)
velocity += acceleration
contour[b] = max(neckWidth/2, min(width/2-2, contour[b-1]+d))
if b % contourInterval == 0 and self.random.float()<=0.5:
acceleration = direction * self.random.range(0,5)/2
direction = -direction
# draw outer stopper
stopperLeft = centerXL - stopperTopWidth/2 + 1
for x in range(stopperTopWidth):
n = (x / (stopperTopWidth - 1))-0.5
color = Color.lerp(stopperLight, stopperDark, n)
self.fill_rect(int(x + stopperLeft), int(stopperTop), 1, int(stopperTopHeight), color)
# draw body
previousContour = lipWidth
for y in range(neckTop, len(contour)):
contourWidth = int(contour[y]*2)
# draw fluid
if y > fluidTop:
vn = (y - fluidTop) / (bottleBottom - fluidTop)
left = int(centerXL - contourWidth/2)
for x in range(1, contourWidth):
n = x/(contourWidth-1)-(0.5+self.random.float()*0.1)
color = Color.lerp(
Color.lerp(fluidColor, fluidColor2, vn),
Color.lerp(
fluidColor.copy().darken(1),
fluidColor2.copy().darken(1),
vn
),
n
)
self.draw_pixel(left + x, y, color)
# draw glass
if y >= neckTop and y <= fluidTop:
left = int(centerXL - contourWidth/2)
for x in range(1, contourWidth):
n = x/(contourWidth-1)
color = Color.lerp(glassLight, glassDark, n)
self.draw_pixel(left + x, y, color)
if contourWidth == previousContour:
# contour is the same
self.draw_pixel(int(centerXL - contourWidth/2 + 1), y, innerBorderLight)
self.draw_pixel(int(centerXL + contourWidth/2), y, innerBorderDark)
else:
yOff = y-1 if previousContour < contourWidth else y
yInner = y if previousContour < contourWidth else y-1
minContour = min(contourWidth, previousContour)
lineWidth = abs(previousContour - contourWidth)/2
lineOffset = lineWidth-1
self.fill_rect(centerXL - minContour/2 - lineWidth + 1, yInner, lineWidth, 1, innerBorderLight)
self.draw_pixel(centerXL - contourWidth/2 + 1, y, innerBorderLight)
self.fill_rect(centerXL + minContour/2 + 1, yInner, lineWidth, 1, innerBorderLight)
self.draw_pixel(centerXL + contourWidth/2, y, innerBorderLight)
previousContour = contourWidth
# draw overlay stuff
previousContour = lipWidth
for y in range(neckTop, len(contour)):
contourWidth = contour[y]*2
# draw top-left reflection
if previousContour < contourWidth:
reflectWidth = max(1, contourWidth - previousContour)
# crunch toward middle
crunch = 1 - 0.3 * contourWidth / width
reflectOffset = round((2 - contourWidth/2) * crunch)
self.fill_rect(centerXL + reflectOffset, y + 2, reflectWidth * crunch, 1, Color(255, 255, 255, 0.5))
previousContour = contourWidth
# draw inner stopper
stopperInnerLeft = centerXL - stopperWidth/2 + 1
for x in range(stopperWidth):
n = (x / (stopperWidth - 1))-0.5
c = Color.lerp(stopperLight, stopperDark, n)
self.fill_rect(x + stopperInnerLeft, lipTop, 1, stopperDepth, c)
# draw lip (over stopper)
lipLeft = centerXL - lipWidth/2 + 1
self.fill_rect(lipLeft, lipTop, 1, lipHeight, innerBorderLight)
self.fill_rect(lipLeft + lipWidth - 1, lipTop, 1, lipHeight, innerBorderDark)
for x in range(1, lipWidth-1):
n = ((x-1) / (lipWidth-3))-0.5
self.fill_rect(x + lipLeft, lipTop, 1, lipHeight, Color.lerp(glassLight, glassDark, n))
# draw bottom border
borderLeft = centerXL - contour[bottleBottom] + 1
borderWidth = int(contour[bottleBottom]*2)
for x in range(borderWidth):
n = (x/(borderWidth-1))-0.5
self.draw_pixel(borderLeft + x, bottleBottom, Color.lerp(innerBorderLight, innerBorderDark, n))
self._draw_border()
self._draw_rarity_border(complexity)
self.export(seed) | /rpg_icon_generator-0.5.0-py3-none-any.whl/rpg_icon_generator/generator/potion.py | 0.568296 | 0.264762 | potion.py | pypi |
from rpg_icon_generator.utils.vector import Vector
import math
from rpg_icon_generator.generator.__generator import Generator
class Axe_Generator(Generator):
def generate(self, seed, dimension, render_scale, output_directory, complexity):
self.reset_canvas(dimension, render_scale, output_directory)
self.set_seed(seed)
self.set_drawing_bound(dimension, complexity)
# length of the pommel
pommelLength = math.ceil(self.random.float_low() * 2 * self.dscale)
hiltStartDiag = math.floor((pommelLength * math.sqrt(2)))
# length of the hilt
lengthDiag = (self.turtle_bound.w - hiltStartDiag) * 0.8
# draw the hilt
hiltParams = {
"startDiag": hiltStartDiag,
"lengthDiag": lengthDiag,
"maxRadius": None
}
grip_size = self._draw_grip_helper(hiltParams)
complexity_factor = (complexity/100) + 0.5
offset = self.random.range(7, 12) * complexity_factor
body_width = self.random.range(0, 6) + grip_size + 3
body_heigth = self.random.range(4, 10) * complexity_factor
axe_width = self.random.range(5, 15) * complexity_factor
dark_color, light_color = self._draw_axe_blade_helper(
origine=Vector(
(self.turtle_bound.x + lengthDiag) - 2,
self.drawing_bound.h - ((self.turtle_bound.y + lengthDiag) - 2)),
offset=offset,
body_width=body_width,
body_heigth=body_heigth,
axe_width=axe_width
)
# draw the pommel
pommelRadius = pommelLength * math.sqrt(2) / 2
pommelParams = {
"center": Vector(math.floor(pommelRadius + self.turtle_bound.x), math.ceil(self.drawing_bound.h - (pommelRadius + self.turtle_bound.y))),
"radius": pommelRadius,
"colorLight": light_color,
"colorDark": dark_color
}
self._draw_round_ornament_helper(pommelParams)
self._draw_border()
self._draw_rarity_border(complexity)
self.export(seed) | /rpg_icon_generator-0.5.0-py3-none-any.whl/rpg_icon_generator/generator/axe.py | 0.643777 | 0.272008 | axe.py | pypi |
import math
import random
import colorsys
import copy
class Color:
def __init__(self, r, g, b, a=1):
self.r = r
self.g = g
self.b = b
self.a = a
def darken(self, t):
self.r *= (1-t)
self.g *= (1-t)
self.b *= (1-t)
return self
def __str__(self):
return "Color(R: {}, G: {}, B: {}, A: {})".format(self.r, self.g, self.b, self.a)
def __repr__(self):
return str(self)
def lighten(self, t):
t = 1-t
self.r = (1 - (1 - self.r/255) * t) * 255
self.g = (1 - (1 - self.g/255) * t) * 255
self.b = (1 - (1 - self.b/255) * t) * 255
return self
def randomize(self, maxamt, r):
maxamtHalf = math.floor(maxamt/2)
self.r = max(0, min(255, self.r + r.range(-maxamtHalf, maxamtHalf)))
self.g = max(0, min(255, self.g + r.range(-maxamtHalf, maxamtHalf)))
self.b = max(0, min(255, self.b + r.range(-maxamtHalf, maxamtHalf)))
return self
def copy(self):
return copy.deepcopy(self)
def to_hex(self):
return '#{:02x}{:02x}{:02x}'.format(math.floor(self.r), math.floor(self.g), math.floor(self.b))
def is_black(self):
return self.a == 1 and self.r == 0 and self.g == 0 and self.b == 0
def is_empty(self, ignore_black=False):
return (self.a == 0 or self.is_black() if ignore_black else False)
def get_tetradic(self):
r, g, b = map(lambda x: x/255.0, [self.r, self.g, self.b])
#hls provides color in radial scale
h, l, s = colorsys.rgb_to_hls(r, g, b)
#get hue changes at 120 and 240 degrees
deg_60_hue = h + (60.0 / 360.0)
deg_180_hue = h + (180.0 / 360.0)
deg_240_hue = h + (240.0 / 360.0)
#convert to rgb
color_60_rgb = list(map(lambda x: round(x * 255),colorsys.hls_to_rgb(deg_60_hue, l, s)))
color_180_rgb = list(map(lambda x: round(x * 255),colorsys.hls_to_rgb(deg_180_hue, l, s)))
color_240_rgb = list(map(lambda x: round(x * 255),colorsys.hls_to_rgb(deg_240_hue, l, s)))
return [Color(*color_60_rgb), Color(*color_180_rgb), Color(*color_240_rgb)]
def __eq__(self, other):
return self.r == other.r and self.g == other.g and self.b == other.b and self.a == other.a
@staticmethod
def hsv2rgb(h, s, v):
r, g, b = tuple(round(i * 255) for i in colorsys.hsv_to_rgb(h/360, s, v))
return Color(r, g, b)
@staticmethod
def lerp(a, b, t):
t = max(0, min(1, t))
cr = (b.r - a.r) * t + a.r
cg = (b.g - a.g) * t + a.g
cb = (b.b - a.b) * t + a.b
aa = a.a
ba = b.a
ca = (ba - aa) * t + aa
return Color(cr, cg, cb, ca)
@staticmethod
def random_color(random):
r = random.range(0, 256)
g = random.range(0, 256)
b = random.range(0, 256)
return Color(r, g, b) | /rpg_icon_generator-0.5.0-py3-none-any.whl/rpg_icon_generator/utils/color.py | 0.661923 | 0.327252 | color.py | pypi |
import copy
import math
class Vector:
def __init__(self, x=None, y=None):
self.x = 0
self.y = 0
if y is None:
if x is not None:
self.x = x.x
self.y = x.y
else:
self.x = x
self.y = y
def __str__(self):
return "Vector(x: {}, y: {})".format(self.x, self.y)
def __repr__(self):
return str(self)
def normalize(self):
length = self.length()
self.x /= length
self.y /= length
return self
def length(self):
return math.sqrt(self.x * self.x + self.y * self.y)
def length_Sq(self):
return self.x * self.x + self.y * self.y
def distance_to(self, x, y):
return math.sqrt(self.distance_to_sq(x, y))
def distance_to_sq(self, x, y=None):
if y is None:
dx = self.x - x.x
dy = self.y - x.y
else:
dx = self.x - x
dy = self.y - y
return dx * dx + dy * dy
def add_vector(self, v):
self.x += v.x
self.y += v.y
return self
def lerp_to(self, v, t):
self.x = (v.x - self.x) * t + self.x
self.y = (v.y - self.y) * t + self.y
return self
def multiply_scalar(self, v):
self.x *= v
self.y *= v
return self
def dot_product(self, x, y=None):
if y is None:
return self.x * x.x + self.y * x.y
else:
return self.x * x + self.y * y
def set(self, x, y=None):
if y is None:
self.x = x.x
self.y = x.y
else:
self.x = x
self.y = y
return self
def copy(self):
return copy.deepcopy(self)
def to_coord(self):
return (self.x, self.y)
def rotate(self, radians, origin=None):
origin = origin if origin is not None else Vector(0, 0)
x, y = self.x, self.y
offset_x, offset_y = origin.x, origin.y
adjusted_x = (x - offset_x)
adjusted_y = (y - offset_y)
cos_rad = math.cos(radians)
sin_rad = math.sin(radians)
self.x = offset_x + cos_rad * adjusted_x + sin_rad * adjusted_y
self.y = offset_y + -sin_rad * adjusted_x + cos_rad * adjusted_y
return self
def round(self):
self.x = round(self.x)
self.y = round(self.y)
return self | /rpg_icon_generator-0.5.0-py3-none-any.whl/rpg_icon_generator/utils/vector.py | 0.730001 | 0.448728 | vector.py | pypi |
from bs4 import BeautifulSoup
import requests
"""
Brute Force extractor for lists on Wikipedia for naming extraction.
Logical flow may not work if lists are nested in a non-expected way (e.g. ul>li>ul)
This also is assuming that post-processing of each list will be done, as some values will be extracted incorrectly.
"""
def extract(url, outfile, letter_filter=None, other_filters=None):
titles = list()
filter_attrs = {
'class': None
}
resp = requests.get(url).content
bs = BeautifulSoup(resp, "html.parser")
uls = bs.findAll("ul")
for ul in uls:
for li in ul.findAll('li'):
for a in li.findAll('a', attrs=filter_attrs):
title = str(a.get('title')).lower()
entry = a.get('title')
add_to = True
if letter_filter:
if not title.startswith(letter_filter):
add_to = False
if other_filters:
if other_filters in title:
add_to = False
if not letter_filter and not other_filters:
titles.append(a.get('title'))
elif add_to:
titles.append(entry)
for item in titles:
try:
if '(' in item or ')' in item:
titles.remove(item)
except TypeError as err:
print("%s on item %s" % (err, item))
with open(outfile, 'w+') as file:
for item in titles:
file.write("%s\n" % item)
def legendaries():
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for char in letters:
base_url = "https://en.wikipedia.org/wiki/List_of_legendary_creatures_(%s)" % char
file = "%s.txt" % char
filter = "%s" % char.lower()
other = "myth"
extract(base_url, file, filter, other)
if __name__ == "__main__":
_url = input("Enter target url: ")
_outfile = input("Enter output file:")
_letter_filter = input("Enter letter filter (if any): ") or None
_other_filter = input("Enter any other filter to exclude: ") or None
extract(_url, _outfile, _letter_filter, _other_filter)
# Example information:
# url = "https://en.wikipedia.org/wiki/List_of_legendary_creatures_(A)"
# outfile = "legendary_creatures_a.txt"
# letter_filter = "a"
# other_filter = "myth" | /rpg_namer-1.0.1.tar.gz/rpg_namer-1.0.1/rpg_namer/examples/extractor.py | 0.492188 | 0.18374 | extractor.py | pypi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.