This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/texera.git

commit aca23086aea781a66ce0fbd0bf730deab22bd774
Author: Xinyuan Lin <[email protected]>
AuthorDate: Thu Nov 5 00:45:32 2026 +0000

    refactor(frontend): deduplicate HuggingFace media components (#9267)
    
    ### What changes were proposed in this PR?
    Deduplicate the shared Formly media upload state, control
    synchronization, and file lifecycle between
    `HuggingFaceAudioUploadComponent` and `HuggingFaceImageUploadComponent`
    into a shared abstract base class `HuggingFaceMediaUploadBase`, and
    factor the repeated media validator and task-hiding expressions in
    `applyHuggingFaceFieldBindings`.
    
    ### Any related issues, documentation, discussions?
    Closes #9266.
    
    ### How was this PR tested?
    Tested with Vitest in `frontend`:
    ```bash
    node frontend/.yarn/releases/yarn-4.14.1.cjs --cwd frontend run ng test 
--watch=false --include 
"src/app/workspace/util/hugging-face-field-bindings.spec.ts" --include 
"src/app/workspace/component/hugging-face-audio-upload/hugging-face-audio-upload.component.spec.ts"
 --include 
"src/app/workspace/component/hugging-face-image-upload/hugging-face-image-upload.component.spec.ts"
 --include 
"src/app/workspace/component/hugging-face/hugging-face.component.spec.ts"
    ```
    185 tests pass.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    Generated-by: Antigravity (gemini-2.5-pro)
---
 .../hugging-face-audio-upload.component.spec.ts    |  26 ++--
 .../hugging-face-audio-upload.component.ts         |  50 +-----
 .../hugging-face-image-upload.component.spec.ts    |  38 +++--
 .../hugging-face-image-upload.component.ts         |  47 +-----
 .../component/hugging-face-media-upload.base.ts    |  75 +++++++++
 .../workspace/util/hugging-face-field-bindings.ts  | 171 ++++++++-------------
 6 files changed, 194 insertions(+), 213 deletions(-)

diff --git 
a/frontend/src/app/workspace/component/hugging-face-audio-upload/hugging-face-audio-upload.component.spec.ts
 
b/frontend/src/app/workspace/component/hugging-face-audio-upload/hugging-face-audio-upload.component.spec.ts
index c8598b1224..41f1fec5af 100644
--- 
a/frontend/src/app/workspace/component/hugging-face-audio-upload/hugging-face-audio-upload.component.spec.ts
+++ 
b/frontend/src/app/workspace/component/hugging-face-audio-upload/hugging-face-audio-upload.component.spec.ts
@@ -109,14 +109,14 @@ describe("HuggingFaceAudioUploadComponent", () => {
 
   describe("derived view state", () => {
     it("reports no audio when formControl is empty", () => {
-      expect(component.hasAudio).toBe(false);
+      expect(component.hasMedia).toBe(false);
       expect(component.previewSrc).toBe("");
       expect(component.displayFileName).toBe("");
     });
 
     it("reports audio when formControl holds a data:audio URL", () => {
       component.formControl.setValue("data:audio/wav;base64,AAA");
-      expect(component.hasAudio).toBe(true);
+      expect(component.hasMedia).toBe(true);
       expect(component.previewSrc).toBe("data:audio/wav;base64,AAA");
       expect(component.displayFileName).toBe("Selected audio");
     });
@@ -129,18 +129,18 @@ describe("HuggingFaceAudioUploadComponent", () => {
 
     it("returns false for a leftover server path (legacy saved value)", () => {
       component.formControl.setValue("/uploads/clip.wav");
-      expect(component.hasAudio).toBe(false);
+      expect(component.hasMedia).toBe(false);
       expect(component.previewSrc).toBe("");
     });
 
     it("returns false for a non-audio data URL", () => {
       component.formControl.setValue("data:image/png;base64,AAA");
-      expect(component.hasAudio).toBe(false);
+      expect(component.hasMedia).toBe(false);
     });
 
     it("returns false for a null value", () => {
       component.formControl.setValue(null);
-      expect(component.hasAudio).toBe(false);
+      expect(component.hasMedia).toBe(false);
     });
   });
 
@@ -160,7 +160,7 @@ describe("HuggingFaceAudioUploadComponent", () => {
       const input = makeFileInput(file);
       await component.onFileSelected({ target: input } as unknown as Event);
       expect(component.errorMessage).toBe("Choose an audio file.");
-      expect(component.hasAudio).toBe(false);
+      expect(component.hasMedia).toBe(false);
       expect(input.value).toBe("");
     });
 
@@ -194,7 +194,7 @@ describe("HuggingFaceAudioUploadComponent", () => {
 
         expect(component.formControl.value).toBe("data:audio/wav;base64,AAAA");
         expect(component.fileName).toBe("clip.wav");
-        expect(component.hasAudio).toBe(true);
+        expect(component.hasMedia).toBe(true);
         expect(component.formControl.dirty).toBe(true);
         expect(component.formControl.touched).toBe(true);
         expect((component.model as 
any).audioInput).toBe("data:audio/wav;base64,AAAA");
@@ -224,7 +224,7 @@ describe("HuggingFaceAudioUploadComponent", () => {
         const input = makeFileInput(file);
         await component.onFileSelected({ target: input } as unknown as Event);
         expect(component.errorMessage).toBe("Could not read this audio file.");
-        expect(component.hasAudio).toBe(false);
+        expect(component.hasMedia).toBe(false);
       } finally {
         teardown();
       }
@@ -249,7 +249,7 @@ describe("HuggingFaceAudioUploadComponent", () => {
         const input = makeFileInput(file);
         await component.onFileSelected({ target: input } as unknown as Event);
         expect(component.errorMessage).toBe("Could not read this audio file.");
-        expect(component.hasAudio).toBe(false);
+        expect(component.hasMedia).toBe(false);
       } finally {
         teardown();
       }
@@ -288,7 +288,7 @@ describe("HuggingFaceAudioUploadComponent", () => {
       } finally {
         teardown();
       }
-      expect(component.hasAudio).toBe(true);
+      expect(component.hasMedia).toBe(true);
     }
 
     it("drops a previously accepted clip when a re-selection is not audio", 
async () => {
@@ -301,7 +301,7 @@ describe("HuggingFaceAudioUploadComponent", () => {
       expect(component.errorMessage).toBe("Choose an audio file.");
       expect(component.formControl.value).toBe("");
       expect(component.fileName).toBe("");
-      expect(component.hasAudio).toBe(false);
+      expect(component.hasMedia).toBe(false);
       expect(input.value).toBe("");
       expect((component.field as any).model.audioInput).toBe("");
     });
@@ -315,7 +315,7 @@ describe("HuggingFaceAudioUploadComponent", () => {
       expect(component.errorMessage).toBe("Audio file is too large (max 25 
MB).");
       expect(component.formControl.value).toBe("");
       expect(component.fileName).toBe("");
-      expect(component.hasAudio).toBe(false);
+      expect(component.hasMedia).toBe(false);
       expect(input.value).toBe("");
     });
 
@@ -329,7 +329,7 @@ describe("HuggingFaceAudioUploadComponent", () => {
         expect(component.errorMessage).toBe("Could not read this audio file.");
         expect(component.formControl.value).toBe("");
         expect(component.fileName).toBe("");
-        expect(component.hasAudio).toBe(false);
+        expect(component.hasMedia).toBe(false);
         expect(input.value).toBe("");
       } finally {
         teardown();
diff --git 
a/frontend/src/app/workspace/component/hugging-face-audio-upload/hugging-face-audio-upload.component.ts
 
b/frontend/src/app/workspace/component/hugging-face-audio-upload/hugging-face-audio-upload.component.ts
index 6eb728dcdb..a59a7fd1fc 100644
--- 
a/frontend/src/app/workspace/component/hugging-face-audio-upload/hugging-face-audio-upload.component.ts
+++ 
b/frontend/src/app/workspace/component/hugging-face-audio-upload/hugging-face-audio-upload.component.ts
@@ -19,8 +19,8 @@
 
 import { Component } from "@angular/core";
 import { CommonModule } from "@angular/common";
-import { FieldType, FieldTypeConfig } from "@ngx-formly/core";
 import { NzButtonModule } from "ng-zorro-antd/button";
+import { HuggingFaceMediaUploadBase } from "../hugging-face-media-upload.base";
 
 // Cap the raw audio size before it is inlined as a base64 data URL into the
 // workflow JSON. Mirrors the image-upload component's data-URL approach so the
@@ -35,24 +35,9 @@ const MAX_AUDIO_BYTES = 25 * 1024 * 1024;
   styleUrls: ["./hugging-face-audio-upload.component.scss"],
   imports: [CommonModule, NzButtonModule],
 })
-export class HuggingFaceAudioUploadComponent extends 
FieldType<FieldTypeConfig> {
-  fileName = "";
-  errorMessage = "";
-
-  get hasAudio(): boolean {
-    const value = this.formControl.value;
-    return typeof value === "string" && value.startsWith("data:audio/");
-  }
-
-  get previewSrc(): string {
-    return this.hasAudio ? this.formControl.value : "";
-  }
-
-  get displayFileName(): string {
-    if (this.fileName) return this.fileName;
-    if (this.hasAudio) return "Selected audio";
-    return "";
-  }
+export class HuggingFaceAudioUploadComponent extends 
HuggingFaceMediaUploadBase {
+  protected readonly dataUrlPrefix = "data:audio/";
+  protected readonly mediaFallbackLabel = "Selected audio";
 
   async onFileSelected(event: Event): Promise<void> {
     this.errorMessage = "";
@@ -78,14 +63,7 @@ export class HuggingFaceAudioUploadComponent extends 
FieldType<FieldTypeConfig>
       if (!dataUrl.startsWith("data:audio/")) {
         throw new Error("Not an audio data URL");
       }
-      this.fileName = file.name;
-      this.formControl.setValue(dataUrl);
-      if (typeof this.key === "string" && this.model) {
-        this.model[this.key] = dataUrl;
-      }
-      this.formControl.markAsDirty();
-      this.formControl.markAsTouched();
-      this.formControl.updateValueAndValidity();
+      this.setMediaValue(dataUrl, file.name);
     } catch {
       this.errorMessage = "Could not read this audio file.";
       this.resetSelection(input);
@@ -93,23 +71,7 @@ export class HuggingFaceAudioUploadComponent extends 
FieldType<FieldTypeConfig>
   }
 
   clearAudio(input: HTMLInputElement): void {
-    this.errorMessage = "";
-    this.resetSelection(input);
-  }
-
-  // A rejected selection must not leave the previously accepted clip behind:
-  // the form value drives both the <audio> preview and what the operator runs,
-  // so keeping it would show an error while silently running the old audio.
-  private resetSelection(input: HTMLInputElement): void {
-    this.fileName = "";
-    input.value = "";
-    this.formControl.setValue("");
-    if (typeof this.key === "string" && this.model) {
-      this.model[this.key] = "";
-    }
-    this.formControl.markAsDirty();
-    this.formControl.markAsTouched();
-    this.formControl.updateValueAndValidity();
+    this.clearMedia(input);
   }
 
   private readAsDataUrl(file: File): Promise<string> {
diff --git 
a/frontend/src/app/workspace/component/hugging-face-image-upload/hugging-face-image-upload.component.spec.ts
 
b/frontend/src/app/workspace/component/hugging-face-image-upload/hugging-face-image-upload.component.spec.ts
index 4a85b7cc44..fa94625d0a 100644
--- 
a/frontend/src/app/workspace/component/hugging-face-image-upload/hugging-face-image-upload.component.spec.ts
+++ 
b/frontend/src/app/workspace/component/hugging-face-image-upload/hugging-face-image-upload.component.spec.ts
@@ -50,14 +50,14 @@ describe("HuggingFaceImageUploadComponent", () => {
 
   describe("derived view state", () => {
     it("reports no image when formControl is empty", () => {
-      expect(component.hasImage).toBe(false);
+      expect(component.hasMedia).toBe(false);
       expect(component.previewSrc).toBe("");
       expect(component.displayFileName).toBe("");
     });
 
     it("reports an image when formControl holds a data URL", () => {
       component.formControl.setValue("data:image/jpeg;base64,AAA");
-      expect(component.hasImage).toBe(true);
+      expect(component.hasMedia).toBe(true);
       expect(component.previewSrc).toBe("data:image/jpeg;base64,AAA");
       expect(component.displayFileName).toBe("Uploaded image");
     });
@@ -95,7 +95,19 @@ describe("HuggingFaceImageUploadComponent", () => {
       const input = makeFileInput(txtFile);
       await component.onFileSelected({ target: input } as unknown as Event);
       expect(component.errorMessage).toBe("Choose an image file.");
-      expect(component.hasImage).toBe(false);
+      expect(component.hasMedia).toBe(false);
+    });
+
+    it("clears a previously selected image when a non-image file is rejected", 
async () => {
+      component.formControl.setValue("data:image/jpeg;base64,AAA");
+      component.fileName = "old.jpg";
+      const txtFile = new File(["hi"], "note.txt", { type: "text/plain" });
+      const input = makeFileInput(txtFile);
+      await component.onFileSelected({ target: input } as unknown as Event);
+      expect(component.errorMessage).toBe("Choose an image file.");
+      expect(component.formControl.value).toBe("");
+      expect(component.fileName).toBe("");
+      expect(component.hasMedia).toBe(false);
     });
 
     it("reports an error when image compression fails", async () => {
@@ -116,7 +128,7 @@ describe("HuggingFaceImageUploadComponent", () => {
         const input = makeFileInput(imgFile);
         await component.onFileSelected({ target: input } as unknown as Event);
         expect(component.errorMessage).toBe("Could not prepare this image. Try 
a smaller image file.");
-        expect(component.hasImage).toBe(false);
+        expect(component.hasMedia).toBe(false);
       } finally {
         (globalThis as any).FileReader = realFileReader;
       }
@@ -145,25 +157,25 @@ describe("HuggingFaceImageUploadComponent", () => {
     });
   });
 
-  describe("hasImage edge cases", () => {
+  describe("hasMedia edge cases", () => {
     it("returns false for a server path string", () => {
       component.formControl.setValue("/uploads/photo.png");
-      expect(component.hasImage).toBe(false);
+      expect(component.hasMedia).toBe(false);
     });
 
     it("returns false for null value", () => {
       component.formControl.setValue(null);
-      expect(component.hasImage).toBe(false);
+      expect(component.hasMedia).toBe(false);
     });
 
     it("returns false for non-image data URL", () => {
       component.formControl.setValue("data:audio/wav;base64,AAA");
-      expect(component.hasImage).toBe(false);
+      expect(component.hasMedia).toBe(false);
     });
 
     it("returns true for data:image/png URL", () => {
       component.formControl.setValue("data:image/png;base64,AAA");
-      expect(component.hasImage).toBe(true);
+      expect(component.hasMedia).toBe(true);
     });
   });
 
@@ -220,7 +232,7 @@ describe("HuggingFaceImageUploadComponent", () => {
 
     it("renders no preview at all without an image, so the label is never 
empty", () => {
       // The preview only renders while previewSrc is non-empty, which happens 
exactly
-      // when hasImage is true — and displayFileName is never empty in that 
case.
+      // when hasMedia is true — and displayFileName is never empty in that 
case.
       component.formControl.setValue("");
       fixture.detectChanges();
 
@@ -347,7 +359,7 @@ describe("HuggingFaceImageUploadComponent", () => {
 
         expect(component.fileName).toBe("sunset.jpg");
         
expect(component.formControl.value).toBe("data:image/jpeg;base64,SMALL");
-        expect(component.hasImage).toBe(true);
+        expect(component.hasMedia).toBe(true);
         expect(component.formControl.dirty).toBe(true);
         expect(component.formControl.touched).toBe(true);
         expect((component.model as 
any).image).toBe("data:image/jpeg;base64,SMALL");
@@ -381,7 +393,7 @@ describe("HuggingFaceImageUploadComponent", () => {
         const input = makeFileInput(imgFile);
         await component.onFileSelected({ target: input } as unknown as Event);
         expect(component.errorMessage).toBe("Could not prepare this image. Try 
a smaller image file.");
-        expect(component.hasImage).toBe(false);
+        expect(component.hasMedia).toBe(false);
       } finally {
         teardown();
       }
@@ -406,7 +418,7 @@ describe("HuggingFaceImageUploadComponent", () => {
         const input = makeFileInput(imgFile);
         await component.onFileSelected({ target: input } as unknown as Event);
         expect(component.errorMessage).toBe("Could not prepare this image. Try 
a smaller image file.");
-        expect(component.hasImage).toBe(false);
+        expect(component.hasMedia).toBe(false);
       } finally {
         teardown();
       }
diff --git 
a/frontend/src/app/workspace/component/hugging-face-image-upload/hugging-face-image-upload.component.ts
 
b/frontend/src/app/workspace/component/hugging-face-image-upload/hugging-face-image-upload.component.ts
index 9556a72670..ce59ecb9cf 100644
--- 
a/frontend/src/app/workspace/component/hugging-face-image-upload/hugging-face-image-upload.component.ts
+++ 
b/frontend/src/app/workspace/component/hugging-face-image-upload/hugging-face-image-upload.component.ts
@@ -19,8 +19,8 @@
 
 import { Component } from "@angular/core";
 import { CommonModule } from "@angular/common";
-import { FieldType, FieldTypeConfig } from "@ngx-formly/core";
 import { NzButtonModule } from "ng-zorro-antd/button";
+import { HuggingFaceMediaUploadBase } from "../hugging-face-media-upload.base";
 
 // Keep in sync with HuggingFaceCodegenBase._compress_image_bytes(max_bytes) 
on the backend:
 // the uploaded data URL must stay within the size the inference helpers 
expect.
@@ -36,24 +36,9 @@ const MIN_JPEG_QUALITY = 0.35;
   styleUrls: ["./hugging-face-image-upload.component.scss"],
   imports: [CommonModule, NzButtonModule],
 })
-export class HuggingFaceImageUploadComponent extends 
FieldType<FieldTypeConfig> {
-  fileName = "";
-  errorMessage = "";
-
-  get hasImage(): boolean {
-    const value = this.formControl.value;
-    return typeof value === "string" && value.startsWith("data:image/");
-  }
-
-  get previewSrc(): string {
-    return this.hasImage ? this.formControl.value : "";
-  }
-
-  get displayFileName(): string {
-    if (this.fileName) return this.fileName;
-    if (this.hasImage) return "Uploaded image";
-    return "";
-  }
+export class HuggingFaceImageUploadComponent extends 
HuggingFaceMediaUploadBase {
+  protected readonly dataUrlPrefix = "data:image/";
+  protected readonly mediaFallbackLabel = "Uploaded image";
 
   async onFileSelected(event: Event): Promise<void> {
     this.errorMessage = "";
@@ -65,23 +50,16 @@ export class HuggingFaceImageUploadComponent extends 
FieldType<FieldTypeConfig>
     }
     if (!file.type.startsWith("image/")) {
       this.errorMessage = "Choose an image file.";
-      input.value = "";
+      this.resetSelection(input);
       return;
     }
 
     try {
       const dataUrl = await this.compressImage(file);
-      this.fileName = file.name;
-      this.formControl.setValue(dataUrl);
-      if (typeof this.key === "string" && this.model) {
-        this.model[this.key] = dataUrl;
-      }
-      this.formControl.markAsDirty();
-      this.formControl.markAsTouched();
-      this.formControl.updateValueAndValidity();
+      this.setMediaValue(dataUrl, file.name);
     } catch {
       this.errorMessage = "Could not prepare this image. Try a smaller image 
file.";
-      input.value = "";
+      this.resetSelection(input);
     }
   }
 
@@ -148,15 +126,6 @@ export class HuggingFaceImageUploadComponent extends 
FieldType<FieldTypeConfig>
   }
 
   clearImage(input: HTMLInputElement): void {
-    this.fileName = "";
-    this.errorMessage = "";
-    input.value = "";
-    this.formControl.setValue("");
-    if (typeof this.key === "string" && this.model) {
-      this.model[this.key] = "";
-    }
-    this.formControl.markAsDirty();
-    this.formControl.markAsTouched();
-    this.formControl.updateValueAndValidity();
+    this.clearMedia(input);
   }
 }
diff --git 
a/frontend/src/app/workspace/component/hugging-face-media-upload.base.ts 
b/frontend/src/app/workspace/component/hugging-face-media-upload.base.ts
new file mode 100644
index 0000000000..56be0a998a
--- /dev/null
+++ b/frontend/src/app/workspace/component/hugging-face-media-upload.base.ts
@@ -0,0 +1,75 @@
+/**
+ * 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 { Directive } from "@angular/core";
+import { FieldType, FieldTypeConfig } from "@ngx-formly/core";
+
+@Directive()
+export abstract class HuggingFaceMediaUploadBase extends 
FieldType<FieldTypeConfig> {
+  fileName = "";
+  errorMessage = "";
+
+  /** Data URL prefix the stored value must start with, e.g. `data:image/`. */
+  protected abstract readonly dataUrlPrefix: string;
+  /** Label shown when a value is present but no file name is known. */
+  protected abstract readonly mediaFallbackLabel: string;
+
+  get hasMedia(): boolean {
+    const value = this.formControl.value;
+    return typeof value === "string" && value.startsWith(this.dataUrlPrefix);
+  }
+
+  get previewSrc(): string {
+    return this.hasMedia ? this.formControl.value : "";
+  }
+
+  get displayFileName(): string {
+    if (this.fileName) return this.fileName;
+    if (this.hasMedia) return this.mediaFallbackLabel;
+    return "";
+  }
+
+  protected setMediaValue(dataUrl: string, fileName: string): void {
+    this.fileName = fileName;
+    this.formControl.setValue(dataUrl);
+    if (typeof this.key === "string" && this.model) {
+      this.model[this.key] = dataUrl;
+    }
+    this.formControl.markAsDirty();
+    this.formControl.markAsTouched();
+    this.formControl.updateValueAndValidity();
+  }
+
+  protected resetSelection(input: HTMLInputElement): void {
+    this.fileName = "";
+    input.value = "";
+    this.formControl.setValue("");
+    if (typeof this.key === "string" && this.model) {
+      this.model[this.key] = "";
+    }
+    this.formControl.markAsDirty();
+    this.formControl.markAsTouched();
+    this.formControl.updateValueAndValidity();
+  }
+
+  clearMedia(input: HTMLInputElement): void {
+    this.errorMessage = "";
+    this.resetSelection(input);
+  }
+}
diff --git a/frontend/src/app/workspace/util/hugging-face-field-bindings.ts 
b/frontend/src/app/workspace/util/hugging-face-field-bindings.ts
index a3f31e5629..d9724a912d 100644
--- a/frontend/src/app/workspace/util/hugging-face-field-bindings.ts
+++ b/frontend/src/app/workspace/util/hugging-face-field-bindings.ts
@@ -61,6 +61,50 @@ const getSelectedTask = (field: FormlyFieldConfig): string | 
undefined => {
   return undefined;
 };
 
+function hideUnlessTask(mappedField: FormlyFieldConfig, predicate: (task: 
string | undefined) => boolean): void {
+  mappedField.expressions = {
+    ...mappedField.expressions,
+    hide: (field: FormlyFieldConfig) => !predicate(getSelectedTask(field)),
+  };
+}
+
+function hideUnlessTaskIn(mappedField: FormlyFieldConfig, tasks: string[]): 
void {
+  hideUnlessTask(mappedField, task => task !== undefined && 
tasks.includes(task));
+}
+
+function bindMediaInput(
+  mappedField: FormlyFieldConfig,
+  tasks: string[],
+  validatorName: string,
+  columnKey: string,
+  inputKey: string,
+  message: string
+): void {
+  hideUnlessTaskIn(mappedField, tasks);
+  mappedField.validators = {
+    ...mappedField.validators,
+    [validatorName]: {
+      expression: (_control: AbstractControl, field: FormlyFieldConfig) => {
+        const t = getSelectedTask(field);
+        if (t === undefined || !tasks.includes(t)) {
+          return true;
+        }
+        const inputCol = field.model?.[columnKey];
+        if (typeof inputCol === "string" && inputCol.trim().length > 0) {
+          return true;
+        }
+        const value = field.formControl?.value ?? field.model?.[inputKey];
+        return typeof value === "string" && value.trim().length > 0;
+      },
+      message: () => message,
+    },
+  };
+  mappedField.validation = {
+    ...mappedField.validation,
+    show: true,
+  };
+}
+
 /**
  * Applies the HuggingFace operator's task-driven field behaviour to a single 
formly field: the
  * `task` field is hidden, and each input field (image/audio uploads and their 
column pickers, the
@@ -80,94 +124,34 @@ export function applyHuggingFaceFieldBindings(mappedField: 
FormlyFieldConfig): v
   const hfKey = mappedField.key;
   if (hfKey === "imageInput") {
     // type ("huggingface-image-upload") is set by customFormlyFieldType
-    mappedField.expressions = {
-      ...mappedField.expressions,
-      hide: (field: FormlyFieldConfig) => {
-        const t = getSelectedTask(field);
-        return t === undefined || !imageInputTasks.includes(t);
-      },
-    };
-    mappedField.validators = {
-      ...mappedField.validators,
-      requiredImageInput: {
-        expression: (_control: AbstractControl, field: FormlyFieldConfig) => {
-          const t = getSelectedTask(field);
-          if (t === undefined || !imageInputTasks.includes(t)) {
-            return true;
-          }
-          const inputImageCol = field.model?.inputImageColumn;
-          if (typeof inputImageCol === "string" && inputImageCol.trim().length 
> 0) {
-            return true;
-          }
-          const value = field.formControl?.value ?? field.model?.imageInput;
-          return typeof value === "string" && value.trim().length > 0;
-        },
-        message: () => "Upload an image or select an Input Image Column for 
this task.",
-      },
-    };
-    mappedField.validation = {
-      ...mappedField.validation,
-      show: true,
-    };
+    bindMediaInput(
+      mappedField,
+      imageInputTasks,
+      "requiredImageInput",
+      "inputImageColumn",
+      "imageInput",
+      "Upload an image or select an Input Image Column for this task."
+    );
   }
   if (hfKey === "audioInput") {
     // type ("huggingface-audio-upload") is set by customFormlyFieldType
-    mappedField.expressions = {
-      ...mappedField.expressions,
-      hide: (field: FormlyFieldConfig) => {
-        const t = getSelectedTask(field);
-        return t === undefined || !audioInputTasks.includes(t);
-      },
-    };
-    mappedField.validators = {
-      ...mappedField.validators,
-      requiredAudioInput: {
-        expression: (_control: AbstractControl, field: FormlyFieldConfig) => {
-          const t = getSelectedTask(field);
-          if (t === undefined || !audioInputTasks.includes(t)) {
-            return true;
-          }
-          const inputAudioCol = field.model?.inputAudioColumn;
-          if (typeof inputAudioCol === "string" && inputAudioCol.trim().length 
> 0) {
-            return true;
-          }
-          const value = field.formControl?.value ?? field.model?.audioInput;
-          return typeof value === "string" && value.trim().length > 0;
-        },
-        message: () => "Upload audio or select an Input Audio Column for this 
task.",
-      },
-    };
-    mappedField.validation = {
-      ...mappedField.validation,
-      show: true,
-    };
+    bindMediaInput(
+      mappedField,
+      audioInputTasks,
+      "requiredAudioInput",
+      "inputAudioColumn",
+      "audioInput",
+      "Upload audio or select an Input Audio Column for this task."
+    );
   }
   if (hfKey === "inputImageColumn") {
-    mappedField.expressions = {
-      ...mappedField.expressions,
-      hide: (field: FormlyFieldConfig) => {
-        const t = getSelectedTask(field);
-        return t === undefined || !imageInputTasks.includes(t);
-      },
-    };
+    hideUnlessTaskIn(mappedField, imageInputTasks);
   }
   if (hfKey === "inputAudioColumn") {
-    mappedField.expressions = {
-      ...mappedField.expressions,
-      hide: (field: FormlyFieldConfig) => {
-        const t = getSelectedTask(field);
-        return t === undefined || !audioInputTasks.includes(t);
-      },
-    };
+    hideUnlessTaskIn(mappedField, audioInputTasks);
   }
   if (hfKey === "promptColumn") {
-    mappedField.expressions = {
-      ...mappedField.expressions,
-      hide: (field: FormlyFieldConfig) => {
-        const t = getSelectedTask(field);
-        return t !== undefined && (imageOnlyTasks.includes(t) || 
audioInputTasks.includes(t));
-      },
-    };
+    hideUnlessTask(mappedField, t => t === undefined || 
(!imageOnlyTasks.includes(t) && !audioInputTasks.includes(t)));
     mappedField.validators = {
       ...mappedField.validators,
       requiredPromptColumn: {
@@ -188,36 +172,15 @@ export function 
applyHuggingFaceFieldBindings(mappedField: FormlyFieldConfig): v
     };
   }
   if (["systemPrompt", "maxNewTokens", "temperature"].includes(hfKey)) {
-    mappedField.expressions = {
-      ...mappedField.expressions,
-      hide: (field: FormlyFieldConfig) => {
-        const t = getSelectedTask(field);
-        return t !== "text-generation";
-      },
-    };
+    hideUnlessTask(mappedField, t => t === "text-generation");
   }
   if (hfKey === "contextColumn") {
-    mappedField.expressions = {
-      ...mappedField.expressions,
-      hide: (field: FormlyFieldConfig) => getSelectedTask(field) !== 
"question-answering",
-    };
+    hideUnlessTask(mappedField, t => t === "question-answering");
   }
   if (hfKey === "candidateLabels") {
-    mappedField.expressions = {
-      ...mappedField.expressions,
-      hide: (field: FormlyFieldConfig) => {
-        const t = getSelectedTask(field);
-        return t !== "zero-shot-classification" && t !== 
"zero-shot-image-classification";
-      },
-    };
+    hideUnlessTask(mappedField, t => t === "zero-shot-classification" || t === 
"zero-shot-image-classification");
   }
   if (hfKey === "sentencesColumn") {
-    mappedField.expressions = {
-      ...mappedField.expressions,
-      hide: (field: FormlyFieldConfig) => {
-        const t = getSelectedTask(field);
-        return t !== "sentence-similarity" && t !== "text-ranking";
-      },
-    };
+    hideUnlessTask(mappedField, t => t === "sentence-similarity" || t === 
"text-ranking");
   }
 }

Reply via email to