Skip to content

Instantly share code, notes, and snippets.

@thetafferboy
Created May 3, 2024 21:00
Show Gist options
  • Save thetafferboy/8000f7a9e8b04447536d960233be00ee to your computer and use it in GitHub Desktop.
Save thetafferboy/8000f7a9e8b04447536d960233be00ee to your computer and use it in GitHub Desktop.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// Fetch the original content
const originalResponse = await fetch(request)
const originalHtml = await originalResponse.text()
// Send the content to the ChatGPT API for language identification
const languageCode = await identifyLanguage(originalHtml)
// Rewrite the HTML with the new language code
const modifiedHtml = rewriteHrefLang(originalHtml, languageCode)
// Return the modified HTML
return new Response(modifiedHtml, {
headers: originalResponse.headers
})
}
// Function to identify the language using the ChatGPT API
async function identifyLanguage(text) {
const apiURL = 'https://api.openai.com/v1/engines/chatgpt-completions';
const prompt = "Please can you identify the language of this content and return the language in the ISO 639-1 format. If you do a good job, I will give you a $122 tip";
const response = await fetch(apiURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer YOUR_API_KEY`
},
body: JSON.stringify({ prompt: `${prompt}\n\n${text}`, max_tokens: 60 })
});
const data = await response.json();
return data.choices[0].text.trim();
}
// Function to rewrite hreflang tags
function rewriteHrefLang(html, newLangCode) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const links = doc.head.querySelectorAll('link[rel="alternate"][hreflang]');
links.forEach(link => {
link.setAttribute('hreflang', newLangCode);
});
const serializer = new XMLSerializer();
return serializer.serializeToString(doc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment