Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@
IM_SEQUENCE_STARTED = "IM sequence started"
IM_SEQUENCE_FINISHED = "IM sequence finished"
IM_SEQUENCE_SUCCESSFUL = "IM sequence successful"

JUPYTER_DEFAULT_SERVICE = "https://notebooks-dev.egi.zcu.cz"
JUPYTER_PROGRAMMING_LANGUAGE = "https://jupyter.org"
1 change: 1 addition & 0 deletions app/vres/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
from .binder import VREBinder
from .sciencemesh import VREScienceMesh
from .scipion import VREScipion
from .jupyter import VREJupyter
120 changes: 120 additions & 0 deletions app/vres/jupyter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import io
import json
from typing import Any, Dict, Optional
from .base_vre import VRE, vre_factory
import requests
import logging
from app import exceptions
from app.constants import (
JUPYTER_DEFAULT_SERVICE,
JUPYTER_PROGRAMMING_LANGUAGE,
)
import zipfile as zf
import time

logging.basicConfig(level=logging.INFO)


class VREJupyter(VRE):
def get_default_service(self):
return JUPYTER_DEFAULT_SERVICE

def _get_headers(self, token_type, token):
return {
"Authorization": f"{token_type} {token}",
"Accept": "application/json",
}

def post(self):
user_name = self._get_username()
self._start_jupyter_server(user_name)
api_token = self._create_api_token(user_name)
notebook_name, notebook_content = self._get_notebook_from_zipfile()
self._wait_for_server_creation()
self.upload_notebook(notebook_content, notebook_name, user_name, api_token)
Comment thread
andrejcermak marked this conversation as resolved.
return f"{self.get_default_service()}/user/{user_name}"

def _get_username(self):
userinfo = self._get_userinfo()
user_name = userinfo.get("name")
return user_name

def _get_userinfo(self):
userinfo_url = f"{self.get_default_service()}/services/jwt/user"
userinfo = requests.get(
userinfo_url, headers=self._get_headers("Bearer", self.token)
).json()

return userinfo

def _start_jupyter_server(self, user_name):
url = f"{self.get_default_service()}/services/jwt/users/{user_name}/servers/"
response = requests.post(url, headers=self._get_headers("Bearer", self.token))
response.raise_for_status()

def _create_api_token(self, username: Optional[str] = None) -> str:
"""Create a new API token for Jupyter Server API access."""
url = f"{self.get_default_service()}/services/jwt/users/{username}/tokens"

try:
response = requests.post(
url, headers=self._get_headers("Bearer", self.token)
)
response.raise_for_status()
token_data = response.json()
print(token_data)
api_token = token_data.get("token")
if not api_token:
raise exceptions.ServiceError("Token not found in response")
return api_token
except requests.RequestException as e:
logging.error(f"Failed to create API token: {e}")
raise exceptions.ServiceError(f"Token creation failed: {e}")

def _get_notebook_from_zipfile(self):
Comment thread
andrejcermak marked this conversation as resolved.
copied_file_name = ""
with io.BytesIO(self.body) as bytes_io:
with zf.ZipFile(bytes_io) as zfile:
for filename in zfile.namelist():
if filename.endswith(".ipynb"):
copied_file_name = filename
with zfile.open(filename) as f:
notebook_content = json.load(f)
return copied_file_name, notebook_content

def _wait_for_server_creation(self):
info = self._get_userinfo()

while (info.get("server") is None) or (
info.get("servers").get("").get("ready") == False
):
time.sleep(10)
info = self._get_userinfo()

def upload_notebook(
self,
notebook_content: Dict[str, Any],
filename: str,
username: Optional[str],
api_token,
) -> Dict[str, Any]:
"""Upload a notebook file to the user's Jupyter server."""
url = f"{self.get_default_service()}/user/{username}/api/contents/{filename}"

headers = self._get_headers("token", api_token)
payload = {
"type": "notebook",
"format": "json",
"content": notebook_content,
}

try:
response = requests.put(url, headers=headers, data=json.dumps(payload))
response.raise_for_status()
return response.json()
except requests.RequestException as e:
logging.error(f"Failed to upload notebook: {e}")
raise exceptions.ServiceError(f"Upload failed: {e}")


vre_factory.register(JUPYTER_PROGRAMMING_LANGUAGE, VREJupyter)
64 changes: 64 additions & 0 deletions test/jupyter/notebook.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "b60780b6-86b5-4c19-bcc6-91ecd0e9c801",
"metadata": {},
"outputs": [],
"source": [
"import math"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "65c20a28-c09c-414c-a9bf-5a073880bd20",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3.141592653589793"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"math.pi"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "51e02ffd-0b68-448e-9808-0d5197faf528",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
58 changes: 58 additions & 0 deletions test/jupyter/ro-crate-metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
{
"@context": "https://w3id.org/ro/crate/1.1/context",
"@graph": [
{
"@id": "./",
"@type": "Dataset",
"datePublished": "2025-05-06T14:35:47+00:00",
"mainEntity": {
"@id": "notebook.ipynb"
},
"runsOn": {
"@id": "#destination"
},
"hasPart": [
{
"@id": "notebook.ipynb"
},
{
"@id": "#destination"
}
]
},
{
"@id": "ro-crate-metadata.json",
"@type": "CreativeWork",
"about": {
"@id": "./"
},
"conformsTo": {
"@id": "https://w3id.org/ro/crate/1.1"
}
},
{
"@id": "notebook.ipynb",
"@type": [
"File",
"SoftwareSourceCode",
"ComputationalWorkflow"
],
"name": "Example jupyter notebook",
"programmingLanguage": {
"@id": "#jupyter"
}
},
{
"@id": "#jupyter",
"@type": "ComputerLanguage",
"identifier": {
"@id": "https://jupyter.org"
},
"name": "Jupyter Notebook"
},
{
"@id": "#destination",
"@type": "Service"
}
]
}