Edits history of script submission #22271 for ' Summarize (nextcloud)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import createClient, { type Middleware } from "openapi-fetch";
    
    type Nextcloud = {
      baseUrl: string,
      userId: string,
      token: string
    };
    
    const TASK_TYPE_SUMMARY = "core:text2text:summary";
    const POLL_INTERVAL_MS = 1000;
    const DEFAULT_POLL_TIMEOUT_MS = 600_000; // 10 minutes (ensure one cron job finished)
    
    /**
     * Creates a summarization task via the Nextcloud OCS Task Processing API,
     * polls until the task completes, and returns the summarized text.
     */
    export async function main(
      ncResource: Nextcloud,
      text: string,
      model: string | null = null,
      timeout_ms: number = DEFAULT_POLL_TIMEOUT_MS,
      interval_ms: number = POLL_INTERVAL_MS,
    ) {
      if (timeout_ms < 1) {
        timeout_ms = DEFAULT_POLL_TIMEOUT_MS;
      }
      if (interval_ms < 1) {
        interval_ms = POLL_INTERVAL_MS;
      }
      const client = createClient({ baseUrl: ncResource.baseUrl }) as any;
      const authMiddleware: Middleware = {
        async onRequest({ request, options }) {
          request.headers.set("Authorization", `Basic ${btoa(ncResource.userId + ':' + ncResource.token)}`);
          return request;
        },
      };
      client.use(authMiddleware);
    
      const input: Record<string, string> = {
        input: text,
      };
    
      if (model !== null && model !== "") {
        input.model = model
      }
      console.log(input)
    
      // Schedule the summarization task
      const { data: scheduleData, error: scheduleError } = await client.POST(
        "/ocs/v2.php/taskprocessing/schedule",
        {
          params: {
            header: {
              "OCS-APIRequest": true,
            },
            query: {
              format: "json",
            },
          },
          body: {
            type: TASK_TYPE_SUMMARY,
            input,
            appId: "windmill",
          },
        },
      );
    
      if (scheduleError) {
        throw new Error(`Failed to schedule summarization task: ${JSON.stringify(scheduleError)}`);
      }
      const taskId = scheduleData?.ocs?.data?.task?.id;
    
      // Polls every interval until timeout or a result happens
      const deadline = Date.now() + timeout_ms;
      while (Date.now() < deadline) {
        console.log("Polling task output")
        const { data: taskData, error: taskError } = await client.GET(
          "/ocs/v2.php/taskprocessing/task/{id}",
          {
            params: {
              header: {
                "OCS-APIRequest": true,
              },
              query: {
                format: "json",
              },
              path: {
                id: taskId,
              },
            },
          },
        );
    
        if (taskError) {
          throw new Error(`Failed to get task ${taskId}: ${JSON.stringify(taskError)}`);
        }
        const task = taskData.ocs?.data?.task;
        const status = task.status;
    
        if (status === "STATUS_SUCCESSFUL") {
          const output = task.output;
          if (output && typeof output.output === "string") {
            return { summarizedText: output.output, taskId };
          }
          return { summarizedText: output, taskId };
        }
    
        if (status === "STATUS_FAILED" || status === "STATUS_CANCELLED") {
          const msg = JSON.stringify(task);
          throw new Error(`Summarization task failed: ${msg}`);
        }
        if (!["STATUS_SCHEDULED", "STATUS_RUNNING"].includes(status)) {
          const msg = JSON.stringify(task);
          throw new Error(`Summarization task failed with unknown status: ${msg}`)
        }
        await new Promise((r) => setTimeout(r, interval_ms));
      }
    
      throw new Error(
        `Summarization task did not complete within ${timeout_ms}ms (taskId: ${taskId})`,
      );
    }
    

    Submitted by nextcloud 58 days ago