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
6 changes: 3 additions & 3 deletions opencodeblocks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@

""" OpenCodeBlocks: An open-source tool for modular visual programing in python """

__appname__ = 'OpenCodeBlocks'
__author__ = 'Mathïs Fédérico'
__version__ = '0.0.1'
__appname__ = "OpenCodeBlocks"
__author__ = "Mathïs Fédérico"
__version__ = "0.0.1"
3 changes: 1 addition & 2 deletions opencodeblocks/blocks/block.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,7 @@ def get_socket_pos(self, socket: OCBSocket) -> Tuple[float]:
y = y_offset
else:
side_lenght = self.height - y_offset - 2 * socket.radius - self.edge_size
y = y_offset + side_lenght * \
sockets.index(socket) / (len(sockets) - 1)
y = y_offset + side_lenght * sockets.index(socket) / (len(sockets) - 1)
return x, y

def update_sockets(self):
Expand Down
13 changes: 5 additions & 8 deletions opencodeblocks/blocks/codeblock.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,16 +88,14 @@ def init_run_button(self):
"""Initialize the run button"""
run_button = QPushButton(">", self.root)
run_button.move(int(self.edge_size), int(self.edge_size / 2))
run_button.setFixedSize(int(3 * self.edge_size),
int(3 * self.edge_size))
run_button.setFixedSize(int(3 * self.edge_size), int(3 * self.edge_size))
run_button.clicked.connect(self.run_left)
return run_button

def init_run_all_button(self):
"""Initialize the run all button"""
run_all_button = QPushButton(">>", self.root)
run_all_button.setFixedSize(
int(3 * self.edge_size), int(3 * self.edge_size))
run_all_button.setFixedSize(int(3 * self.edge_size), int(3 * self.edge_size))
run_all_button.clicked.connect(self.run_right)
run_all_button.raise_()

Expand Down Expand Up @@ -141,7 +139,7 @@ def has_output(self) -> bool:
return False

def _interrupt_execution(self):
""" Interrupt an execution, reset the blocks in the queue """
"""Interrupt an execution, reset the blocks in the queue"""
for block, _ in self.source_editor.kernel.execution_queue:
# Reset the blocks that have not been run
block.reset_buttons()
Expand Down Expand Up @@ -200,13 +198,12 @@ def run_right(self):
# Same as run_left but instead of running the blocks, we'll use run_left
graph = self.scene().create_graph()
edges = bfs_edges(graph, self)
blocks_to_run: List["OCBCodeBlock"] = [
self] + [v for _, v in edges]
blocks_to_run: List["OCBCodeBlock"] = [self] + [v for _, v in edges]
for block in blocks_to_run[::-1]:
block.run_left(in_right_button=True)

def reset_has_been_run(self):
""" Reset has_been_run, is called when the output is an error """
"""Reset has_been_run, is called when the output is an error"""
self.has_been_run = False

def update_title(self):
Expand Down
44 changes: 23 additions & 21 deletions opencodeblocks/blocks/drawingblock.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@


class DrawableWidget(QWidget):
""" A drawable widget is a canvas like widget on which you can doodle """
"""A drawable widget is a canvas like widget on which you can doodle"""

def __init__(self, parent: QWidget):
""" Create a new Drawable widget """
"""Create a new Drawable widget"""
super().__init__(parent)
self.setAttribute(Qt.WA_PaintOnScreen)
self.pixel_width = 24
Expand All @@ -31,13 +31,13 @@ def __init__(self, parent: QWidget):
self.color_buffer[-1].append(0xFFFFFFFF)

def clearDrawing(self):
""" Clear the drawing """
"""Clear the drawing"""
for i in range(self.pixel_width):
for j in range(self.pixel_height):
self.color_buffer[i][j] = 0xFFFFFFFF

def paintEvent(self, evt: QPaintEvent):
""" Draw the content of the widget """
"""Draw the content of the widget"""
painter = QPainter(self)

for i in range(self.pixel_width):
Expand All @@ -50,11 +50,11 @@ def paintEvent(self, evt: QPaintEvent):
h * j,
w + eps,
h + eps,
QColor.fromRgb(
self.color_buffer[i][j]))
QColor.fromRgb(self.color_buffer[i][j]),
)

def mouseMoveEvent(self, evt: QMouseEvent):
""" Change the drawing when dragging the mouse around"""
"""Change the drawing when dragging the mouse around"""
if self.mouse_down:
x = floor(evt.x() / self.width() * self.pixel_width)
y = floor(evt.y() / self.height() * self.pixel_height)
Expand All @@ -63,52 +63,54 @@ def mouseMoveEvent(self, evt: QMouseEvent):
self.repaint()

def mousePressEvent(self, evt: QMouseEvent):
""" Signal that the drawing starts """
"""Signal that the drawing starts"""
self.mouse_down = True

def mouseReleaseEvent(self, evt: QMouseEvent):
""" Signal that the drawing stops """
"""Signal that the drawing stops"""
self.mouse_down = False


class OCBDrawingBlock(OCBBlock):
""" An OCBBlock on which you can draw, to test your CNNs for example"""
"""An OCBBlock on which you can draw, to test your CNNs for example"""

def __init__(self, **kwargs):
""" Create a new OCBBlock"""
"""Create a new OCBBlock"""
super().__init__(**kwargs)

self.draw_area = DrawableWidget(self.root)

self.splitter.addWidget(self.draw_area) # QGraphicsView
self.run_button = QPushButton("Clear", self.root)
self.run_button.move(int(self.edge_size * 2),
int(self.title_widget.height() + self.edge_size * 2))
self.run_button.setFixedSize(
int(8 * self.edge_size), int(3 * self.edge_size))
self.run_button.move(
int(self.edge_size * 2),
int(self.title_widget.height() + self.edge_size * 2),
)
self.run_button.setFixedSize(int(8 * self.edge_size), int(3 * self.edge_size))
self.run_button.clicked.connect(self.draw_area.clearDrawing)
self.holder.setWidget(self.root)

@property
def drawing(self):
""" A json-encoded representation of the drawing """
"""A json-encoded representation of the drawing"""
return json.dumps(self.draw_area.color_buffer)

@drawing.setter
def drawing(self, value: str):
self.draw_area.color_buffer = json.loads(value)

def serialize(self):
""" Return a serialized version of this widget """
"""Return a serialized version of this widget"""
base_dict = super().serialize()
base_dict["drawing"] = self.drawing

return base_dict

def deserialize(self, data: OrderedDict,
hashmap: dict = None, restore_id: bool = True):
""" Restore a markdown block from it's serialized state """
for dataname in ['drawing']:
def deserialize(
self, data: OrderedDict, hashmap: dict = None, restore_id: bool = True
):
"""Restore a markdown block from it's serialized state"""
for dataname in ["drawing"]:
if dataname in data:
setattr(self, dataname, data[dataname])

Expand Down
20 changes: 11 additions & 9 deletions opencodeblocks/blocks/markdownblock.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@


class OCBMarkdownBlock(OCBBlock):
""" A block that is able to render markdown text """
"""A block that is able to render markdown text"""

def __init__(self, **kwargs):
"""
Create a new OCBMarkdownBlock, a block that renders markdown
Create a new OCBMarkdownBlock, a block that renders markdown
"""
super().__init__(**kwargs)

Expand Down Expand Up @@ -46,13 +46,14 @@ def __init__(self, **kwargs):

self.rendered_markdown = QWebEngineView()
self.rendered_markdown.page().setBackgroundColor(
QColor.fromRgba64(0, 0, 0, alpha=0))
QColor.fromRgba64(0, 0, 0, alpha=0)
)

self.splitter.addWidget(self.rendered_markdown)
self.holder.setWidget(self.root)

def valueChanged(self):
""" Update markdown rendering when the content of the markdown editor changes """
"""Update markdown rendering when the content of the markdown editor changes"""
t = self.editor.text()

dark_theme = """
Expand All @@ -68,7 +69,7 @@ def valueChanged(self):

@property
def text(self) -> str:
""" The content of the markdown block """
"""The content of the markdown block"""
return self.editor.text()

@text.setter
Expand All @@ -82,10 +83,11 @@ def serialize(self):

return base_dict

def deserialize(self, data: OrderedDict,
hashmap: dict = None, restore_id: bool = True):
""" Restore a markdown block from it's serialized state """
for dataname in ['text']:
def deserialize(
self, data: OrderedDict, hashmap: dict = None, restore_id: bool = True
):
"""Restore a markdown block from it's serialized state"""
for dataname in ["text"]:
if dataname in data:
setattr(self, dataname, data[dataname])

Expand Down
1 change: 0 additions & 1 deletion opencodeblocks/core/serializable.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ class Serializable:
MANDATORY_FIELDS: OrderedDict = {}
DEFAULT_DATA: Set[str] = {}


def __init__(self):
self.id = id(self)

Expand Down
2 changes: 1 addition & 1 deletion opencodeblocks/graphics/edge.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class OCBEdge(QGraphicsPathItem, Serializable):
def __init__(
self,
edge_width: float = 4.0,
path_type = DEFAULT_DATA["path_type"],
path_type=DEFAULT_DATA["path_type"],
edge_color="#001000",
edge_selected_color="#00ff00",
source: QPointF = QPointF(0, 0),
Expand Down
9 changes: 4 additions & 5 deletions opencodeblocks/graphics/function_parsing.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

""" Module for code parsing and code execution """

from typing import List, Tuple
Expand Down Expand Up @@ -119,11 +118,11 @@ def execute_function(code: str, *args, **kwargs) -> str:

"""
function_name = get_function_name(code)
execution_code = f'{function_name}('
execution_code = f"{function_name}("
for arg in args:
execution_code += f'{arg},'
execution_code += f"{arg},"
for name, value in kwargs.items():
execution_code += f'{name}={value},'
execution_code += f"{name}={value},"

run_cell(code)
return run_cell(execution_code + ')')
return run_cell(execution_code + ")")
45 changes: 22 additions & 23 deletions opencodeblocks/graphics/kernel.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

""" Module to create and manage ipython kernels """

import queue
Expand All @@ -8,7 +7,7 @@
from opencodeblocks.graphics.worker import Worker


class Kernel():
class Kernel:

"""jupyter_client kernel used to execute code and return output"""

Expand All @@ -28,31 +27,31 @@ def message_to_output(self, message: dict) -> Tuple[str, str]:
single output found in the message in that order of priority:
image > text data > text print > error > nothing
"""
message_type = 'None'
if 'data' in message:
if 'image/png' in message['data']:
message_type = 'image'
message_type = "None"
if "data" in message:
if "image/png" in message["data"]:
message_type = "image"
# output an image (from plt.plot or plt.imshow)
out = message['data']['image/png']
elif 'text/html' in message['data']:
message_type = 'text'
out = message["data"]["image/png"]
elif "text/html" in message["data"]:
message_type = "text"
# output some html text (like a pandas dataframe)
out = message['data']['text/html']
out = message["data"]["text/html"]
else:
message_type = 'text'
message_type = "text"
# output data as str (for example if code="a=10\na")
out = message['data']['text/plain']
elif 'name' in message and message['name'] == "stdout":
message_type = 'text'
out = message["data"]["text/plain"]
elif "name" in message and message["name"] == "stdout":
message_type = "text"
# output a print (print("Hello World"))
out = message['text']
elif 'traceback' in message:
message_type = 'error'
out = message["text"]
elif "traceback" in message:
message_type = "error"
# output an error
out = '\n'.join(message['traceback'])
out = "\n".join(message["traceback"])
else:
message_type = 'text'
out = ''
message_type = "text"
out = ""
return out, message_type

def run_block(self, block, code: str):
Expand All @@ -73,7 +72,7 @@ def run_block(self, block, code: str):
block.source_editor.threadpool.start(worker)

def run_queue(self):
""" Runs the next code in the queue """
"""Runs the next code in the queue"""
self.busy = True
if self.execution_queue == []:
self.busy = False
Expand Down Expand Up @@ -114,8 +113,8 @@ def get_message(self) -> Tuple[str, bool]:
"""
done = False
try:
message = self.client.get_iopub_msg(timeout=1000)['content']
if 'execution_state' in message and message['execution_state'] == 'idle':
message = self.client.get_iopub_msg(timeout=1000)["content"]
if "execution_state" in message and message["execution_state"] == "idle":
done = True
except queue.Empty:
message = None
Expand Down
Loading