注册 登录
n/program · 2024-12-04 · 407 次浏览
u/xz123白银
n/programu/xz123 · 2024-12-04

使用cloudflare wokers ai部署沉浸式翻译自定义API

代码来源于chatgpt,创建时使用wokers ai模板;或者创建完后绑定Workers AI 目录,绑定名称为AI

```
export default {
async fetch(request, env) {
if (request.method !== "POST") {
return new Response(
JSON.stringify({ error: "Only POST method is supported." }),
{ status: 405, headers: { "Content-Type": "application/json" } }
);
}

try {
  const { source_lang, target_lang, text_list } = await request.json();

  if (!source_lang || !target_lang || !Array.isArray(text_list)) {
    return new Response(
      JSON.stringify({ error: "Invalid input. Please provide source_lang, target_lang, and text_list." }),
      { status: 400, headers: { "Content-Type": "application/json" } }
    );
  }

  // Normalize language codes
  const normalizeLang = (lang) => lang.split('-')[0];
  const normalizedSourceLang = normalizeLang(source_lang);
  const normalizedTargetLang = normalizeLang(target_lang);

  // Placeholder management
  const delimiters = ['{', '}'];
  const placeholderTexts = text_list.map((text, index) => {
    return text.replace(/(\p{Emoji_Presentation}|\p{Extended_Pictographic})/gu, (_, match) => {
      return `${delimiters[0]}${index}${delimiters[1]}`;
    });
  });

  // Request to AI model
  const aiResponse = await env.AI.run("@cf/meta/m2m100-1.2b", {
    text: placeholderTexts.join("\n"),
    source_lang: normalizedSourceLang,
    target_lang: normalizedTargetLang,
  });

  if (!aiResponse || !aiResponse.translated_text) {
    return new Response(
      JSON.stringify({ error: "Invalid response from AI model.", details: aiResponse }),
      { status: 500, headers: { "Content-Type": "application/json" } }
    );
  }

  // Build translations array
  const translations = aiResponse.translated_text.split("\n").map((translatedText, index) => {
    const originalText = text_list[index];
    const detectedLang = aiResponse.detected_source_lang || normalizedSourceLang;

    return {
      detected_source_lang: detectedLang,
      text: translatedText.replace(
        new RegExp(`\\${delimiters[0]}(\\d+)\\${delimiters[1]}`, "g"),
        (_, matchedIndex) => originalText[matchedIndex]
      ),
    };
  });

  return new Response(
    JSON.stringify({ translations }),
    { headers: { "Content-Type": "application/json" } }
  );
} catch (error) {
  return new Response(
    JSON.stringify({ error: "Internal Server Error", details: error.message }),
    { status: 500, headers: { "Content-Type": "application/json" } }
  );
}

},
};
```

0
0
登录后参与讨论。

0 条回复

排序

还没有回复,来说第一句。