Skip to content

Commit

Permalink
add workspace and sibling tasks support in project creation
Browse files Browse the repository at this point in the history
  • Loading branch information
pritamrungta committed Mar 4, 2024
1 parent 6d26513 commit 93f2a60
Show file tree
Hide file tree
Showing 6 changed files with 121 additions and 9 deletions.
64 changes: 62 additions & 2 deletions redbrick/cli/command/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ def __init__(self, parser: ArgumentParser) -> None:
"-r",
help="Number of review stages",
)
parser.add_argument(
"--workspace",
"-w",
help="The workspace that you want to add this project to",
)
parser.add_argument(
"--sibling-tasks",
help="Number of tasks created for each uploaded datapoint",
)
parser.add_argument(
"path",
nargs="?",
Expand Down Expand Up @@ -53,6 +62,7 @@ def handler(self, args: Namespace) -> None:

def handle_init(self) -> None:
"""Handle empty sub command."""
# pylint: disable=too-many-locals
assert_validation(self.project.creds.exists, "Credentials missing")

console = Console()
Expand All @@ -75,15 +85,65 @@ def handle_init(self) -> None:
status.stop()
raise error

with console.status("Fetching workspaces") as status:
try:
workspaces = org.workspaces_raw()
except Exception as error:
status.stop()
raise error

name = CLIInputText(
self.args.name, "Name", os.path.basename(self.project.path)
).get()
taxonomy = CLIInputSelect(self.args.taxonomy, "Taxonomy", taxonomies).get()
reviews = int(CLIInputNumber(self.args.reviews, "Reviews").get())
reviews = int(CLIInputNumber(self.args.reviews, "Reviews", "1").get())

workspace_ids, workspace_names, workspace_choices = [""], [""], ["--- NONE ---"]
for workspace in workspaces:
workspace_ids.append(workspace["workspaceId"])
workspace_names.append(workspace["name"])
workspace_choices.append(
workspace["name"] + " (" + workspace["workspaceId"] + ")"
)

selected_workspace = self.args.workspace
if selected_workspace:
index = -1
if selected_workspace in workspace_ids:
index = workspace_ids.index(selected_workspace)
elif selected_workspace in workspace_names:
index = workspace_names.index(selected_workspace)

if index >= 0:
selected_workspace = (
workspace_names[index] + " (" + workspace_ids[index] + ")"
)

workspace_id = workspace_ids[
workspace_choices.index(
CLIInputSelect(
selected_workspace, "Workspaces", workspace_choices
).get()
)
]

sibling_tasks = CLIInputNumber(
self.args.sibling_tasks, "Sibling Tasks", "", False
).get()

with console.status("Creating project") as status:
try:
project = org.create_project(name, taxonomy, reviews)
project = org.create_project(
name=name,
taxonomy_name=taxonomy,
reviews=reviews,
workspace_id=workspace_id or None,
sibling_tasks=(
None
if not sibling_tasks or int(sibling_tasks) <= 1
else int(sibling_tasks)
),
)
except Exception as error:
status.stop()
raise error
Expand Down
1 change: 1 addition & 0 deletions redbrick/common/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def create_project(
td_type: str,
tax_name: str,
workspace_id: Optional[str],
sibling_tasks: Optional[int],
) -> Dict:
"""Create a project and return project_id."""

Expand Down
6 changes: 5 additions & 1 deletion redbrick/common/workspace.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
"""Interface for getting basic information about a workspace."""

from typing import Dict
from typing import Dict, List
from abc import ABC, abstractmethod


class WorkspaceRepoInterface(ABC):
"""Abstract interface to Workspace APIs."""

@abstractmethod
def get_workspaces(self, org_id: str) -> List[Dict]:
"""Get list of workspaces."""

@abstractmethod
def get_workspace(self, org_id: str, workspace_id: str) -> Dict:
"""
Expand Down
32 changes: 29 additions & 3 deletions redbrick/organization/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@ def taxonomies(self, only_name: bool = True) -> Union[List[str], List[Taxonomy]]
return [tax["name"] for tax in taxonomies]
return list(map(format_taxonomy, taxonomies))

def workspaces_raw(self) -> List[Dict]:
"""Get a list of active workspaces as raw objects in the organization."""
workspaces = self.context.workspace.get_workspaces(self._org_id)
workspaces = list(
filter(lambda x: x["status"] == "CREATION_SUCCESS", workspaces)
)

return workspaces

def projects_raw(self) -> List[Dict]:
"""Get a list of active projects as raw objects in the organization."""
projects = self.context.project.get_projects(self._org_id)
Expand Down Expand Up @@ -123,6 +132,7 @@ def create_project_advanced(
stages: Sequence[Stage],
exists_okay: bool = False,
workspace_id: Optional[str] = None,
sibling_tasks: Optional[int] = None,
) -> RBProject:
"""
Create a project within the organization.
Expand All @@ -148,7 +158,10 @@ def create_project_advanced(
do not want to keep creating new projects.
workspace_id: Optional[str] = None
The workspace id that you want to add this project to.
The id of the workspace that you want to add this project to.
sibling_tasks: Optional[int] = None
Number of tasks created for each uploaded datapoint.
Returns
--------------
Expand Down Expand Up @@ -176,6 +189,9 @@ def create_project_advanced(
return temp

try:
sibling_tasks = (
None if sibling_tasks is None or sibling_tasks <= 1 else sibling_tasks
)
taxonomy = self.context.project.get_taxonomy(
org_id=self.org_id, tax_id=None, name=taxonomy_name
)
Expand All @@ -186,6 +202,7 @@ def create_project_advanced(
"DICOM_SEGMENTATION",
taxonomy_name,
workspace_id,
sibling_tasks,
)
except ValueError as error:
raise Exception(
Expand All @@ -202,6 +219,7 @@ def create_project(
reviews: int = 0,
exists_okay: bool = False,
workspace_id: Optional[str] = None,
sibling_tasks: Optional[int] = None,
) -> RBProject:
"""
Create a project within the organization.
Expand All @@ -228,15 +246,23 @@ def create_project(
do not want to keep creating new projects.
workspace_id: Optional[str] = None
The workspace id that you want to add this project to.
The id of the workspace that you want to add this project to.
sibling_tasks: Optional[int] = None
Number of tasks created for each uploaded datapoint.
Returns
--------------
redbrick.project.RBProject
A RedBrick Project object.
"""
return self.create_project_advanced(
name, taxonomy_name, get_middle_stages(reviews), exists_okay, workspace_id
name,
taxonomy_name,
get_middle_stages(reviews),
exists_okay,
workspace_id,
sibling_tasks,
)

def get_project(
Expand Down
4 changes: 4 additions & 0 deletions redbrick/repo/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def create_project(
td_type: str,
tax_name: str,
workspace_id: Optional[str],
sibling_tasks: Optional[int],
) -> Dict:
"""Create a project and return project_id."""
query = """
Expand All @@ -69,6 +70,7 @@ def create_project(
$taxonomyName: String!
$taxonomyVersion: Int!
$workspaceId: UUID
$taskDuplicationCount: Int
) {
createProjectSimple(
orgId: $orgId
Expand All @@ -78,6 +80,7 @@ def create_project(
taxonomyName: $taxonomyName
taxonomyVersion: $taxonomyVersion
workspaceId: $workspaceId
taskDuplicationCount: $taskDuplicationCount
) {
ok
errors
Expand All @@ -99,6 +102,7 @@ def create_project(
"taxonomyName": tax_name,
"taxonomyVersion": 1,
"workspaceId": workspace_id,
"taskDuplicationCount": sibling_tasks,
}

response: Dict[str, Dict] = self.client.execute_query(query, variables)
Expand Down
23 changes: 20 additions & 3 deletions redbrick/repo/workspace.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Handlers to access APIs for getting workspaces."""

from typing import Dict
from typing import Dict, List

from redbrick.common.client import RBClient
from redbrick.common.workspace import WorkspaceRepoInterface
Expand All @@ -13,15 +13,32 @@ def __init__(self, client: RBClient) -> None:
"""Construct WorkspaceRepo."""
self.client = client

def get_workspaces(self, org_id: str) -> List[Dict]:
"""Get list of workspaces."""
query = """
query sdkGetWorkspacesSDK($orgId: UUID!) {
workspaces(orgId: $orgId) {
orgId
workspaceId
name
status
createdAt
}
}
"""
variables = {"orgId": org_id}
response: Dict[str, List[Dict]] = self.client.execute_query(query, variables)
return response["workspaces"]

def get_workspace(self, org_id: str, workspace_id: str) -> Dict:
"""
Get workspace name and status.
Raise an exception if workspace does not exist.
"""
query = """
query sdkGetWorkspaceSDK($orgId: UUID!, $workspaceId: UUID!){
workspace(orgId: $orgId, workspaceId: $workspaceId){
query sdkGetWorkspaceSDK($orgId: UUID!, $workspaceId: UUID!) {
workspace(orgId: $orgId, workspaceId: $workspaceId) {
orgId
workspaceId
name
Expand Down

0 comments on commit 93f2a60

Please sign in to comment.