Last active
November 1, 2024 14:39
-
-
Save rkmax/cef19c9dabcc5f9060ccd364d1e1bccb to your computer and use it in GitHub Desktop.
Clipboard Translator using OpenAI API This Deno script translates text from your clipboard using OpenAI's API and copies the result back to your clipboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env -S deno run --allow-net --allow-env --allow-run --allow-read --allow-write | |
import { copy, paste } from "https://deno.land/x/[email protected]/mod.ts"; | |
import { config } from "https://deno.land/x/[email protected]/mod.ts"; | |
// Load environment variables | |
config({ export: true }); | |
const DEFAULT_SYSTEM = "Translate any user input into English, in an informal and concise way."; | |
const DEFAULT_MODEL = "gpt-4o-mini"; | |
async function notify(message: string, timeout: number = 2000): Promise<void> { | |
if (Deno.build.os === "windows") { | |
console.log(message); | |
} else { | |
const args = [ "-t", timeout.toString(), "Translate", message]; | |
const cmd = new Deno.Command('notify-send', {args}); | |
await cmd.output(); | |
} | |
} | |
async function translate(text: string): Promise<string> { | |
const apiKey = Deno.env.get("OPENAI_API_KEY"); | |
if (!apiKey) { | |
throw new Error("OPENAI_API_KEY must be set in your environment"); | |
} | |
const response = await fetch("https://api.openai.com/v1/chat/completions", { | |
method: "POST", | |
headers: { | |
"Content-Type": "application/json", | |
"Authorization": `Bearer ${apiKey}`, | |
}, | |
body: JSON.stringify({ | |
model: DEFAULT_MODEL, | |
messages: [ | |
{ role: "system", content: DEFAULT_SYSTEM }, | |
{ role: "user", content: text }, | |
], | |
}), | |
}); | |
const data = await response.json(); | |
return data.choices[0].message.content; | |
} | |
async function main() { | |
try { | |
await notify("Translating clipboard text..."); | |
const textFromClipboard = await paste(); | |
if (!textFromClipboard) { | |
throw new Error("No text found in clipboard."); | |
} | |
const translatedText = await translate(textFromClipboard); | |
await copy(translatedText); | |
await notify("Translation copied to clipboard.", 5000); | |
} catch (error) { | |
if (error instanceof Error) { | |
await notify(`Error: ${error.message}`); | |
} else { | |
throw error; | |
} | |
} | |
} | |
if (import.meta.main) { | |
main(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment