Registrati Accedi
n/program · 2024-12-04 · 409 visualizzazioni
u/xz123Argento
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
Accedi per partecipare alla discussione.
海外原生IP VPS,稳定访问全球网络

还在为IP不纯、平台风控、频繁验证而烦恼? 丽萨主机海外原生IP VPS,双ISP住宅IP,覆盖美国、香港、日本、新加坡、台湾、德国、越南、英国等热门地区,适合跨境电商、社媒运营、AI工具、流媒体及海外业务使用。

lisahost.com Scopri di più

0 risposte

Ordinamento

Ancora nessuna risposta. Sii il primo a dire qualcosa.