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
Original file line number Diff line number Diff line change
Expand Up @@ -71,20 +71,20 @@ const open = (model_id: string, application_id?: string, model_setting_data?: an
.getModelParamsForm(model_id, loading)
.then(( ok: any ) => {
model_form_field.value = ok.data
const res = ok.data
const resp = ok.data
.map((item: any) => ({
[item.field]: item.show_default_value !== false ? item.default_value : undefined,
}))
.reduce((x: any, y: any) => ({ ...x, ...y }), {})

if (model_setting_data) {
Object.keys(model_setting_data).forEach((key) => {
if (!(key in res)) {
if (!(key in resp)) {
delete model_setting_data[key]
}
})
}
model_setting_data = { ...res, ...model_setting_data }
model_setting_data = { ...resp, ...model_setting_data }
// 渲染动态表单
dynamicsFormRef.value?.render(model_form_field.value, model_setting_data)
})
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code is mostly well-structured, but here are a few improvements to address some potential issues:

  1. Variable Naming Consistency: Ensure consistent naming conventions for variables throughout the function. For example, const res in one place should be renamed to match elsewhere.

  2. Type Annotations: While TypeScript does not change variable type assignments based on value, adding explicit types where appropriate can help catch errors early.

  3. Code Readability: Consider breaking down long lines of code into multiple lines with proper indentation for better readability.

  4. Functionality Verification: Ensure that open method correctly processes the response and updates the UI accordingly.

Here's an improved version of the code incorporating these suggestions:

@@ -71,20 +71,28 @@
     .getModelParamsForm(model_id, loading)
     .then((ok: any) => {
       model_form_field.value = ok.data;
      
       const formattedData = ok.data.map(item =>
         ({
           [item.field]: item.show_default_value !== false ? item.default_value : undefined,
         })
       ).reduce((prev, curr) => ({ ...prev, ...curr }), {});

       if (model_setting_data) {
         Object.keys(model_setting_data).forEach(key => {
           if (!(key in formattedData)) {
             delete model_setting_data[key];
           }
         });
       }

       let updatedModelSettingData = { ...formattedData, ...model_setting_data };

       // Render dynamic form
       dynamicsFormRef.value?.render(model_form_field.value, updatedModelSettingData);
     });

Detailed Changes Made:

  1. Renaming Variables:

    • Change res to formattedData consistently.
  2. Added Comment Breaks to enhance readability.

These changes make the code more readable and maintainable while keeping it functional.

Expand Down
39 changes: 38 additions & 1 deletion ui/src/workflow/nodes/speech-to-text-node/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@
}}<span class="color-danger">*</span></span
>
</div>
<el-button
type="primary"
link
@click="openSTTParamSettingDialog"
:disabled="!form_data.stt_model_id"
class="mr-4"
>
<AppIcon iconName="app-setting"></AppIcon>
</el-button>
</div>
</template>
<ModelSelect
Expand Down Expand Up @@ -91,6 +100,7 @@
</el-form-item>
</el-form>
</el-card>
<STTModeParamSettingDialog ref="STTModeParamSettingDialogRef" @refresh="refreshSTTForm" />
</NodeContainer>
</template>

Expand All @@ -100,12 +110,17 @@ import { computed, onMounted, ref, inject } from 'vue'
import { groupBy, set } from 'lodash'
import NodeCascader from '@/workflow/common/NodeCascader.vue'
import type { FormInstance } from 'element-plus'
import { MsgSuccess } from '@/utils/message'
import { t } from '@/locales'
import { useRoute } from 'vue-router'
import { loadSharedApi } from '@/utils/dynamics-api/shared-api'
import STTModeParamSettingDialog from '@/views/application/component/STTModelParamSettingDialog.vue'
const getApplicationDetail = inject('getApplicationDetail') as any
const route = useRoute()

const {} = route as any
const {
params: { id },
} = route as any

const apiType = computed(() => {
if (route.path.includes('resource-management')) {
Expand All @@ -117,6 +132,8 @@ const apiType = computed(() => {

const props = defineProps<{ nodeModel: any }>()
const modelOptions = ref<any>(null)
const STTModeParamSettingDialogRef = ref<InstanceType<typeof STTModeParamSettingDialog>>()


const aiChatNodeFormRef = ref<FormInstance>()
const nodeCascaderRef = ref()
Expand All @@ -143,6 +160,7 @@ const form = {
stt_model_id: '',
is_result: true,
audio_list: [],
model_params_setting: {},
}

const form_data = computed({
Expand All @@ -159,6 +177,25 @@ const form_data = computed({
},
})


const openSTTParamSettingDialog = () => {
const model_id = form_data.value.stt_model_id
if (!model_id) {
MsgSuccess(t('views.application.form.voiceInput.requiredMessage'))
return
}
STTModeParamSettingDialogRef.value?.open(
model_id,
id,
form_data.value.model_params_setting,
)
}

const refreshSTTForm = (data: any) => {
form_data.value.model_params_setting = data
}


const application = getApplicationDetail()
function getSelectModel() {
const obj =
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code appears to be mostly syntactically correct, but it contains several areas that could benefit from improvements. Here are some suggestions:

  1. Unused Imports:

    • MsgSuccess and t from '@/utils/message', along with '@/locales' should only be imported if used within their respective modules.
  2. Unnecessary Variable Declaration:

    • The line {} seems unnecessary and can likely be removed.
  3. Duplicate Route Parameter Usage:

    • There's a duplicate usage of route parameters in the comment: ${}) as any inside the onMounted hook. It might be better to use the new variable id directly unless there's a specific reason for this duplication.
  4. Function Scope:

    • The function getSelectModel is defined after its usage. While not technically incorrect, it would generally be cleaner to place it at the beginning of functions where variables are declared before being used.
  5. Code Readability and Structure:

    • Ensure proper indentation and spacing for readability. Adjust the line lengths to fit comfortably in an editor without wrapping them excessively.

Here is a revised version keeping these points in mind:

@@ -28,6 +28,15 @@
                   }}<span class="color-danger">*</span></span
                 >
               </div>
+              <el-button
+                type="primary"
+                link
+                @click="openSTTParamSettingDialog"
+                :disabled="!form_data.stt_model_id"
+                class="mr-4"
+              >
+                <AppIcon iconName="app-setting"></AppIcon>
+              </el-button>
             </div>
           </template>
           <ModelSelect
@@ -91,6 +100,7 @@
         </el-form-item>
       </el-form>
     </el-card>
+    <STTModeParamSettingDialog ref="STTModeParamSettingDialogRef" @refresh="refreshSTTForm" />
   </NodeContainer>
 </template>

<script lang="ts">
import {
  nextTick,
  watchEffect,
  defineComponent,
  PropType,
  reactive,
} from "vue";
import { cloneDeep } from 'lodash';
// ... other imports
import ModelSelect from './components/ModelSelect.vue';

export default defineComponent({
  components: {
    // Components
  },
  props: {
    nodeModel: Object as PropType<Node>,
  },
 setup(props) {
    const apiType = computed(() => {
      // ...
    });

    const route = useRouter();
    const id = computed((): string => route.params.id);

    // Refs
    const aiChatNodeFormRef = ref<FormElement>();
    const nodeCascaderRef = ref();
    const modelOptions = ref([]);
    
    // Reactive state
    const form = reactive({
      stt_model_id: "",
      is_result: true,
      audio_list: [],
      model_params_setting: {},
    });
    const form_data = computed(() => ({
      // Compute properties
    }));

    // Methods

    const openSTTParamSettingDialog = () => {
      // ...
    };

    const refreshSTTTForm = (data: any) => {
      // ...
    };

    // Fetching and setting initial data
    async function fetchData() {
      try {
        applicationInfo.data.data.config.is_voice_input_enabled &&
          loadSharedApi(apiType.value).listModels().then((res) => {
            console.log(res);
            modelOptions.value = res.models;
          });

        await nextTick(async () => {
          loadSharedApi(apiType.value).getModel(id.value).then(response => {
            let tmpData = response;

            if (
              props.nodeModel.settings?.voice_settings &&
              props.nodeModel.settings.voice_settings.stt_mode_param_setting && 
              !response.model_params_setting && 
              !!props.nodeModel.settings.voice_settings.stt_mode_param_setting.id
            ) {
              tmpData.model_params_setting =
                props.nodeModel.settings.voice_settings.stt_mode_param_setting;
              
              set(form, ["audio_list", "0"], "");
            }

            // Apply changes to the main form state using lodash deep copy
            applyChanges(tmpData);
          }, error => {
            console.error(`There was an error while trying to fetch models ${error}`);
          });
        }) 
      } catch(error) { console.error("Error fetching application configuration:", error); }
    }

    watchEffect(() => {
      if (!application.config.is_voice_input_enabled || props.nodeModel.disabled) return;

      fetchData();
    });

    const applyChanges = (tmpData: Config) => {
      // ...
    }

    return {
      applyChanges,
      aiChatNodeFormRef,
      getSelectModel,
      fetchModels,
      nodeCascaderRef,
      refreshSTTForm,
    };
  },
});
</script>

These adjustments improve code organization and consistency, ensuring readability and maintainability.

Expand Down
Loading