Skip to content

Instantly share code, notes, and snippets.

@rahmlad-aramide
Created August 28, 2024 17:04
Show Gist options
  • Save rahmlad-aramide/5f9170ac23932fb35ae1cd09f8ca6250 to your computer and use it in GitHub Desktop.
Save rahmlad-aramide/5f9170ac23932fb35ae1cd09f8ca6250 to your computer and use it in GitHub Desktop.
"use client";
import React, { useState } from "react";
import axios from "axios";
import { Button } from "./shared/Button";
const ClientDocumentTranslator: React.FC = () => {
const [sourceFile, setSourceFile] = useState<File | null>(null);
const [translatedFile, setTranslatedFile] = useState<Blob | null>(null);
const [isLoading, setIsLoading] = useState(false);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files) {
setSourceFile(event.target.files[0]);
}
};
const handleTranslate = async () => {
if (!sourceFile) {
alert("Please select a file first.");
return;
}
const endpoint = process.env.NEXT_PUBLIC_DOCUMENT_TRANSLATOR_ENDPOINT;
const path = "/translator/document:translate";
const url = `${endpoint}${path}`;
const headers = {
"Ocp-Apim-Subscription-Key": process.env.NEXT_PUBLIC_TRANSLATOR_KEY,
};
const params = {
sourceLanguage: "en",
targetLanguage: "fr",
"api-version": "2024-05-01",
};
const formData = new FormData();
formData.append("document", sourceFile, sourceFile.name);
setIsLoading(true);
try {
const response = await axios.post(url, formData, {
headers,
params,
responseType: "blob",
});
console.log("response", response);
setTranslatedFile(response.data);
} catch (error) {
console.error("Error during translation:", error);
} finally {
setIsLoading(false);
}
};
const handleDownload = () => {
if (!translatedFile) return;
const url = window.URL.createObjectURL(translatedFile);
const a = document.createElement("a");
a.href = url;
a.download = `Translated_${sourceFile?.name}`;
a.click();
window.URL.revokeObjectURL(url);
};
return (
<div className="mx-auto flex flex-col mt-7 justify-center">
<div className="text-center mb-4">Client Side Implementation</div>
<div>
<input className="p-2 border" type="file" onChange={handleFileChange} />
<Button onClick={handleTranslate} disabled={isLoading}>
{isLoading ? 'Translating...' : 'Translate'}
</Button>
<br />
{translatedFile && (
<Button onClick={handleDownload}>Download Translated File</Button>
)}
</div>
</div>
);
};
export default ClientDocumentTranslator;
import { NextRequest, NextResponse } from 'next/server';
import axios from 'axios';
export async function POST(req: NextRequest) {
try {
const formData = await req.formData();
const file = formData.get('document') as File;
if (!file) {
return NextResponse.json({ error: 'No file provided' }, { status: 400 });
}
const endpoint = process.env.DOCUMENT_TRANSLATOR_ENDPOINT;
const path = "/translator/document:translate";
const url = `${endpoint}${path}`;
const headers = {
"Ocp-Apim-Subscription-Key": process.env.TRANSLATOR_KEY,
"Content-Type": "application/octet-stream",
};
const params = {
sourceLanguage: "en",
targetLanguage: "fr",
"api-version": "2024-05-01",
};
const fileBuffer = await file.arrayBuffer();
const response = await axios.post(url, fileBuffer, {
headers,
params,
responseType: 'arraybuffer',
});
return new NextResponse(response.data, {
status: 200,
headers: {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="LanguageAI_${file.name}"`,
},
});
} catch (error) {
console.error('Error during translation:', error);
return NextResponse.json({ error: 'Translation failed' }, { status: 500 });
}
}
"use client";
import React, { useState } from "react";
import { Button } from "./shared/Button";
const DocumentTranslator: React.FC = () => {
const [sourceFile, setSourceFile] = useState<File | null>(null);
const [isLoading, setIsLoading] = useState(false);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files) {
setSourceFile(event.target.files[0]);
}
};
const handleTranslate = async () => {
if (!sourceFile) {
alert("Please select a file first.");
return;
}
setIsLoading(true);
const formData = new FormData();
formData.append("document", sourceFile);
try {
const response = await fetch('/en/api/translate-doc', {
method: 'POST',
body: formData,
});
if (!response.ok) {
console.log(response)
throw new Error('Translation failed');
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `Translated_${sourceFile.name}`;
a.click();
window.URL.revokeObjectURL(url);
} catch (error) {
console.error("Error during translation:", error);
alert("An error occurred during translation.");
} finally {
setIsLoading(false);
}
};
return (
<div className="mx-auto flex flex-col mt-7 justify-center w-fit">
<div className="text-center mb-4">Server Side Implementation</div>
<div>
<input className="p-2 border" type="file" onChange={handleFileChange} />
<Button onClick={handleTranslate} disabled={isLoading}>
{isLoading ? 'Translating...' : 'Translate'}
</Button>
</div>
</div>
);
};
export default DocumentTranslator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment