File size: 3,064 Bytes
e7c6240
 
 
 
24c2656
e7c6240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe735d
e7c6240
 
 
 
dbe735d
e7c6240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe735d
e7c6240
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Initialize the app container.
const app = document.getElementById('app');
app.innerHTML = `
  <div style="max-width: 1024px; margin: 0 auto; padding: 20px;">
    <button id="translateButton" style="margin-bottom: 10px;" disabled class="button-disabled">Translate to Spanish</button>
    <div id="editor" style="border: 1px solid black; height: 600px; position: relative"></div>
  </div>
`;

// Load Document Authoring SDK
const script = document.createElement('script');
script.src = 'https://document-authoring-cdn.pspdfkit.com/releases/document-authoring-1.0.26-umd.js';
script.crossOrigin = true;
document.head.appendChild(script);

script.onload = async () => {
  const docAuthSystem = await DocAuth.createDocAuthSystem({});
  
  const editor = await docAuthSystem.createEditor(
    document.getElementById("editor"),
    {
      document: await docAuthSystem.importDOCX(fetch('./Sample.docx')),
    }
  );

  // Translation function.
  async function translate(content, lang = "Spanish") {
    try {
      const response = await fetch('/client/api/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          messages: [
            {
              role: "system",
              content: "You are a translator. Only provide the translation, no explanations or additional text."
            },
            {
              role: "user",
              content: `Translate the following text to ${lang}: ${content}`
            }
          ],
          model: "gemma-2b",
          stream: false
        })
      });

      if (!response.ok) {
        throw new Error('Translation request failed');
      }

      const data = await response.json();
      return data.choices[0].message.content;
    } catch (error) {
      console.error("Translation error:", error);
      throw new Error("Failed to generate translation");
    }
  }

  // Function to recursively translate text in the JSON structure.
  async function translateRecursive(obj) {
    for (let key in obj) {
      if (typeof obj[key] === "string" && key === "text" && obj[key].length > 0) {
        obj[key] = await translate(obj[key]);
      } else if (typeof obj[key] === "object") {
	 await translateRecursive(obj[key]);
      }
    }
  }

  // Add translation button handler
  const translateButton = document.getElementById('translateButton');
  translateButton.addEventListener('click', async () => {
    try {
      translateButton.disabled = true;
      translateButton.innerHTML = '<span class="spinner"></span> Translating...';

      const jsonDoc = await editor.currentDocument().saveDocument();
      await translateRecursive(jsonDoc.container.document);
      const translatedDoc = await docAuthSystem.loadDocument(jsonDoc);
      editor.setCurrentDocument(translatedDoc);
    } catch (error) {
      alert('Translation failed: ' + error.message);
    } finally {
      translateButton.disabled = false;
      translateButton.innerHTML = 'Translate to Spanish';
    }
  });
};