bobbai00 commented on code in PR #9646:
URL: https://github.com/apache/texera/pull/9646#discussion_r4677759264


##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/continuousErrorBands/ContinuousErrorBandsOpDesc.scala:
##########
@@ -137,81 +142,24 @@ class ContinuousErrorBandsOpDesc extends 
PythonVisualizationOpDesc with PlotlySt
          |    @overrides
          |    def process_table(self, table: Table, port: int) -> 
Iterator[Optional[TableLike]]:
          |${emptyTableGuard("input table is empty.")}
-         |        ${createPlotlyFigure()}
+         |${createPlotlyFigure()}
          |        # convert fig to html content
          |${plotlyHtmlYield()}
          |"""
     finalCode.encode
   }
 
   override def generateStandaloneCode(): String = {
-    val traces =
-      bands.asScala
-        .map { bandConf =>
-          // Values typed into the UI become escaped Python literals: the 
runtime
-          // path splices them as decode expressions, which a standalone 
script has
-          // no decoder for, and hand-written quotes break on a value 
containing one.
-          val colorLit = pyStringLiteral(bandConf.color)
-          val colorPart =
-            if (bandConf.color != "")
-              s"""line={'color': $colorLit}, marker={'color': $colorLit}, """
-            else ""
-          val fillColorPart =
-            if (bandConf.fillColor != "")
-              s"""fillcolor=${pyStringLiteral(bandConf.fillColor)}, """
-            else ""
-          val nameLit =
-            pyStringLiteral(if (bandConf.name != "") bandConf.name else 
bandConf.yValue)
-          val xLit = pyStringLiteral(bandConf.xValue)
-
-          s"""fig.add_trace(go.Scatter(
-             |    x=in1df[$xLit],
-             |    y=in1df[${pyStringLiteral(bandConf.yUpper)}],
-             |    mode='lines',
-             |    marker=dict(color="#444"),
-             |    line=dict(width=0),
-             |    showlegend=False,
-             |    name=$nameLit
-             |))
-             |fig.add_trace(go.Scatter(
-             |    x=in1df[$xLit],
-             |    y=in1df[${pyStringLiteral(bandConf.yLower)}],
-             |    mode='lines',
-             |    marker=dict(color="#444"),
-             |    line=dict(width=0),
-             |    fill='tonexty',
-             |    showlegend=False,
-             |    $fillColorPart
-             |    name=$nameLit
-             |))
-             |fig.add_trace(go.Scatter(
-             |    x=in1df[$xLit],
-             |    y=in1df[${pyStringLiteral(bandConf.yValue)}],
-             |    mode='${bandConf.mode.getModeInPlotly}',
-             |    $colorPart
-             |    name=$nameLit
-             |))""".stripMargin
-        }
-        .mkString("\n")
-
-    // Nested under the `else` below, so every trace line needs the extra 
level.
-    val indentedTraces =
-      traces.linesIterator.map(line => if (line.isEmpty) line else s"    
$line").mkString("\n")
-
-    // The empty-input branch mirrors generatePythonCode's `if table.empty`
-    // guard: without it the traces index columns of a frame that has none, and
-    // an empty input silently renders a blank chart instead of saying why.
+    // Values typed into the UI become escaped Python literals: the runtime
+    // path splices them as decode expressions, which a standalone script has
+    // no decoder for, and hand-written quotes break on a value containing one.
+    // The empty-input branch mirrors generatePythonCode's `if table.empty` 
guard.
     s"""${standaloneError("Continuous Error Bands is not available.")}
        |
        |if in1df.empty:
        |${standaloneErrorPage("input table is empty.")}
        |else:
-       |    fig = go.Figure()
-       |$indentedTraces
-       |    fig.update_layout(margin=dict(t=0, b=0, l=0, r=0),
-       |                      xaxis_title=${pyStringLiteral(xLabel)},
-       |                      yaxis_title=${pyStringLiteral(yLabel)},
-       |                      hovermode="x")
+       |${buildFigure("in1df", s => { val lit: String = pyStringLiteral(s); 
pyb"$lit" }, indent = 4).plain}

Review Comment:
   **Advisory:**
   
   This is the only production `.plain` render ([its 
doc](https://github.com/apache/texera/blob/cd3fc253ee0c5ee6fbecf6020c7b849340c8fe8e/common/pybuilder/src/main/scala/org/apache/texera/amber/pybuilder/PythonTemplateBuilder.scala#L116)
 scopes `plain` to debugging or known-safe content). The exported script stays 
quoted only while every user value in `buildFigure` goes through `encode`. A 
new band option spliced the usual pyb way (say `${bandConf.dash}`) would still 
be encoded in the operator, so `PythonCodeRawInvalidTextSpec` stays green, but 
land unquoted here: the NameError 
[SklearnAdvancedBaseDesc](https://github.com/apache/texera/blob/cd3fc253ee0c5ee6fbecf6020c7b849340c8fe8e/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/machineLearning/sklearnAdvanced/base/SklearnAdvancedBaseDesc.scala#L346-L347)
 records for `.plain`. An `s"..."` template with an `EncodableString => String` 
callback, as in [`vectorizerStage`](https://github.com/apache/texera/blob/cd3fc
 
253ee0c5ee6fbecf6020c7b849340c8fe8e/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/sklearn/SklearnModelOpDesc.scala#L141-L146),
 would make a skipped callback show up raw in both scripts, where that spec 
catches it.



##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDesc.scala:
##########
@@ -212,95 +123,110 @@ class NetworkGraphOpDesc extends 
PythonVisualizationOpDesc with PlotlyStandalone
        |    if table.empty:
        |${standaloneErrorPage("Table should not have any empty/null values or 
fields.", indent = 8)}
        |    else:
-       |        sources = table[$sourceLit]
-       |        destinations = table[$destinationLit]
-       |        nodes = list(dict.fromkeys(pd.concat([sources, 
destinations]).tolist()))
-       |        G = nx.Graph()
-       |        for node in nodes:
-       |            G.add_node(node)
-       |        for _, row in table.iterrows():
-       |            G.add_edges_from([(row[$sourceLit], row[$destinationLit])])
-       |        pos = nx.spring_layout(G, k=0.5, iterations=50, seed=0)
-       |        for n, p in pos.items():
-       |            G.nodes[n]["pos"] = p
-       |
-       |        edge_trace = go.Scatter(
-       |            x=[],
-       |            y=[],
-       |            name="Edges",
-       |            line=dict(width=0.5, color="#888"),
-       |            hoverinfo="none",
-       |            mode="lines",
-       |            visible=True
-       |        )
-       |
-       |        for edge in G.edges():
-       |            x0, y0 = G.nodes[edge[0]]["pos"]
-       |            x1, y1 = G.nodes[edge[1]]["pos"]
-       |            edge_trace["x"] += tuple([x0, x1, None])
-       |            edge_trace["y"] += tuple([y0, y1, None])
-       |
-       |        node_trace = go.Scatter(
-       |            x=[],
-       |            y=[],
-       |            name="Nodes",
-       |            text=[],
-       |            mode="markers",
-       |            hoverinfo="text",
-       |            visible=True,
-       |            marker=dict(
-       |                showscale=True,
-       |                colorscale="plasma",
-       |                reversescale=True,
-       |                color=[],
-       |                size=15,
-       |                colorbar=dict(
-       |                    thickness=10,
-       |                    title="Node Connections",
-       |                    xanchor="left",
-       |                    titleside="right"
-       |                ),
-       |                line=dict(width=0)
-       |            )
-       |        )
-       |
-       |        for node in G.nodes():
-       |            x, y = G.nodes[node]["pos"]
-       |            node_trace["x"] += tuple([x])
-       |            node_trace["y"] += tuple([y])
-       |
-       |        for _, adjacencies in enumerate(G.adjacency()):
-       |            node_trace["marker"]["color"] += 
tuple([len(adjacencies[1])])
-       |            node_info = str(adjacencies[0]) + ": " + 
str(len(adjacencies[1])) + " connections."
-       |            node_trace["text"] += tuple([node_info])
-       |
-       |        fig = go.Figure(
-       |            data=[edge_trace, node_trace],
-       |            layout=go.Layout(
-       |                title=$titleLit,
-       |                hovermode="closest",
-       |                showlegend=False,
-       |                margin=dict(b=20, l=5, r=5, t=40),
-       |                annotations=[
-       |                    dict(
-       |                        text="",
-       |                        showarrow=False,
-       |                        xref="paper",
-       |                        yref="paper"
-       |                    )
-       |                ],
-       |                xaxis=dict(showgrid=False, zeroline=False, 
showticklabels=False),
-       |                yaxis=dict(showgrid=False, zeroline=False, 
showticklabels=False)
-       |            )
-       |        )
-       |        fig.update_layout(
-       |            margin=dict(l=0, r=0, t=0, b=0),
-       |            legend=dict(
-       |                itemclick=False,
-       |                itemdoubleclick=False
-       |            )
-       |        )
+       |        source_col = $sourceLit
+       |        dest_col = $destinationLit
+       |        graph_title = $titleLit
+       |${NetworkGraphPython.body(8)}

Review Comment:
   **Must fix:**
   
   Nothing in CI executes the new shared fragments, so the uncommitted 8/8 
parity run is the only evidence this refactor preserves behavior. This 
`generateStandaloneCode` has no test, and neither does ContinuousErrorBands'. 
BulletChart's is reached only through its assert 
([spec](https://github.com/apache/texera/blob/cd3fc253ee0c5ee6fbecf6020c7b849340c8fe8e/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDescSpec.scala#L137)),
 and `PythonCodeRawInvalidTextSpec` only py_compiles operator code, so a 
fragment reading a name its call site never bound (here `dest_col`) still 
passes CI. 
[AGENTS.md](https://github.com/apache/texera/blob/main/AGENTS.md#tests-come-first)
 asks for characterization tests before changing untested code. Please commit 
the parity run as a `NeedsPythonPackages` spec, reusing the exec drivers in 
[GaugeChartOpDescSpec](https://github.com/apache/texera/blob/cd3fc253ee0c5ee6fbecf6020c7b849340c8fe8e/common/w
 
orkflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/gaugeChart/GaugeChartOpDescSpec.scala#L139)
 and 
[TreePlotOpDescSpec](https://github.com/apache/texera/blob/cd3fc253ee0c5ee6fbecf6020c7b849340c8fe8e/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDescSpec.scala#L65).



##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala:
##########
@@ -94,20 +94,24 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
     assert(deltaReference.nonEmpty)
   }
 
-  override def generatePythonCode(): String = {
-    // The reference keeps the 0 the generated code used to fall back to; an 
unset
-    // threshold stays absent as None.
-    val deltaReferenceExpr: PythonLiteral = 
deltaReference.getOrElse(0.0).toString
-    val thresholdExpr: PythonLiteral = 
thresholdValue.map(_.toString).getOrElse("None")
+  // The reference keeps the 0 the generated code used to fall back to; an 
unset
+  // threshold stays absent as None.
+  private def deltaReferenceLiteral: PythonLiteral = 
deltaReference.getOrElse(0.0).toString
+  private def thresholdLiteral: PythonLiteral = 
thresholdValue.map(_.toString).getOrElse("None")
+
+  // The steps whose bounds are both filled in, as a list literal of numbers.
+  private def stepsLiteral: PythonLiteral =
+    Option(steps)
+      .map(_.asScala.toSeq)
+      .getOrElse(Seq.empty)
+      .flatMap(step => step.start.zip(step.end))
+      .map { case (start, end) => s"""{"start": $start, "end": $end}""" }
+      .mkString("[", ", ", "]")
 
-    // The steps whose bounds are both filled in, as a list literal of numbers.
-    val stepsExpr: PythonLiteral =
-      Option(steps)
-        .map(_.asScala.toSeq)
-        .getOrElse(Seq.empty)
-        .flatMap(step => step.start.zip(step.end))
-        .map { case (start, end) => s"""{"start": $start, "end": $end}""" }
-        .mkString("[", ", ", "]")
+  override def generatePythonCode(): String = {
+    val deltaReferenceExpr: PythonLiteral = deltaReferenceLiteral
+    val thresholdExpr: PythonLiteral = thresholdLiteral
+    val stepsExpr: PythonLiteral = stepsLiteral

Review Comment:
   **Advisory:**
   
   These three vals only rename the new defs. `generateStandaloneCode` already 
splices `$deltaReferenceLiteral`, `$thresholdLiteral` and `$stepsLiteral` 
directly (lines 214 and 223-224). `pyb` treats a `PythonLiteral` def as a plain 
literal too, so the operator template can do the same and both paths read alike.



##########
common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDesc.scala:
##########
@@ -360,3 +250,73 @@ class BulletChartOpDesc extends PythonVisualizationOpDesc 
with PlotlyStandaloneC
        |            output.write(render_error(f"General error: 
{str(e)}"))""".stripMargin
   }
 }
+
+private object BulletChartPython {
+  def helperDefs(indent: Int, isMethod: Boolean): String = {
+    val (selfParam, errorsVar, cmp, retStmt) =
+      if (isMethod) ("self, ", "self.step_errors", "≥", "return valid_steps")

Review Comment:
   **Advisory:**
   
   `isMethod` also picks the glyph in the user-facing step error: `≥` in the 
operator and `>=` in the exported script. Keeping that split is right for a 
refactor, but nothing in the flag's name says it changes message text. A 
one-line comment here saying the two messages differ on purpose keeps the next 
editor from treating the flag as purely structural.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to