Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -114,14 +114,9 @@ trait StandaloneCodeGenerator {
def producesDataFrame(): Boolean = true

/**
* Definitions this operator's standalone code depends on, emitted once near
* the top of the script rather than inline.
*
* The translator concatenates operator bodies into a single module, so an
* operator needing a helper class has nowhere to put it that another operator
* would not duplicate. Helpers returned here are collected across the whole
* plan and deduplicated by their text, so two sampling operators in one
* workflow yield one copy of the generator they share.
* Definitions this operator's standalone code depends on. Each block must be
* one of [[StandaloneHelpers.moduleHelpers]]: the exported script imports the
* names it calls from the `texera_helpers` module rather than defining them.
*/
def standaloneHelpers(): Seq[String] = Seq.empty

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@

package org.apache.texera.amber.operator

import org.apache.texera.amber.operator.aggregate.AggregateOpDesc
import org.apache.texera.amber.operator.filter.SpecializedFilterOpDesc
import org.apache.texera.amber.operator.source.scan.file.FileScanOpDesc
import org.apache.texera.amber.operator.source.scan.json.JSONLScanSourceOpDesc

/** Python definitions shared by several operators' standalone code, emitted
* once per script via [[StandaloneCodeGenerator.standaloneHelpers]].
*/
Expand Down Expand Up @@ -389,4 +394,45 @@ object StandaloneHelpers {
| name=s.name,
| dtype=object,
| )""".stripMargin

/** Every shared helper block, in the order the `texera_helpers` module holds them.
* A new block returned by some [[StandaloneCodeGenerator.standaloneHelpers]] belongs
* here too: an exported script imports its helpers, and the translator refuses a
* block this list lacks.
*/
def moduleHelpers: Seq[String] =
Seq(
AttributeCasts,
SamplingHelpers.JavaRandom,
AggregateOpDesc.Helpers,
SpecializedFilterOpDesc.FilterPredicates,
FileScanOpDesc.DecodeHelper,
JSONLScanSourceOpDesc.JsonFlatten,
JSONLScanSourceOpDesc.JsonText,
StandaloneCodeGenerator.PythonOperatorInput.definition
)

/** `texera_helpers/__init__.py`: the shared blocks under the one import they share.
* The export also hands it out as `texera_helpers.py`, which a script finds when the
* two sit in one directory.
*/
def helpersModule: String =
("""# Licensed to the Apache Software Foundation (ASF) under one
|# or more contributor license agreements. See the NOTICE file
|# distributed with this work for additional information
|# regarding copyright ownership. The ASF licenses this file
|# to you under the Apache License, Version 2.0 (the
|# "License"); you may not use this file except in compliance
|# with the License. You may obtain a copy of the License at
|#
|# http://www.apache.org/licenses/LICENSE-2.0
|#
|# Unless required by applicable law or agreed to in writing,
|# software distributed under the License is distributed on an
|# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|# KIND, either express or implied. See the License for the
|# specific language governing permissions and limitations
|# under the License.
|
|import pandas as pd""".stripMargin +: moduleHelpers).mkString("", "\n\n\n", "\n")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.texera.amber.operator

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path}

/** The `texera_helpers` module against the helpers the operators declare. */
class StandaloneHelpersSpec extends AnyFlatSpec with Matchers {

private val module: Path = Path
.of(sys.env.getOrElse("TEXERA_HOME", "."))
.resolve("texera-helpers")
.resolve("texera_helpers")
.resolve("__init__.py")

// With TEXERA_HELPERS_WRITE set, the module is rewritten instead of checked.
"texera_helpers/__init__.py" should "hold exactly the helpers the operators declare" in {
if (sys.env.contains("TEXERA_HELPERS_WRITE")) {
Files.write(module, StandaloneHelpers.helpersModule.getBytes(StandardCharsets.UTF_8))
}
withClue(s"$module is stale; rerun this spec with TEXERA_HELPERS_WRITE=1 to rewrite it.\n") {
new String(Files.readAllBytes(module), StandardCharsets.UTF_8) shouldBe
StandaloneHelpers.helpersModule
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export const WORKFLOW_TO_PYTHON_ENDPOINT = "workflow-to-python";
export interface WorkflowToPythonResponse {
type: "success" | "failure";
pythonCode?: string;
/** The `texera_helpers.py` the script imports from, when it imports any. */
helpersModule?: string;
errorMessage?: string;
}

Expand Down
37 changes: 27 additions & 10 deletions frontend/src/app/workspace/component/menu/menu.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -533,16 +533,33 @@
<ng-template #workflowPythonScriptModal>
<div class="workflow-python-modal">
<div class="workflow-python-modal-toolbar">
<button
nz-button
title="copy Python script"
aria-label="copy Python script"
(click)="copyPythonCodeToClipboard()"
[disabled]="!pythonCodeForModal">
<i
nz-icon
nzType="copy"></i>
</button>
<span>
<ng-container *ngIf="pythonHelpersModuleForModal">
Download the zip and run <code>script.py</code> next to the <code>texera_helpers.py</code> it holds.
</ng-container>
</span>
<span class="workflow-python-actions">
<button
nz-button
title="download Python script as zip"
aria-label="download Python script as zip"
(click)="downloadPythonZip()"
[disabled]="!pythonCodeForModal">
<i
nz-icon
nzType="download"></i>
</button>
<button
nz-button
title="copy Python script"
aria-label="copy Python script"
(click)="copyPythonCodeToClipboard()"
[disabled]="!pythonCodeForModal">
<i
nz-icon
nzType="copy"></i>
</button>
</span>
</div>
<pre class="workflow-python-code">{{ pythonCodeForModal }}</pre>
</div>
Expand Down
10 changes: 9 additions & 1 deletion frontend/src/app/workspace/component/menu/menu.component.scss
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,15 @@ texera-coeditor-user-icon {

.workflow-python-modal-toolbar {
display: flex;
justify-content: flex-end;
justify-content: space-between;
align-items: center;
gap: 8px;
}

.workflow-python-actions {
display: flex;
flex: none;
gap: 8px;
}

.workflow-python-code {
Expand Down
65 changes: 65 additions & 0 deletions frontend/src/app/workspace/component/menu/menu.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import { loadPersistedHeatmapView, savePersistedHeatmapView } from "../../servic
import { ComputingUnitState } from "../../../common/type/computing-unit-connection.interface";
import { mockPoint, mockScanPredicate } from "../../service/workflow-graph/model/mock-workflow-data";
import { FileSaverService } from "../../../dashboard/service/user/file/file-saver.service";
import JSZip from "jszip";
import type { ModalOptions } from "ng-zorro-antd/modal";
import type { ComputingUnitSelectionComponent } from "../power-button/computing-unit-selection.component";
import { WorkflowContent } from "../../../common/type/workflow";
Expand Down Expand Up @@ -762,6 +763,18 @@ describe("MenuComponent", () => {
expect(convert).toHaveBeenCalled();
expect(convert.mock.calls[0][0].operators).toHaveLength(1);
});

it("keeps the module the script imports for the download", () => {
vi.spyOn(component["workflowToPythonService"], "convertToPython").mockReturnValue(
of({ type: "success", pythonCode: "print(1)", helpersModule: "def f(): pass" } as any)
);
workflowActionService.addOperator(mockScanPredicate, mockPoint);
validationStream$.next({ errors: {}, workflowEmpty: false });

component.onClickExportAsPython();

expect(component.pythonHelpersModuleForModal).toBe("def f(): pass");
});
});

describe("hasOperators", () => {
Expand Down Expand Up @@ -1094,6 +1107,58 @@ describe("MenuComponent", () => {
vi.unstubAllGlobals();
});

it("copyPythonCodeToClipboard says where the helper module is when the script imports one", async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
vi.stubGlobal("navigator", { clipboard: { writeText } });
const successSpy = vi.spyOn(notificationService, "success").mockImplementation(() => {});
component.pythonCodeForModal = "from texera_helpers import f";
component.pythonHelpersModuleForModal = "def f(): pass";

await component.copyPythonCodeToClipboard();

expect(writeText).toHaveBeenCalledWith("from texera_helpers import f");
expect(successSpy).toHaveBeenCalledWith(
"Python script copied to clipboard. It needs the texera_helpers.py in the zip download next to it."
);
vi.unstubAllGlobals();
});

describe("downloadPythonZip", () => {
const download = async () => {
const saveAs = vi.spyOn(TestBed.inject(FileSaverService), "saveAs").mockImplementation(() => {});
await component.downloadPythonZip();
const [blob, name] = saveAs.mock.calls[0] as [Blob, string];
// jsdom's Blob has no arrayBuffer(), so it is read the way a browser without one would.
const bytes = await new Promise<ArrayBuffer>(resolve => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as ArrayBuffer);
reader.readAsArrayBuffer(blob);
});
return { name, zip: await JSZip.loadAsync(bytes) };
};

it("zips the script with the module it imports, under the workflow name", async () => {
component.currentWorkflowName = "my-workflow";
component.pythonCodeForModal = "from texera_helpers import f";
component.pythonHelpersModuleForModal = "def f(): pass";

const { name, zip } = await download();

expect(name).toBe("my-workflow.zip");
expect(await zip.file("script.py")?.async("string")).toBe("from texera_helpers import f");
expect(await zip.file("texera_helpers.py")?.async("string")).toBe("def f(): pass");
});

it("zips the script alone when it imports nothing", async () => {
component.pythonCodeForModal = "print(1)";
component.pythonHelpersModuleForModal = undefined;

const { zip } = await download();

expect(Object.keys(zip.files)).toEqual(["script.py"]);
});
});

// The export flags are reset when a menu is destroyed -- right on leaving the workspace, wrong on
// a hand-over between a workflow's two views, where the results are kept. A menu mounting on
// retained results asks for them to be recomputed rather than offering a dead button.
Expand Down
28 changes: 27 additions & 1 deletion frontend/src/app/workspace/component/menu/menu.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ import { NzTooltipDirective } from "ng-zorro-antd/tooltip";
import { JupyterPanelService } from "../../service/jupyter-panel/jupyter-panel.service";
import { WorkflowCompilingService } from "../../service/compile-workflow/workflow-compiling.service";
import { CompilationState } from "../../types/workflow-compiling.interface";
import JSZip from "jszip";

/**
* MenuComponent is the top level menu bar that shows
Expand Down Expand Up @@ -756,6 +757,7 @@ export class MenuComponent implements OnInit, OnDestroy {

public isTranslatingToPython = false;
public pythonCodeForModal = "";
public pythonHelpersModuleForModal?: string;

public onClickExportAsPython(): void {
// Exporting the valid part of the graph answers a workflow with a required
Expand All @@ -779,6 +781,7 @@ export class MenuComponent implements OnInit, OnDestroy {
this.isTranslatingToPython = false;
if (response.type === "success") {
this.pythonCodeForModal = response.pythonCode ?? "";
this.pythonHelpersModuleForModal = response.helpersModule;
this.modalService.create({
nzTitle: "Workflow as Python Script",
nzContent: this.workflowPythonScriptModal ?? "",
Expand All @@ -803,12 +806,35 @@ export class MenuComponent implements OnInit, OnDestroy {

try {
await navigator.clipboard.writeText(this.pythonCodeForModal);
this.notificationService.success("Python script copied to clipboard");
// The copied script imports its helpers, so it does not run without the module.
this.notificationService.success(
this.pythonHelpersModuleForModal
? "Python script copied to clipboard. It needs the texera_helpers.py in the zip download next to it."
: "Python script copied to clipboard"
);
} catch (error) {
this.notificationService.error("Failed to copy Python script");
}
}

/**
* The script as a zip, with the `texera_helpers.py` it imports beside it: Python finds a
* module in the script's own directory, so the unzipped folder runs with nothing installed.
* WorkflowToPythonTranslator keeps sources off both file names, since they unzip beside them.
*/
public async downloadPythonZip(): Promise<void> {
if (!this.pythonCodeForModal) {
return;
}
const zip = new JSZip();
zip.file("script.py", this.pythonCodeForModal);
Comment thread
kz930 marked this conversation as resolved.
Resolved
if (this.pythonHelpersModuleForModal) {
zip.file("texera_helpers.py", this.pythonHelpersModuleForModal);
}
const blob = await zip.generateAsync({ type: "blob" });
this.fileSaverService.saveAs(blob, `${this.currentWorkflowName || "workflow"}.zip`);
}

public onClickExportWorkflow(): void {
// The same shape the dashboard download produces (see exportedWorkflow): the content plus the
// landing view as a sibling key, so a file exported here uploads as a form-default workflow too.
Expand Down
36 changes: 36 additions & 0 deletions texera-helpers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->

# texera-helpers

The helpers a Python script exported from a Texera workflow calls, so the
script gives the answers the Texera engine gives.

An exported script imports the helpers it calls from this module. The export
downloads as a zip that holds it as `texera_helpers.py` next to the script, so
the unzipped folder runs with nothing installed.

`texera_helpers/__init__.py` is generated from the helper definitions in
`common/workflow-operator`. Do not edit it by hand. After changing a helper, run

```
TEXERA_HELPERS_WRITE=1 sbt "WorkflowOperator/testOnly org.apache.texera.amber.operator.StandaloneHelpersSpec"
```

Without the variable, the same spec fails when the file is stale.
Loading
Loading