├── .dockerignore ├── src ├── public │ ├── _redirects │ ├── robots.txt │ ├── favicon.png │ ├── icons │ │ ├── icon-192x192.png │ │ ├── icon-512x512.png │ │ ├── icon-maskable-192x192.png │ │ └── icon-maskable-512x512.png │ ├── openai-translator-apple-touch-icon.png │ └── locales │ │ ├── zh │ │ └── translation.json │ │ ├── zh-TW │ │ └── translation.json │ │ ├── ja │ │ └── translation.json │ │ └── en │ │ └── translation.json ├── i18next.d.ts ├── vite-env.d.ts ├── pages │ ├── NotFound.tsx │ ├── HistoryRecord.tsx │ ├── Config.tsx │ └── Translator.tsx ├── components │ ├── Loading.tsx │ ├── ReactQueryProvider.tsx │ ├── ConfigButton.tsx │ ├── ToggleThemeButton.tsx │ ├── GlobalToaster.tsx │ ├── NavBar.tsx │ ├── SpeechRecognitionButton.tsx │ ├── TTSButton.tsx │ ├── Header.tsx │ ├── SwitchLanguageButton.tsx │ └── GlobalStore.tsx ├── client │ ├── apis.ts │ ├── fetcher.ts │ └── index.ts ├── prompt-sw.ts ├── layouts │ ├── TabLayout.tsx │ └── ConfigDrawerLayout.tsx ├── utils │ ├── index.ts │ └── prompt.ts ├── main.tsx ├── hooks │ ├── useQueryApi.ts │ ├── useTheme.ts │ └── useChatGPTStream.ts ├── i18n.ts ├── index.html ├── types.d.ts ├── App.tsx ├── index.css └── constants │ └── index.ts ├── .husky └── pre-commit ├── postcss.config.cjs ├── .prettierrc.json ├── .vscode ├── extensions.json └── settings.json ├── tsconfig.node.json ├── .hintrc ├── .gitignore ├── .prettierignore ├── Dockerfile ├── nginx └── default.conf ├── .github └── FUNDING.yml ├── tsconfig.json ├── tailwind.config.cjs ├── vite.config.ts ├── package.json ├── eslint.config.js ├── README.md └── LICENSE.md /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist -------------------------------------------------------------------------------- /src/public/_redirects: -------------------------------------------------------------------------------- 1 | /* /index.html 200 -------------------------------------------------------------------------------- /src/public/robots.txt: -------------------------------------------------------------------------------- 1 | User-agent: * 2 | Allow: / 3 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | pnpx lint-staged 5 | -------------------------------------------------------------------------------- /src/public/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LanceMoe/openai-translator/HEAD/src/public/favicon.png -------------------------------------------------------------------------------- /src/public/icons/icon-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LanceMoe/openai-translator/HEAD/src/public/icons/icon-192x192.png -------------------------------------------------------------------------------- /src/public/icons/icon-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LanceMoe/openai-translator/HEAD/src/public/icons/icon-512x512.png -------------------------------------------------------------------------------- /postcss.config.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: [require('tailwindcss'), require('autoprefixer'), require('postcss-100vh-fix')], 3 | }; 4 | -------------------------------------------------------------------------------- /src/public/icons/icon-maskable-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LanceMoe/openai-translator/HEAD/src/public/icons/icon-maskable-192x192.png -------------------------------------------------------------------------------- /src/public/icons/icon-maskable-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LanceMoe/openai-translator/HEAD/src/public/icons/icon-maskable-512x512.png -------------------------------------------------------------------------------- /src/i18next.d.ts: -------------------------------------------------------------------------------- 1 | import 'i18next'; 2 | 3 | declare module 'i18next' { 4 | interface CustomTypeOptions { 5 | returnNull: false; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/public/openai-translator-apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LanceMoe/openai-translator/HEAD/src/public/openai-translator-apple-touch-icon.png -------------------------------------------------------------------------------- /src/vite-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "semi": true, 3 | "tabWidth": 2, 4 | "printWidth": 120, 5 | "singleQuote": true, 6 | "trailingComma": "all", 7 | "jsxSingleQuote": false, 8 | "bracketSpacing": true 9 | } 10 | -------------------------------------------------------------------------------- /src/pages/NotFound.tsx: -------------------------------------------------------------------------------- 1 | function NotFound() { 2 | return ( 3 |
4 |

404 NotFound

5 |
6 | ); 7 | } 8 | 9 | export default NotFound; 10 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "dbaeumer.vscode-eslint", 4 | "andrewmcodes.tailwindcss-extension-pack", 5 | "esbenp.prettier-vscode", 6 | "steoates.autoimport", 7 | "ambar.bundle-size", 8 | "streetsidesoftware.code-spell-checker" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /tsconfig.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "strict": true, 5 | "composite": true, 6 | "module": "esnext", 7 | "moduleResolution": "node", 8 | "forceConsistentCasingInFileNames": true 9 | }, 10 | "include": ["vite.config.ts"] 11 | } 12 | -------------------------------------------------------------------------------- /src/components/Loading.tsx: -------------------------------------------------------------------------------- 1 | export function Loading() { 2 | return ( 3 |
4 |
5 |
Loading...
6 |
7 |
8 | ); 9 | } 10 | -------------------------------------------------------------------------------- /.hintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "development" 4 | ], 5 | "hints": { 6 | "meta-viewport": "off", 7 | "axe/forms": [ 8 | "default", 9 | { 10 | "label": "off" 11 | } 12 | ], 13 | "compat-api/html": [ 14 | "default", 15 | { 16 | "ignore": [ 17 | "img[loading]" 18 | ] 19 | } 20 | ] 21 | } 22 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | !.vscode/settings.json 19 | .idea 20 | .DS_Store 21 | *.suo 22 | *.ntvs* 23 | *.njsproj 24 | *.sln 25 | *.sw? 26 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | !.vscode/settings.json 19 | .idea 20 | .DS_Store 21 | *.suo 22 | *.ntvs* 23 | *.njsproj 24 | *.sln 25 | *.sw? 26 | -------------------------------------------------------------------------------- /src/components/ReactQueryProvider.tsx: -------------------------------------------------------------------------------- 1 | import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; 2 | 3 | const queryClient = new QueryClient(); 4 | 5 | type Props = { 6 | children: React.ReactNode; 7 | }; 8 | 9 | export function ReactQueryProvider(props: Props) { 10 | const { children } = props; 11 | return {children}; 12 | } 13 | -------------------------------------------------------------------------------- /src/components/ConfigButton.tsx: -------------------------------------------------------------------------------- 1 | import { useTranslation } from 'react-i18next'; 2 | import { BsFillGearFill } from 'react-icons/bs'; 3 | 4 | export function ConfigButton() { 5 | const { t } = useTranslation(); 6 | return ( 7 | 14 | ); 15 | } 16 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:18-buster-slim as builder 2 | 3 | LABEL maintainer="admin@lance.moe" 4 | 5 | WORKDIR /app 6 | COPY . ./ 7 | 8 | RUN npm install -g pnpm 9 | RUN pnpm install 10 | ENV NODE_ENV=production 11 | RUN pnpm build 12 | 13 | 14 | FROM nginx 15 | LABEL maintainer="admin@lance.moe" 16 | 17 | ENV NODE_ENV=production 18 | COPY --from=builder /app/dist /usr/share/nginx/html 19 | COPY --from=builder /app/nginx/default.conf /etc/nginx/conf.d/default.conf 20 | 21 | EXPOSE 80 22 | -------------------------------------------------------------------------------- /nginx/default.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 80; 3 | listen [::]:80; 4 | server_name localhost; 5 | 6 | location / { 7 | root /usr/share/nginx/html; 8 | index index.html index.htm; 9 | try_files $uri $uri/ /index.html; 10 | } 11 | 12 | #error_page 404 /404.html; 13 | 14 | # redirect server error pages to the static page /50x.html 15 | # 16 | error_page 500 502 503 504 /50x.html; 17 | location = /50x.html { 18 | root /usr/share/nginx/html; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/client/apis.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | baseUrl: 'https://api.openai.com', 3 | endpoints: { 4 | v1: { 5 | completions: { 6 | url: '/v1/completions', 7 | method: 'POST', 8 | headers: { 9 | 'Content-Type': 'application/json', 10 | }, 11 | }, 12 | chat: { 13 | completions: { 14 | url: '/v1/chat/completions', 15 | method: 'POST', 16 | headers: { 17 | 'Content-Type': 'application/json', 18 | }, 19 | }, 20 | }, 21 | }, 22 | }, 23 | }; 24 | -------------------------------------------------------------------------------- /src/prompt-sw.ts: -------------------------------------------------------------------------------- 1 | import { cleanupOutdatedCaches, precacheAndRoute } from 'workbox-precaching'; 2 | 3 | declare let self: ServiceWorkerGlobalScope; 4 | 5 | if (import.meta.env.DEV) { 6 | // @ts-expect-error: inject to window 7 | self.__WB_DISABLE_DEV_LOGS = true; 8 | } 9 | 10 | self.addEventListener('message', (event) => { 11 | if (event.data && event.data.type === 'SKIP_WAITING') { 12 | self.skipWaiting(); 13 | } 14 | }); 15 | 16 | // clean old assets 17 | cleanupOutdatedCaches(); 18 | 19 | // self.__WB_MANIFEST is default injection point 20 | precacheAndRoute(self.__WB_MANIFEST); 21 | -------------------------------------------------------------------------------- /src/layouts/TabLayout.tsx: -------------------------------------------------------------------------------- 1 | import { Suspense } from 'react'; 2 | import { Outlet } from 'react-router-dom'; 3 | 4 | import Header from '@/components/Header'; 5 | import { Loading } from '@/components/Loading'; 6 | import NavBar from '@/components/NavBar'; 7 | import ConfigDrawerLayout from '@/layouts/ConfigDrawerLayout'; 8 | 9 | function TabLayout() { 10 | return ( 11 | 12 |
13 | }> 14 | 15 | 16 | 17 | 18 | ); 19 | } 20 | 21 | export default TabLayout; 22 | -------------------------------------------------------------------------------- /src/utils/index.ts: -------------------------------------------------------------------------------- 1 | export function trimText(text: string) { 2 | if (text.startsWith('"') || text.startsWith('「')) { 3 | text = text.slice(1); 4 | } 5 | if (text.endsWith('"') || text.endsWith('」')) { 6 | text = text.slice(0, -1); 7 | } 8 | return text; 9 | } 10 | 11 | export function formatTime(time: number, lang = 'en-US') { 12 | const dt = new Date(time); 13 | const result = new Intl.DateTimeFormat(lang, { 14 | year: 'numeric', 15 | month: 'short', 16 | day: 'numeric', 17 | hour: 'numeric', 18 | minute: 'numeric', 19 | second: 'numeric', 20 | }).format(dt); 21 | return result; 22 | } 23 | 24 | export const getKeys = >(obj: T): (keyof T)[] => Object.keys(obj); 25 | -------------------------------------------------------------------------------- /src/main.tsx: -------------------------------------------------------------------------------- 1 | import '@/i18n'; 2 | import '@/index.css'; 3 | import 'regenerator-runtime/runtime'; 4 | 5 | import React from 'react'; 6 | import ReactDOM from 'react-dom/client'; 7 | import { registerSW } from 'virtual:pwa-register'; 8 | 9 | import App from '@/App'; 10 | 11 | const rootElement = document.getElementById('root'); 12 | if (rootElement) { 13 | ReactDOM.createRoot(rootElement).render( 14 | 15 | 16 | , 17 | ); 18 | } 19 | 20 | // Service Worker registration 21 | registerSW({ 22 | // eslint-disable-next-line @typescript-eslint/no-empty-function 23 | onNeedRefresh() {}, 24 | // eslint-disable-next-line @typescript-eslint/no-empty-function 25 | onOfflineReady() {}, 26 | }); 27 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # !STARTERCONF You can delete this file :) Your support is much appreciated! 2 | # These are supported funding model platforms 3 | 4 | github: LanceMoe 5 | patreon: # Replace with a single Patreon username 6 | open_collective: # Replace with a single Open Collective username 7 | ko_fi: # Replace with a single Ko-fi username 8 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 9 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 10 | liberapay: # Replace with a single Liberapay username 11 | issuehunt: # Replace with a single IssueHunt username 12 | otechie: # Replace with a single Otechie username 13 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 14 | custom: ['https://www.lance.moe/'] 15 | -------------------------------------------------------------------------------- /src/components/ToggleThemeButton.tsx: -------------------------------------------------------------------------------- 1 | import { useTranslation } from 'react-i18next'; 2 | import { BsLightbulbFill, BsMoonStarsFill } from 'react-icons/bs'; 3 | 4 | import { useTheme } from '@/hooks/useTheme'; 5 | 6 | export function ToggleThemeButton() { 7 | const { t } = useTranslation(); 8 | const { theme, toggleTheme } = useTheme(); 9 | 10 | return ( 11 | 22 | ); 23 | } 24 | -------------------------------------------------------------------------------- /src/layouts/ConfigDrawerLayout.tsx: -------------------------------------------------------------------------------- 1 | import { lazy, Suspense } from 'react'; 2 | 3 | import { Loading } from '@/components/Loading'; 4 | 5 | const ConfigPage = lazy(() => import('@/pages/Config')); 6 | 7 | type Props = { 8 | children: React.ReactNode; 9 | }; 10 | 11 | function ConfigDrawerLayout(props: Props) { 12 | const { children } = props; 13 | 14 | return ( 15 | <> 16 | 17 |
{children}
18 |
19 | 20 | }> 21 | 22 | 23 |
24 | 25 | ); 26 | } 27 | 28 | export default ConfigDrawerLayout; 29 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "useDefineForClassFields": true, 5 | "lib": ["DOM", "DOM.Iterable", "ESNext", "WebWorker"], 6 | "allowJs": false, 7 | "skipLibCheck": true, 8 | "esModuleInterop": false, 9 | "allowSyntheticDefaultImports": true, 10 | "strict": true, 11 | "forceConsistentCasingInFileNames": true, 12 | "module": "ESNext", 13 | "moduleResolution": "Node", 14 | "resolveJsonModule": true, 15 | "isolatedModules": true, 16 | "noEmit": true, 17 | "jsx": "react-jsx", 18 | "types": ["vite/client", "vite-plugin-pwa/client"], 19 | "baseUrl": "./", 20 | "paths": { 21 | "@/*": ["./src/*"] 22 | } 23 | }, 24 | "include": ["./src", "node_modules/vite-plugin-pwa/client.d.ts"], 25 | "references": [ 26 | { 27 | "path": "./tsconfig.node.json" 28 | } 29 | ] 30 | } 31 | -------------------------------------------------------------------------------- /src/hooks/useQueryApi.ts: -------------------------------------------------------------------------------- 1 | import { useMutation } from '@tanstack/react-query'; 2 | import { useMemo } from 'react'; 3 | 4 | import { fetchTranslation } from '@/client/fetcher'; 5 | 6 | import { useChatGPTStream } from './useChatGPTStream'; 7 | 8 | export function useQueryApi(streamEnabled = true) { 9 | const { data, mutate, isPending, isError } = useMutation({ mutationFn: fetchTranslation }); 10 | const { 11 | data: streamData, 12 | mutate: streamMutate, 13 | isLoading: streamIsLoading, 14 | isError: streamIsError, 15 | } = useChatGPTStream(); 16 | 17 | const value = useMemo( 18 | () => 19 | streamEnabled 20 | ? { data: streamData, mutate: streamMutate, isLoading: streamIsLoading, isError: streamIsError } 21 | : { data, mutate, isLoading: isPending, isError }, 22 | [data, isError, isPending, mutate, streamData, streamEnabled, streamIsError, streamIsLoading, streamMutate], 23 | ); 24 | 25 | return value; 26 | } 27 | -------------------------------------------------------------------------------- /src/i18n.ts: -------------------------------------------------------------------------------- 1 | import i18n from 'i18next'; 2 | import Backend from 'i18next-http-backend/cjs'; 3 | import { initReactI18next } from 'react-i18next'; 4 | 5 | const langCode = localStorage.getItem('langCode'); 6 | 7 | i18n 8 | .use(Backend) 9 | .use(initReactI18next) // passes i18n down to react-i18next 10 | .init({ 11 | defaultNS: 'translation', 12 | lng: langCode ? langCode.slice(1, -1) : 'zh', 13 | // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources 14 | // you can use the i18n.changeLanguage function to change the language manually: https://www.i18next.com/overview/api#changelanguage 15 | // if you're using a language detector, do not define the lng option 16 | 17 | fallbackLng: false, 18 | interpolation: { 19 | escapeValue: false, // react already safes from xss 20 | }, 21 | returnNull: false, 22 | react: { 23 | useSuspense: true, 24 | }, 25 | }); 26 | 27 | export default i18n; 28 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | OpenAI Translator 5 | 9 | 10 | 11 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/types.d.ts: -------------------------------------------------------------------------------- 1 | interface Window { 2 | BUILD_TIME: string; 3 | } 4 | 5 | declare const BUILD_TIME: string; 6 | 7 | type CompletionsResponse = { 8 | id: string; 9 | object: string; 10 | created: number; 11 | model: string; 12 | choices: { 13 | text: string; 14 | index: number; 15 | logprobs: number | null; 16 | finish_reason: string; 17 | }[]; 18 | usage: { 19 | prompt_tokens: number; 20 | completion_tokens: number; 21 | total_tokens: number; 22 | }; 23 | }; 24 | 25 | type ChatCompletionsResponse = { 26 | id: string; 27 | object: string; 28 | created: number; 29 | model: string; 30 | usage: { 31 | prompt_tokens: number; 32 | completion_tokens: number; 33 | total_tokens: number; 34 | }; 35 | choices: { 36 | delta?: { 37 | content: string; 38 | }; 39 | message?: { 40 | role: string; 41 | content: string; 42 | }; 43 | finish_reason: string; 44 | index: number; 45 | }[]; 46 | }; 47 | 48 | type HistoryRecord = { 49 | id: string; 50 | text: string; 51 | translation: string; 52 | createdAt: number; 53 | fromLanguage: string; 54 | toLanguage: string; 55 | }; 56 | 57 | type LastTranslateData = { 58 | fromLang: string; 59 | toLang: string; 60 | }; 61 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import '@/i18n'; 2 | import '@/index.css'; 3 | 4 | import { lazy } from 'react'; 5 | import { BrowserRouter, Route, Routes } from 'react-router-dom'; 6 | 7 | import { GlobalProvider } from '@/components/GlobalStore'; 8 | import { ReactQueryProvider } from '@/components/ReactQueryProvider'; 9 | import { useAutoChangeTheme } from '@/hooks/useTheme'; 10 | import TabLayout from '@/layouts/TabLayout'; 11 | import NotFound from '@/pages/NotFound'; 12 | 13 | const GlobalToaster = lazy(() => import('@/components/GlobalToaster')); 14 | 15 | const TranslatorPage = lazy(() => import('@/pages/Translator')); 16 | const HistoryRecordPage = lazy(() => import('@/pages/HistoryRecord')); 17 | 18 | function App() { 19 | useAutoChangeTheme(); 20 | 21 | return ( 22 | 23 | 24 | 25 | 26 | 27 | }> 28 | } /> 29 | } /> 30 | 31 | } /> 32 | 33 | 34 | 35 | 36 | ); 37 | } 38 | 39 | export default App; 40 | -------------------------------------------------------------------------------- /src/utils/prompt.ts: -------------------------------------------------------------------------------- 1 | import { Language, LANGUAGES } from '@/constants'; 2 | 3 | export const getTranslatePrompt = (fromLang: Language, toLang: Language) => { 4 | if (fromLang === 'wyw' || fromLang === 'zh-Hans' || fromLang === 'zh-Hant') { 5 | if (toLang === 'zh-Hant') { 6 | return '翻譯成繁體白話文,使用台灣用語'; 7 | } else if (toLang === 'zh-Hans') { 8 | return '翻译成简体白话文'; 9 | } else if (toLang === 'yue') { 10 | return '翻譯成粵語白話文'; 11 | } 12 | } 13 | if (toLang === 'wyw' || toLang === 'yue') { 14 | return `翻譯成${LANGUAGES[toLang] || toLang}`; 15 | } 16 | if (fromLang === 'auto') { 17 | if (toLang === 'zh-Hant') { 18 | return '翻譯為繁體中文,使用台灣用語'; 19 | } 20 | if (toLang === 'zh-Hans') { 21 | return '翻译成简体'; 22 | } 23 | if (toLang === 'ja') { 24 | return 'Translate into Japanese.'; 25 | } 26 | return `translate into ${LANGUAGES[toLang] || toLang}`; 27 | } 28 | if (fromLang === toLang) { 29 | if (toLang === 'zh-Hans') { 30 | return '润色此句'; 31 | } else if (toLang === 'zh-Hant') { 32 | return '把這段文字潤飾一下,使用台灣用語'; 33 | } else if (toLang === 'ja') { 34 | return 'この文を磨く'; 35 | } else if (toLang === 'ko') { 36 | return '이 문장을 예쁘게 만들어주세요'; 37 | } else { 38 | return 'polish this sentence'; 39 | } 40 | } 41 | return `translate from ${LANGUAGES[fromLang] || fromLang} to ${LANGUAGES[toLang] || toLang}`; 42 | }; 43 | -------------------------------------------------------------------------------- /src/hooks/useTheme.ts: -------------------------------------------------------------------------------- 1 | import { useEffect } from 'react'; 2 | import { create } from 'zustand'; 3 | import { persist } from 'zustand/middleware'; 4 | 5 | const statusBarColor = { 6 | light: '#ffffff', 7 | dark: '#1E232A', 8 | } as const; 9 | 10 | const localStorageKey = 'openai-translator-theme' as const; 11 | 12 | const isSystemInDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches; 13 | 14 | type ThemeStore = { 15 | theme: 'light' | 'dark'; 16 | toggleTheme: () => void; 17 | }; 18 | 19 | export const useTheme = create()( 20 | persist( 21 | (set) => ({ 22 | theme: isSystemInDarkMode ? 'dark' : 'light', 23 | toggleTheme: () => set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light' })), 24 | }), 25 | { name: localStorageKey }, 26 | ), 27 | ); 28 | 29 | export function setDaisyUiTheme(theme: string) { 30 | document.documentElement.setAttribute('data-theme', theme); 31 | } 32 | 33 | export function setThemeColor(color: string) { 34 | const themeMeta = document.head.querySelector('meta[name="theme-color"]'); 35 | themeMeta?.setAttribute('content', color); 36 | } 37 | 38 | export function useAutoChangeTheme() { 39 | const { theme } = useTheme(); 40 | useEffect(() => { 41 | document.documentElement.classList.toggle('dark', theme === 'dark'); 42 | setDaisyUiTheme(theme); 43 | setThemeColor(statusBarColor[theme]); 44 | }, [theme]); 45 | } 46 | -------------------------------------------------------------------------------- /tailwind.config.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | content: [ 3 | './src/**/*.{html,js,jsx,md,mdx,ts,tsx}', 4 | 'node_modules/daisyui/dist/**/*.js', 5 | 'node_modules/react-daisyui/dist/**/*.js', 6 | ], 7 | // prefix: 'tw-', 8 | darkMode: 'class', 9 | important: true, 10 | theme: { 11 | extend: { 12 | boxShadow: { 13 | tabs: '0 0 12px hsla(174, 65%, 15%, 0.15)', 14 | }, 15 | borderRadius: { 16 | tabs: '1rem 1rem 0 0', 17 | }, 18 | fontFamily: { 19 | sans: [ 20 | '-apple-system', 21 | 'BlinkMacSystemFont', 22 | 'Segoe UI', 23 | 'Roboto', 24 | 'Oxygen', 25 | 'Ubuntu', 26 | 'Cantarell', 27 | 'Fira Sans', 28 | 'Droid Sans', 29 | 'Helvetica Neue', 30 | 'sans-serif', 31 | ], 32 | }, 33 | }, 34 | }, 35 | daisyui: { 36 | styled: true, 37 | base: true, 38 | utils: true, 39 | logs: true, 40 | rtl: false, 41 | prefix: '', 42 | darkTheme: 'dark', 43 | themes: [ 44 | { 45 | light: { 46 | ...require('daisyui/src/theming/themes')['light'], 47 | primary: '#1967d2', 48 | }, 49 | }, 50 | { 51 | dark: { 52 | ...require('daisyui/src/theming/themes')['dark'], 53 | primary: '#7096F8', 54 | }, 55 | }, 56 | ], 57 | }, 58 | plugins: [require('daisyui')], 59 | }; 60 | -------------------------------------------------------------------------------- /src/client/fetcher.ts: -------------------------------------------------------------------------------- 1 | import OpenAIClient from '@/client'; 2 | import { CHAT_MODELS, type ChatModel, type OpenAIModel } from '@/constants'; 3 | import { trimText } from '@/utils'; 4 | 5 | export const fetchTranslation = async (params: { 6 | token: string; 7 | engine: OpenAIModel; 8 | prompt: string; 9 | temperatureParam: number; 10 | queryText: string; 11 | }) => { 12 | const { token, engine, prompt, queryText, temperatureParam } = params; 13 | if (!token) { 14 | throw new Error('No API Key found!'); 15 | } 16 | if (!prompt) { 17 | throw new Error('No prompt found!'); 18 | } 19 | 20 | const getRadomNumber = (min: number, max: number) => { 21 | return Math.random() * (max - min) + min; 22 | }; 23 | 24 | const isChatModel = (CHAT_MODELS as string[]).includes(engine); 25 | 26 | const tmpParam = +temperatureParam > 0.4 && +temperatureParam <= 1.0 ? +temperatureParam : getRadomNumber(0.5, 1.0); 27 | 28 | if (isChatModel) { 29 | const resp = await OpenAIClient.chatCompletions(token, prompt, queryText, engine as ChatModel, tmpParam); 30 | const text = resp.data.choices 31 | .map((choice) => choice.message?.content.trim() || '') 32 | .join('\n') 33 | .trim(); 34 | return trimText(text); 35 | } 36 | 37 | const resp = await OpenAIClient.completions(token, prompt, queryText, engine, tmpParam); 38 | const text = resp.data.choices 39 | .map((choice) => choice.text.trim()) 40 | .join('\n') 41 | .trim(); 42 | return trimText(text); 43 | }; 44 | -------------------------------------------------------------------------------- /src/components/GlobalToaster.tsx: -------------------------------------------------------------------------------- 1 | import { Transition } from '@headlessui/react'; 2 | import { Button } from 'react-daisyui'; 3 | import toast, { resolveValue, Toaster, ToastIcon } from 'react-hot-toast'; 4 | import { twMerge } from 'tailwind-merge'; 5 | 6 | const toastStyle = { 7 | success: 'alert-success', 8 | error: 'alert-error', 9 | loading: 'alert-info', 10 | custom: 'alert-warning', 11 | blank: '', 12 | }; 13 | 14 | export default function GlobalToaster() { 15 | return ( 16 | 17 | {(t) => ( 18 | 28 |
35 | 36 |
37 |

{resolveValue(t.message, t)}

38 |
39 | 42 |
43 |
44 | )} 45 |
46 | ); 47 | } 48 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.tabSize": 2, 3 | 4 | // disable default validator 5 | "css.validate": false, 6 | "scss.validate": false, 7 | 8 | // デフォルトのフォーマットの設定をOFFに 9 | // https://tech-1natsu.hatenablog.com/entry/2018/11/10/231855 10 | "editor.formatOnSave": true, 11 | 12 | // フォーマッターの指定 13 | "editor.defaultFormatter": "esbenp.prettier-vscode", 14 | 15 | // 言語別に設定 16 | // https://qiita.com/mysticatea/items/3f306470e8262e50bb70 17 | "[javascript]": { 18 | "editor.codeActionsOnSave": { 19 | "source.fixAll.eslint": "explicit" 20 | } 21 | }, 22 | "[typescript]": { 23 | "editor.codeActionsOnSave": { 24 | "source.fixAll.eslint": "explicit", 25 | "source.fixAll.stylelint": "explicit" 26 | } 27 | }, 28 | "[typescriptreact]": { 29 | "editor.codeActionsOnSave": { 30 | "source.fixAll.eslint": "explicit", 31 | "source.fixAll.stylelint": "explicit" 32 | } 33 | }, 34 | "[css]": { 35 | "editor.codeActionsOnSave": { 36 | "source.fixAll.stylelint": "explicit" 37 | } 38 | }, 39 | "[json]": { 40 | "editor.formatOnSave": true 41 | }, 42 | "[jsonc]": { 43 | "editor.formatOnSave": true 44 | }, 45 | "[typescript][typescriptreact]": { 46 | "editor.codeActionsOnSave": { 47 | "source.fixAll.eslint": "explicit", 48 | "source.fixAll.stylelint": "explicit" 49 | } 50 | }, 51 | "tailwindCSS.classAttributes": ["class", "className", " ngClass", "classes", ".*_CLASSES"], 52 | "cSpell.words": ["Davinci", "OPENAI", "zustand"], 53 | "eslint.useFlatConfig": true, 54 | "editor.quickSuggestions": { 55 | "strings": "on" 56 | }, 57 | "files.associations": { 58 | "*.css": "tailwindcss" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/components/NavBar.tsx: -------------------------------------------------------------------------------- 1 | import clsx from 'clsx'; 2 | import { useMemo } from 'react'; 3 | import { useTranslation } from 'react-i18next'; 4 | import { BsTranslate } from 'react-icons/bs'; 5 | import { FaHistory } from 'react-icons/fa'; 6 | import { Link, matchPath, useLocation } from 'react-router-dom'; 7 | 8 | const NAV_ITEMS = [ 9 | { key: 'translator', label: 'Translator', to: '/', icon: }, 10 | { key: 'history', label: 'History records', to: '/history', icon: }, 11 | ] as const; 12 | 13 | function NavBar() { 14 | const location = useLocation(); 15 | const { t } = useTranslation(); 16 | 17 | const selectedKey = useMemo( 18 | () => 19 | matchPath({ path: '/', end: true }, location.pathname) 20 | ? NAV_ITEMS[0].key 21 | : NAV_ITEMS.find(({ to }) => matchPath({ path: to, end: true }, location.pathname))?.key, 22 | [location], 23 | ); 24 | 25 | return ( 26 |
27 |
    28 | {NAV_ITEMS.map(({ key, label, to, icon }) => ( 29 |
  • 33 | 34 |
    40 | {icon} 41 | {/* {t(`navbar.${label}`)} */} 42 | 43 |
  • 44 | ))} 45 |
46 |
47 | ); 48 | } 49 | 50 | export default NavBar; 51 | -------------------------------------------------------------------------------- /src/public/locales/zh/translation.json: -------------------------------------------------------------------------------- 1 | { 2 | "topBar": { 3 | "title": "OpenAI 翻译器", 4 | "darkModeSwitcherTitle": "深色模式切换" 5 | }, 6 | "navbar": { 7 | "Translator": "翻译器", 8 | "History records": "历史记录" 9 | }, 10 | "Please enter your API Key in config page first!": "请先在设置页面输入您的 API Key!", 11 | "Something went wrong, please try again later.": "出了点问题,请稍后再试。", 12 | "Please enter the text you want to translate here.": "请输入您想要翻译的文字。", 13 | "Translate": "翻译", 14 | "Translating...": "翻译中...", 15 | "Please wait...": "请稍等...", 16 | "Translated text will appear here.": "翻译结果将会显示在这里。", 17 | "Model (engine)": "模型 (引擎)", 18 | "OpenAI API Key": "OpenAI API Key", 19 | "Please enter API Url.": "请输入 API Url。", 20 | "Please enter your API Key.": "请输入您的 API Key。", 21 | "Please select a model.": "请选择一个模型。", 22 | "Config": "设置", 23 | "Config Saved!": "设置已保存!", 24 | "Get your OpenAI API Key": "获取您的 OpenAI API Key", 25 | "Please paste your OpenAI API Key here.": "请将您的 OpenAI API Key 粘贴到这里。", 26 | "Save": "保存", 27 | "Cancel": "取消", 28 | "Yes": "是", 29 | "Copy original text": "复制原文", 30 | "Copy translation": "复制翻译", 31 | "No history record.": "没有历史记录。", 32 | "Delete this record": "删除这条记录", 33 | "Do you really want to clear all history?": "您真的想要清空所有历史记录吗?", 34 | "Notice!": "注意!", 35 | "Clear All": "清空所有", 36 | "History Record": "历史记录", 37 | "Delete history record successfully.": "删除历史记录成功。", 38 | "Clear history records successfully.": "清空历史记录成功。", 39 | "Copy original text successfully.": "复制原文成功。", 40 | "Copy translation successfully.": "复制翻译成功。", 41 | "Temperature": "随机应变", 42 | "Higher temperature will be more creative.": "随机应变值越高,结果越有创意。", 43 | "Use stream (typing effect)": "使用流模式 (打字效果)", 44 | "Reset to default": "重置为默认值", 45 | "Don't forget to click the save button for the settings to take effect!": "别忘了点击保存按钮使设置生效!", 46 | "Close": "关闭", 47 | "Change Language": "更改语言", 48 | "Nothing to copy!": "没有可复制的内容!", 49 | "Copied!": "已复制!", 50 | "Failed to copy!": "复制失败!", 51 | "Copy translated text": "复制翻译" 52 | } 53 | -------------------------------------------------------------------------------- /src/public/locales/zh-TW/translation.json: -------------------------------------------------------------------------------- 1 | { 2 | "topBar": { 3 | "title": "OpenAI 翻譯器", 4 | "darkModeSwitcherTitle": "切換深色模式" 5 | }, 6 | "navbar": { 7 | "Translator": "翻譯器", 8 | "History records": "歷史記錄" 9 | }, 10 | "Please enter your API Key in config page first!": "請先在設定頁面輸入您的 API Key!", 11 | "Something went wrong, please try again later.": "出了點問題,請稍後再試。", 12 | "Please enter the text you want to translate here.": "請輸入您想要翻譯的文字。", 13 | "Translate": "翻譯", 14 | "Translating...": "翻譯中...", 15 | "Please wait...": "請稍等...", 16 | "Translated text will appear here.": "翻譯結果將會顯示在這裡。", 17 | "Model (engine)": "模型(引擎)", 18 | "OpenAI API Key": "OpenAI API Key", 19 | "Please enter API Url.": "請輸入 API Url。", 20 | "Please enter your API Key.": "請輸入您的 API Key。", 21 | "Please select a model.": "請選擇一個模型。", 22 | "Config": "設定", 23 | "Config Saved!": "設定已儲存!", 24 | "Get your OpenAI API Key": "取得您的 OpenAI API Key", 25 | "Please paste your OpenAI API Key here.": "請在這裡貼上你的 OpenAI API Key。", 26 | "Save": "儲存", 27 | "Cancel": "取消", 28 | "Yes": "是", 29 | "Copy original text": "複製原文", 30 | "Copy translation": "複製翻譯", 31 | "No history record.": "沒有歷史記錄。", 32 | "Delete this record": "刪除這筆記錄", 33 | "Do you really want to clear all history?": "您真的想要清除所有歷史記錄嗎?", 34 | "Notice!": "注意!", 35 | "Clear All": "清除所有", 36 | "History Record": "歷史記錄", 37 | "Delete history record successfully.": "成功刪除歷史記錄。", 38 | "Clear history records successfully.": "成功清除歷史記錄。", 39 | "Copy original text successfully.": "成功複製原文。", 40 | "Copy translation successfully.": "成功複製翻譯。", 41 | "Temperature": "隨機應變", 42 | "Higher temperature will be more creative.": "隨機應變值越高,結果越有創意。", 43 | "Use stream (typing effect)": "使用串流模式 (打字效果)", 44 | "Reset to default": "重設為預設值", 45 | "Don't forget to click the save button for the settings to take effect!": "別忘了點選儲存按鈕設定才會生效!", 46 | "Close": "關閉", 47 | "Change Language": "更改語言", 48 | "Nothing to copy!": "沒有可複製的內容!", 49 | "Copied!": "已複製!", 50 | "Failed to copy!": "複製失敗!", 51 | "Copy translated text": "複製翻譯" 52 | } 53 | -------------------------------------------------------------------------------- /src/components/SpeechRecognitionButton.tsx: -------------------------------------------------------------------------------- 1 | import { useCallback, useEffect } from 'react'; 2 | import { Button } from 'react-daisyui'; 3 | import { toast } from 'react-hot-toast'; 4 | import { useTranslation } from 'react-i18next'; 5 | import { MdOutlineMicNone, MdStop } from 'react-icons/md'; 6 | import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition'; 7 | 8 | type Props = { 9 | language: string; 10 | onChangeTranscript: (newTranscript: string) => void; 11 | } & React.ComponentPropsWithoutRef; 12 | 13 | export function SpeechRecognitionButton(props: Props) { 14 | const { language, onChangeTranscript, ...restProps } = props; 15 | const { t } = useTranslation(); 16 | 17 | const { transcript, listening, resetTranscript, browserSupportsSpeechRecognition } = useSpeechRecognition(); 18 | 19 | useEffect(() => { 20 | onChangeTranscript(transcript); 21 | }, [onChangeTranscript, transcript]); 22 | 23 | const onClickSpeechRecognitionBtn = useCallback(() => { 24 | if (!listening) { 25 | resetTranscript(); 26 | SpeechRecognition.startListening({ 27 | language: language === 'wyw' ? 'zh-TW' : language, 28 | continuous: true, 29 | }); 30 | toast.success(t('Recording started.')); 31 | } else { 32 | SpeechRecognition.stopListening(); 33 | toast.success(t('Recording stopped.')); 34 | } 35 | }, [language, listening, resetTranscript, t]); 36 | 37 | if (!browserSupportsSpeechRecognition) { 38 | return null; 39 | } 40 | 41 | // NOTE: This is a workaround for a bug in react-daisyui. 42 | // eslint-disable-next-line react-compiler/react-compiler 43 | (restProps as Record)['type'] = 'button'; 44 | 45 | return ( 46 | 56 | ); 57 | } 58 | -------------------------------------------------------------------------------- /src/public/locales/ja/translation.json: -------------------------------------------------------------------------------- 1 | { 2 | "topBar": { 3 | "title": "OpenAI翻訳機", 4 | "darkModeSwitcherTitle": "暗色モードに切り替える" 5 | }, 6 | "navbar": { 7 | "Translator": "翻訳機", 8 | "History records": "履歴記録" 9 | }, 10 | "Please enter your API Key in config page first!": "最初に設定ページでAPIキーを入力してください!", 11 | "Something went wrong, please try again later.": "何かが間違っているようです。後でもう一度お試しください。", 12 | "Please enter the text you want to translate here.": "翻訳したいテキストをここに入力してください。", 13 | "Translate": "翻訳する", 14 | "Translating...": "翻訳中...", 15 | "Please wait...": "お待ちください...", 16 | "Translated text will appear here.": "翻訳されたテキストがここに表示されます。", 17 | "Model (engine)": "モデル(エンジン)", 18 | "OpenAI API Key": "OpenAI APIキー", 19 | "Please enter API Url.": "API URLを入力してください。", 20 | "Please enter your API Key.": "APIキーを入力してください。", 21 | "Please select a model.": "モデルを選択してください。", 22 | "Config": "設定", 23 | "Config Saved!": "設定が保存されました!", 24 | "Get your OpenAI API Key": "OpenAI APIキーを取得する", 25 | "Please paste your OpenAI API Key here.": "OpenAI APIキーをここに貼り付けてください。", 26 | "Save": "保存", 27 | "Cancel": "キャンセル", 28 | "Yes": "はい", 29 | "Copy original text": "元のテキストをコピー", 30 | "Copy translation": "翻訳をコピー", 31 | "No history record.": "履歴記録はありません。", 32 | "Delete this record": "この記録を削除する", 33 | "Do you really want to clear all history?": "本当にすべての履歴を消去しますか?", 34 | "Notice!": "注意!", 35 | "Clear All": "すべて消去", 36 | "History Record": "履歴記録", 37 | "Delete history record successfully.": "履歴記録を削除しました。", 38 | "Clear history records successfully.": "履歴記録を消去しました。", 39 | "Copy original text successfully.": "元のテキストをコピーしました。", 40 | "Copy translation successfully.": "翻訳をコピーしました。", 41 | "Temperature": "臨機応変", 42 | "Higher temperature will be more creative.": "高い臨機応変值はより創造的になります。", 43 | "Use stream (typing effect)": "ストリームを有効(タイピング効果)", 44 | "Reset to default": "デフォルトにリセット", 45 | "Don't forget to click the save button for the settings to take effect!": "設定を有効にするには保存ボタンをクリックしてください!", 46 | "Close": "閉じる", 47 | "Change Language": "言語を変更する", 48 | "Nothing to copy!": "コピーするものがありません!", 49 | "Copied!": "コピーしました!", 50 | "Failed to copy!": "コピーに失敗しました!", 51 | "Copy translated text": "翻訳されたテキストをコピーする" 52 | } 53 | -------------------------------------------------------------------------------- /src/components/TTSButton.tsx: -------------------------------------------------------------------------------- 1 | import { useCallback, useEffect, useMemo, useState } from 'react'; 2 | import { Button } from 'react-daisyui'; 3 | import { toast } from 'react-hot-toast'; 4 | import { useTranslation } from 'react-i18next'; 5 | import { MdOutlineVolumeUp, MdStop } from 'react-icons/md'; 6 | 7 | type Props = { 8 | language: string; 9 | text: string; 10 | } & React.ComponentPropsWithoutRef; 11 | 12 | export function TTSButton(props: Props) { 13 | const { language, text, ...restProps } = props; 14 | const { t } = useTranslation(); 15 | const [recording, setRecording] = useState(false); 16 | const utterance = useMemo(() => new SpeechSynthesisUtterance(), []); 17 | 18 | useEffect(() => { 19 | utterance.lang = language === 'wyw' ? 'zh-TW' : language; 20 | utterance.volume = 1; 21 | utterance.rate = 1; 22 | utterance.pitch = 1; 23 | utterance.text = text; 24 | utterance.onend = () => { 25 | setRecording(false); 26 | window.speechSynthesis.cancel(); 27 | }; 28 | utterance.onerror = () => { 29 | toast.error(t('Something went wrong, please try again later.')); 30 | setRecording(false); 31 | window.speechSynthesis.cancel(); 32 | }; 33 | utterance.onstart = () => { 34 | setRecording(true); 35 | }; 36 | }, [language, t, text, utterance]); 37 | 38 | const onClickTTSBtn = useCallback(() => { 39 | if (recording) { 40 | window.speechSynthesis.pause(); 41 | window.speechSynthesis.cancel(); 42 | } else { 43 | window.speechSynthesis.cancel(); 44 | window.speechSynthesis.speak(utterance); 45 | } 46 | }, [recording, utterance]); 47 | 48 | // NOTE: This is a workaround for a bug in react-daisyui. 49 | // eslint-disable-next-line react-compiler/react-compiler 50 | (restProps as Record)['type'] = 'button'; 51 | 52 | return ( 53 | 63 | ); 64 | } 65 | -------------------------------------------------------------------------------- /src/components/Header.tsx: -------------------------------------------------------------------------------- 1 | import { Navbar } from 'react-daisyui'; 2 | import { useTranslation } from 'react-i18next'; 3 | import { BsGithub, BsTwitter } from 'react-icons/bs'; 4 | 5 | import { ConfigButton } from '@/components/ConfigButton'; 6 | import { SwitchLanguageButton } from '@/components/SwitchLanguageButton'; 7 | import { ToggleThemeButton } from '@/components/ToggleThemeButton'; 8 | 9 | function AboutModal() { 10 | return ( 11 | <> 12 | 13 | 41 | 42 | ); 43 | } 44 | 45 | function Header() { 46 | const { t } = useTranslation(); 47 | return ( 48 | <> 49 | 50 | 51 |
52 | 55 |
56 |
57 | 58 | 59 | 60 |
61 |
62 | 63 | ); 64 | } 65 | 66 | export default Header; 67 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | @tailwind variants; 5 | 6 | @layer components { 7 | .navbar { 8 | @apply z-50 border-b border-b-base-300 backdrop-blur bg-base-100/80; 9 | } 10 | 11 | .btn { 12 | @apply relative; 13 | 14 | &:before { 15 | @apply absolute -left-0.5 -top-0.5 -right-0.5 -bottom-0.5 content-[''] transition-[background] duration-1000 ease-out bg-center rounded-[inherit]; 16 | } 17 | 18 | &:hover { 19 | &:before { 20 | @apply bg-[length:15000%] bg-[radial-gradient(circle,_transparent_1%,_#00000020_1%)]; 21 | } 22 | } 23 | 24 | &:active { 25 | &:before { 26 | @apply duration-0 bg-[length:100%]; 27 | } 28 | } 29 | } 30 | 31 | .bottom-nav { 32 | @apply border-t border-t-base-300 backdrop-blur bg-base-100/80 fixed inset-x-0 bottom-0 z-50 items-center block h-[calc(48px+env(safe-area-inset-bottom))] rounded-tabs; 33 | 34 | & > * { 35 | @apply gap-0 bg-transparent text-xs leading-normal tracking-[.0125em] font-medium; 36 | 37 | &:not(.active) { 38 | @apply pt-0; 39 | } 40 | 41 | &:where(.active) { 42 | @apply font-bold border-t-0 text-primary; 43 | 44 | & > svg { 45 | @apply rounded-full bg-primary/5; 46 | } 47 | } 48 | 49 | & > svg { 50 | @apply h-8 w-14 p-1.5; 51 | } 52 | } 53 | } 54 | } 55 | 56 | :root { 57 | padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left); 58 | } 59 | 60 | body { 61 | @apply w-full h-full p-0 m-0 mx-auto overscroll-y-none overscroll-x-none; 62 | -ms-overflow-style: none; 63 | scrollbar-width: none; 64 | -webkit-tap-highlight-color: transparent; 65 | -webkit-font-smoothing: antialiased; 66 | -moz-osx-font-smoothing: grayscale; 67 | height: calc(100vh - env(safe-area-inset-top) - env(safe-area-inset-bottom)); 68 | height: calc(100svh - env(safe-area-inset-top) - env(safe-area-inset-bottom)); 69 | max-height: calc(100vh - env(safe-area-inset-top) - env(safe-area-inset-bottom)); 70 | max-height: calc(100svh - env(safe-area-inset-top) - env(safe-area-inset-bottom)); 71 | } 72 | 73 | @supports (-webkit-touch-callout: none) { 74 | body { 75 | /* The hack for Safari */ 76 | height: -webkit-fill-available; 77 | max-height: -webkit-fill-available; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/public/locales/en/translation.json: -------------------------------------------------------------------------------- 1 | { 2 | "topBar": { 3 | "title": "OpenAI Translator", 4 | "darkModeSwitcherTitle": "Switch Dark Mode" 5 | }, 6 | "navbar": { 7 | "Translator": "Translator", 8 | "History records": "History records" 9 | }, 10 | "Please enter your API Key in config page first!": "Please enter your API Key in config page first!", 11 | "Something went wrong, please try again later.": "Something went wrong, please try again later.", 12 | "Please enter the text you want to translate here.": "Please enter the text you want to translate here.", 13 | "Translate": "Translate", 14 | "Translating...": "Translating...", 15 | "Please wait...": "Please wait...", 16 | "Translated text will appear here.": "Translated text will appear here.", 17 | "Model (engine)": "Model (engine)", 18 | "OpenAI API Key": "OpenAI API Key", 19 | "Please enter API Url.": "Please enter API Url.", 20 | "Please enter your API Key.": "Please enter your API Key.", 21 | "Please select a model.": "Please select a model.", 22 | "Config": "Config", 23 | "Config Saved!": "Config Saved!", 24 | "Get your OpenAI API Key": "Get your OpenAI API Key", 25 | "Please paste your OpenAI API Key here.": "Please paste your OpenAI API Key here.", 26 | "Save": "Save", 27 | "Cancel": "Cancel", 28 | "Yes": "Yes", 29 | "Copy original text": "Copy original text", 30 | "Copy translation": "Copy translation", 31 | "No history record.": "No history record.", 32 | "Delete this record": "Delete this record", 33 | "Do you really want to clear all history?": "Do you really want to clear all history?", 34 | "Notice!": "Notice!", 35 | "Clear All": "Clear All", 36 | "History Record": "History Record", 37 | "Delete history record successfully.": "Delete history record successfully.", 38 | "Clear history records successfully.": "Clear history records successfully.", 39 | "Copy original text successfully.": "Copy original text successfully.", 40 | "Copy translation successfully.": "Copy translation successfully.", 41 | "Temperature": "Temperature", 42 | "Higher temperature will be more creative.": "Higher temperature will be more creative.", 43 | "Use stream (typing effect)": "Use stream (typing effect)", 44 | "Reset to default": "Reset to default", 45 | "Don't forget to click the save button for the settings to take effect!": "Don't forget to click the save button for the settings to take effect!", 46 | "Close": "Close", 47 | "Change Language": "Change Language", 48 | "Nothing to copy!": "Nothing to copy!", 49 | "Copied!": "Copied!", 50 | "Failed to copy!": "Failed to copy!", 51 | "Copy translated text": "Copy translated text" 52 | } 53 | -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable camelcase */ 2 | import { resolve } from 'node:path'; 3 | 4 | import react from '@vitejs/plugin-react'; 5 | import { ConfigEnv, loadEnv, UserConfig } from 'vite'; 6 | import { ManifestOptions, VitePWA, VitePWAOptions } from 'vite-plugin-pwa'; 7 | import svgr from 'vite-plugin-svgr'; 8 | 9 | const ReactCompilerConfig = { 10 | target: '19', 11 | }; 12 | 13 | const pwaOptions: Partial = { 14 | registerType: 'autoUpdate', 15 | categories: ['education', 'utilities'], 16 | description: 17 | 'A translator app built using OpenAI GPT model to translate between languages. It is a PWA that can be installed on your phone or desktop.', 18 | manifest: { 19 | short_name: 'OpenAI Translator', 20 | name: 'OpenAI Translator', 21 | display: 'standalone', 22 | icons: [ 23 | { 24 | src: 'icons/icon-192x192.png', 25 | sizes: '192x192', 26 | type: 'image/png', 27 | }, 28 | { 29 | src: 'icons/icon-512x512.png', 30 | sizes: '512x512', 31 | type: 'image/png', 32 | }, 33 | { 34 | purpose: 'maskable', 35 | src: 'icons/icon-192x192.png', 36 | sizes: '192x192', 37 | type: 'image/png', 38 | }, 39 | { 40 | purpose: 'maskable', 41 | src: 'icons/icon-512x512.png', 42 | sizes: '512x512', 43 | type: 'image/png', 44 | }, 45 | ], 46 | start_url: '/', 47 | theme_color: '#ffffff', 48 | background_color: '#ffffff', 49 | }, 50 | includeAssets: ['openai-translator-apple-touch-icon.png', 'favicon.png', 'locales/**/*.json', 'icons/*.{png,svg}'], 51 | }; 52 | 53 | // https://vitejs.dev/config/ 54 | 55 | // local mode: development | test 56 | // publishing mode: pre | prod 57 | 58 | export default async function ({ command, mode }: ConfigEnv): Promise { 59 | const env = loadEnv(mode, __dirname); 60 | 61 | return { 62 | server: { 63 | open: true, 64 | }, 65 | base: env['VITE_PUBLIC_PATH'], 66 | root: resolve(__dirname, 'src'), 67 | build: { 68 | // Specified by the relative path from root (= ./) 69 | outDir: '../dist', 70 | emptyOutDir: true, 71 | }, 72 | plugins: [ 73 | react({ 74 | babel: { 75 | plugins: [['babel-plugin-react-compiler', ReactCompilerConfig]], 76 | }, 77 | }), 78 | svgr(), 79 | VitePWA(pwaOptions), 80 | ], 81 | resolve: { 82 | alias: { 83 | '@/': `${__dirname}/src/`, 84 | }, 85 | }, 86 | define: { 87 | BUILD_TIME: JSON.stringify(new Date().toISOString()), 88 | }, 89 | assetsInclude: ['favicon.png', 'openai-translator-apple-touch-icon.png', 'locales/**/*.json', 'icons/*.{png,svg}'], 90 | }; 91 | } 92 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "openai-translator-web", 3 | "private": false, 4 | "version": "0.3.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite --host", 8 | "build": "tsc && vite build", 9 | "prepare": "husky", 10 | "preview": "vite preview", 11 | "prod": "pnpm build && pnpx serve -s dist", 12 | "lint": "eslint", 13 | "lint:fix": "eslint --fix", 14 | "format": "prettier --write ." 15 | }, 16 | "dependencies": { 17 | "@headlessui/react": "^2.2.9", 18 | "@mantine/hooks": "^7.17.8", 19 | "@microsoft/fetch-event-source": "^2.0.1", 20 | "@popperjs/core": "^2.11.8", 21 | "@tanstack/react-query": "^5.90.12", 22 | "axios": "^1.13.2", 23 | "clsx": "^2.1.1", 24 | "csstype": "^3.2.3", 25 | "daisyui": "^4.12.24", 26 | "i18next": "^24.2.3", 27 | "i18next-http-backend": "^3.0.2", 28 | "react": "^19.2.3", 29 | "react-daisyui": "^5.0.5", 30 | "react-dom": "^19.2.3", 31 | "react-hot-toast": "^2.6.0", 32 | "react-i18next": "^15.7.4", 33 | "react-icons": "^5.5.0", 34 | "react-router-dom": "^7.10.1", 35 | "react-speech-recognition": "^3.10.0", 36 | "react-string-replace": "^1.1.1", 37 | "react-textarea-autosize": "^8.5.9", 38 | "regenerator-runtime": "^0.14.1", 39 | "tailwind-merge": "^2.6.0", 40 | "workbox-build": "^7.4.0", 41 | "zustand": "^5.0.9" 42 | }, 43 | "devDependencies": { 44 | "@eslint/js": "^9.39.2", 45 | "@types/react": "^19.2.7", 46 | "@types/react-dom": "^19.2.3", 47 | "@types/react-speech-recognition": "^3.9.6", 48 | "@vitejs/plugin-react": "^4.7.0", 49 | "autoprefixer": "^10.4.23", 50 | "babel-plugin-react-compiler": "19.0.0-beta-201e55d-20241215", 51 | "eslint": "^9.39.2", 52 | "eslint-config-prettier": "^9.1.2", 53 | "eslint-import-resolver-typescript": "^3.10.1", 54 | "eslint-plugin-import": "^2.32.0", 55 | "eslint-plugin-react": "^7.37.5", 56 | "eslint-plugin-react-compiler": "19.0.0-beta-201e55d-20241215", 57 | "eslint-plugin-react-hooks": "^5.2.0", 58 | "eslint-plugin-react-refresh": "^0.4.25", 59 | "eslint-plugin-simple-import-sort": "^12.1.1", 60 | "globals": "^15.15.0", 61 | "husky": "^9.1.7", 62 | "lint-staged": "^15.5.2", 63 | "postcss": "^8.5.6", 64 | "postcss-100vh-fix": "^1.0.2", 65 | "prettier": "^3.7.4", 66 | "tailwindcss": "^3.4.19", 67 | "typescript": "^5.9.3", 68 | "typescript-eslint": "^8.50.0", 69 | "vite": "^6.4.1", 70 | "vite-plugin-pwa": "^0.21.2", 71 | "vite-plugin-svgr": "^4.5.0", 72 | "workbox-core": "^7.4.0", 73 | "workbox-precaching": "^7.4.0", 74 | "workbox-routing": "^7.4.0", 75 | "workbox-window": "^7.4.0" 76 | }, 77 | "lint-staged": { 78 | "**/*": "prettier --write --ignore-unknown" 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | import react from 'eslint-plugin-react'; 2 | import js from '@eslint/js'; 3 | import globals from 'globals'; 4 | import reactHooks from 'eslint-plugin-react-hooks'; 5 | import reactRefresh from 'eslint-plugin-react-refresh'; 6 | import tseslint from 'typescript-eslint'; 7 | import simpleImportSort from 'eslint-plugin-simple-import-sort'; 8 | import importPlugin from 'eslint-plugin-import'; 9 | import reactCompiler from 'eslint-plugin-react-compiler'; 10 | 11 | export default tseslint.config( 12 | { ignores: ['dist', 'vite.config.ts', '**/env.d.ts', '**/vite-env.d.ts'] }, 13 | { 14 | extends: [js.configs.recommended, ...tseslint.configs.recommended, importPlugin.flatConfigs.recommended], 15 | settings: { 16 | react: { 17 | version: 'detect', 18 | }, 19 | 20 | 'import/resolver': { 21 | typescript: {}, 22 | }, 23 | }, 24 | files: ['**/*.{ts,tsx}'], 25 | languageOptions: { 26 | ecmaVersion: 'latest', 27 | sourceType: 'module', 28 | globals: { ...globals.browser }, 29 | parserOptions: { 30 | ecmaFeatures: { 31 | jsx: true, 32 | }, 33 | }, 34 | }, 35 | plugins: { 36 | react, 37 | 'react-hooks': reactHooks, 38 | 'react-compiler': reactCompiler, 39 | 'react-refresh': reactRefresh, 40 | 'simple-import-sort': simpleImportSort, 41 | }, 42 | rules: { 43 | ...react.configs.recommended.rules, 44 | ...reactHooks.configs.recommended.rules, 45 | 'react-compiler/react-compiler': 'error', 46 | 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }], 47 | 48 | 'react/react-in-jsx-scope': 'off', 49 | camelcase: 'error', 50 | 'spaced-comment': 'error', 51 | quotes: ['error', 'single'], 52 | 'no-duplicate-imports': 'error', 53 | 'no-empty-function': 'off', 54 | '@typescript-eslint/no-empty-function': 'warn', 55 | 'sort-imports': 'off', 56 | 'import/order': 'off', 57 | 'simple-import-sort/imports': 'error', 58 | 'simple-import-sort/exports': 'error', 59 | 'import/first': 'error', 60 | 'import/newline-after-import': 'off', 61 | 'import/no-duplicates': 'error', 62 | '@next/next/no-img-element': 'off', 63 | 'brace-style': ['error', '1tbs'], 64 | curly: ['error', 'all'], 65 | 66 | 'react/jsx-curly-brace-presence': [ 67 | 'error', 68 | { 69 | props: 'never', 70 | }, 71 | ], 72 | 73 | 'object-shorthand': 'error', 74 | 'no-unused-vars': 'off', 75 | '@typescript-eslint/no-unused-vars': 'warn', 76 | 'prefer-arrow-callback': 'error', 77 | 'react/function-component-definition': [ 78 | 2, 79 | { namedComponents: 'function-declaration', unnamedComponents: 'arrow-function' }, 80 | ], 81 | 'react-hooks/rules-of-hooks': 'error', 82 | 'react-hooks/exhaustive-deps': 'warn', 83 | 'no-irregular-whitespace': 'off', 84 | 'import/no-unresolved': ['error', { ignore: ['^virtual:'] }], 85 | }, 86 | }, 87 | ); 88 | -------------------------------------------------------------------------------- /src/hooks/useChatGPTStream.ts: -------------------------------------------------------------------------------- 1 | import { useCallback, useState } from 'react'; 2 | 3 | import OpenAIClient from '@/client'; 4 | import { CHAT_MODELS, type ChatModel, type OpenAIModel } from '@/constants'; 5 | 6 | function getRadomNumber(min: number, max: number) { 7 | return Math.random() * (max - min) + min; 8 | } 9 | 10 | export function useChatGPTStream() { 11 | const [data, setData] = useState(''); 12 | const [error, setError] = useState(''); 13 | const [loading, setLoading] = useState(false); 14 | 15 | const mutate = useCallback( 16 | (params: { token: string; engine: OpenAIModel; prompt: string; temperatureParam: number; queryText: string }) => { 17 | const { token, engine, prompt, queryText, temperatureParam } = params; 18 | if (loading) { 19 | console.warn('Already loading!'); 20 | return; 21 | } 22 | setData(''); 23 | setLoading(true); 24 | if (!token) { 25 | setError('No API Key found!'); 26 | setLoading(false); 27 | return; 28 | } 29 | if (!prompt) { 30 | setError('No prompt found!'); 31 | setLoading(false); 32 | return; 33 | } 34 | 35 | const tmpParam = 36 | +temperatureParam > 0.4 && +temperatureParam <= 1.0 ? +temperatureParam : getRadomNumber(0.5, 1.0); 37 | 38 | const isChatModel = CHAT_MODELS.includes(engine as ChatModel); 39 | 40 | OpenAIClient.chatCompletionsStream( 41 | { 42 | token, 43 | prompt, 44 | query: queryText, 45 | model: isChatModel ? (engine as ChatModel) : 'gpt-4o-mini', 46 | temperature: tmpParam, 47 | }, 48 | { 49 | async onopen(res) { 50 | setData(''); 51 | setLoading(true); 52 | if (res.ok && res.status === 200) { 53 | console.log('Connection made ', res.status); 54 | setError(''); 55 | } else if (res.status >= 400 && res.status < 500 && res.status !== 429) { 56 | console.warn('Client side error ', res); 57 | setError('Client side error ' + res.status); 58 | setLoading(false); 59 | } 60 | }, 61 | onmessage(event) { 62 | if (event.data === '[DONE]') { 63 | setError(''); 64 | setLoading(false); 65 | return; 66 | } 67 | const parsedData = JSON.parse(event.data) as ChatCompletionsResponse; 68 | const text = parsedData.choices.map((choice) => choice.delta?.content || '').join(''); 69 | setData((prev) => prev + text); 70 | }, 71 | onclose() { 72 | setError(''); 73 | setLoading(false); 74 | }, 75 | onerror(err) { 76 | setError(err); 77 | setLoading(false); 78 | }, 79 | }, 80 | ).catch((err) => { 81 | setError(err); 82 | setLoading(false); 83 | }); 84 | }, 85 | [loading], 86 | ); 87 | return { data, mutate, isError: !!error, isLoading: loading }; 88 | } 89 | -------------------------------------------------------------------------------- /src/components/SwitchLanguageButton.tsx: -------------------------------------------------------------------------------- 1 | import { useClickOutside, useLocalStorage } from '@mantine/hooks'; 2 | import clsx from 'clsx'; 3 | import { useEffect, useState } from 'react'; 4 | import { Badge, Button } from 'react-daisyui'; 5 | import { useTranslation } from 'react-i18next'; 6 | import { FaSortDown } from 'react-icons/fa'; 7 | import { IoLanguage } from 'react-icons/io5'; 8 | 9 | const LANGUAGES = [ 10 | { 11 | code: 'en', 12 | name: 'English', 13 | icon: ( 14 | 15 | EN 16 | 17 | ), 18 | }, 19 | { 20 | code: 'zh', 21 | name: '简体中文', 22 | icon: ( 23 | 24 | ZH 25 | 26 | ), 27 | }, 28 | { 29 | code: 'zh-TW', 30 | name: '正體中文', 31 | icon: ( 32 | 33 | ZH 34 | 35 | ), 36 | }, 37 | { 38 | code: 'ja', 39 | name: '日本語', 40 | icon: ( 41 | 42 | JA 43 | 44 | ), 45 | }, 46 | ] as const; 47 | 48 | type LanguageCode = (typeof LANGUAGES)[number]['code']; 49 | 50 | export function SwitchLanguageButton() { 51 | const { t, i18n } = useTranslation(); 52 | const ref = useClickOutside(() => setIsMenuOpen(false)); 53 | const [lang, setLang] = useLocalStorage({ 54 | key: 'langCode', 55 | defaultValue: 'zh', 56 | getInitialValueInEffect: false, 57 | }); 58 | const [isMenuOpen, setIsMenuOpen] = useState(false); 59 | 60 | useEffect(() => { 61 | document.documentElement.setAttribute('lang', lang); 62 | i18n.changeLanguage(lang); 63 | }, [i18n, lang]); 64 | 65 | useEffect(() => { 66 | if (!isMenuOpen && document.activeElement) { 67 | const elem = document.activeElement as HTMLElement; 68 | elem.blur(); 69 | } 70 | }, [isMenuOpen]); 71 | 72 | return ( 73 |
74 | 85 | 103 |
104 | ); 105 | } 106 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Cloudflare](https://img.shields.io/badge/Cloudflare-F38020?style=for-the-badge&logo=Cloudflare&logoColor=white) 2 | ![TypeScript](https://img.shields.io/badge/typescript-%23007ACC.svg?style=for-the-badge&logo=typescript&logoColor=white) 3 | ![React](https://img.shields.io/badge/react-%2320232a.svg?style=for-the-badge&logo=react&logoColor=%2361DAFB) 4 | ![Vite](https://img.shields.io/badge/vite-%23646CFF.svg?style=for-the-badge&logo=vite&logoColor=white) 5 | ![TailwindCSS](https://img.shields.io/badge/tailwindcss-%2338B2AC.svg?style=for-the-badge&logo=tailwind-css&logoColor=white) 6 | ![React Router](https://img.shields.io/badge/React_Router-CA4245?style=for-the-badge&logo=react-router&logoColor=white) 7 | ![React Query](https://img.shields.io/badge/-React%20Query-FF4154?style=for-the-badge&logo=react%20query&logoColor=white) 8 | 9 | # OpenAI Translator 10 | 11 | A translator app built using OpenAI GPT model to translate between languages. It is a PWA that can be installed on your phone or desktop. 12 | 13 | https://translator.lance.moe/ 14 | 15 | Support models: 16 | 17 | - GPT-4o 18 | - GPT-4o Mini 19 | - GPT-4 Turbo 20 | - GPT-4 21 | - GPT-3.5 Turbo 22 | - And other OpenAI LLM models 23 | 24 | image 25 | 26 | image 27 | 28 | ## Tech Stack 29 | 30 | - OpenAI API 31 | - React 19 32 | - Vite 6 33 | - Tailwind CSS 3 34 | - DaisyUI 4 35 | - Axios 36 | - React Router 7 37 | - React Query 5 38 | - PWA 39 | - Cloudflare Pages 40 | 41 | I think this project will help you learn these techniques. 42 | 43 | If you like this project, please don't forget to give this project a star, thanks. 44 | 45 | ## Local Development 46 | 47 | ### 1. Install pnpm 48 | 49 | Make sure that pnpm is installed on your computer. If it's not already installed, you can install it: 50 | 51 | https://pnpm.io/installation 52 | 53 | ### 2. Download project dependencies 54 | 55 | Navigate to the root directory of your project and run the following command to download project dependencies: 56 | 57 | ```bash 58 | pnpm install 59 | ``` 60 | 61 | ### 3. Start the local server 62 | 63 | Run the following command to start the local development server: 64 | 65 | ```bash 66 | pnpm dev 67 | ``` 68 | 69 | ### 4. Open the application 70 | 71 | Vite should automatically open your browser. 72 | 73 | ## Build the Project 74 | 75 | ### Docker Build 76 | 77 | #### 1. Run docker build 78 | 79 | Navigate to the root directory of your project in your command line interface and run the following command to build the Docker image: 80 | 81 | ```bash 82 | docker build -t openai-translator-web . 83 | ``` 84 | 85 | Here, `openai-translator-web` is the name you want to give to the image, and the `.` at the end indicates the current directory. 86 | 87 | #### 2. Start the Container 88 | 89 | Run the following command to start the container and map the port to your local machine: 90 | 91 | ```bash 92 | docker run -p 3000:80 openai-translator-web 93 | ``` 94 | 95 | Here, 3000 represents the local port you want to map to the container's 80 port. You can change this to any other port you prefer. 96 | 97 | #### 3. Open the Application 98 | 99 | In your browser, enter the following URL to access the application: 100 | 101 | http://localhost:3000/ 102 | 103 | ### Local Build 104 | 105 | #### 1. Install pnpm 106 | 107 | Make sure that pnpm is installed on your computer. If it's not already installed, you can install it: 108 | 109 | https://pnpm.io/installation 110 | 111 | #### 2. Download project dependencies 112 | 113 | Navigate to the root directory of your project and run the following command to download project dependencies: 114 | 115 | ```bash 116 | pnpm install 117 | ``` 118 | 119 | #### 3. Build 120 | 121 | Run the following command to build your project: 122 | 123 | ```bash 124 | pnpm build 125 | ``` 126 | 127 | The compiled files will be placed in the `dist` folder. 128 | 129 | #### 4. Deploy 130 | 131 | Now you can treat the files in the `dist` folder as a static website and deploy it on the server. 132 | 133 | ## Credit 134 | 135 | - Inspired by https://github.com/yetone/bob-plugin-openai-translator 136 | -------------------------------------------------------------------------------- /src/client/index.ts: -------------------------------------------------------------------------------- 1 | import { fetchEventSource, FetchEventSourceInit } from '@microsoft/fetch-event-source'; 2 | import axios from 'axios'; 3 | 4 | import apis from '@/client/apis'; 5 | import type { ChatModel, OpenAIModel } from '@/constants'; 6 | 7 | const { endpoints, baseUrl } = apis; 8 | 9 | const client = axios.create({ baseURL: baseUrl }); 10 | 11 | export function setApiBaseUrl(url: string) { 12 | client.defaults.baseURL = url; 13 | } 14 | 15 | export async function completions( 16 | token: string, 17 | prompt: string, 18 | query: string, 19 | model: Omit = 'text-davinci-003', 20 | temperature = 0, 21 | maxTokens = 1000, 22 | topP = 1, 23 | frequencyPenalty = 1, 24 | presencePenalty = 1, 25 | ) { 26 | const { url, headers } = endpoints.v1.completions; 27 | const config = { 28 | headers: { 29 | ...headers, 30 | Authorization: `Bearer ${token}`, 31 | }, 32 | }; 33 | 34 | const body = { 35 | prompt: `${prompt}:\n\n"${query}" =>`, 36 | model, 37 | temperature, 38 | // eslint-disable-next-line camelcase 39 | max_tokens: maxTokens, 40 | // eslint-disable-next-line camelcase 41 | top_p: topP, 42 | // eslint-disable-next-line camelcase 43 | frequency_penalty: frequencyPenalty, 44 | // eslint-disable-next-line camelcase 45 | presence_penalty: presencePenalty, 46 | }; 47 | 48 | const response = await client.post(url, body, config); 49 | return response; 50 | } 51 | 52 | export async function chatCompletions( 53 | token: string, 54 | prompt: string, 55 | query: string, 56 | model: ChatModel = 'gpt-4o-mini', 57 | temperature = 0, 58 | maxTokens = 1000, 59 | topP = 1, 60 | frequencyPenalty = 1, 61 | presencePenalty = 1, 62 | ) { 63 | const { url, headers } = endpoints.v1.chat.completions; 64 | const config = { 65 | headers: { 66 | ...headers, 67 | Authorization: `Bearer ${token}`, 68 | }, 69 | }; 70 | 71 | const body = { 72 | model, 73 | temperature, 74 | // eslint-disable-next-line camelcase 75 | max_tokens: maxTokens, 76 | // eslint-disable-next-line camelcase 77 | top_p: topP, 78 | // eslint-disable-next-line camelcase 79 | frequency_penalty: frequencyPenalty, 80 | // eslint-disable-next-line camelcase 81 | presence_penalty: presencePenalty, 82 | messages: [ 83 | { role: 'system', content: prompt }, 84 | { role: 'user', content: `"${query}"` }, 85 | ], 86 | }; 87 | 88 | const response = await client.post(url, body, config); 89 | return response; 90 | } 91 | 92 | export async function chatCompletionsStream( 93 | params: { 94 | token: string; 95 | prompt: string; 96 | query: string; 97 | model?: ChatModel; 98 | temperature?: number; 99 | maxTokens?: number; 100 | topP?: number; 101 | frequencyPenalty?: number; 102 | presencePenalty?: number; 103 | }, 104 | options: FetchEventSourceInit, 105 | ) { 106 | const { 107 | token, 108 | prompt, 109 | query, 110 | model = 'gpt-4o-mini', 111 | temperature = 0, 112 | maxTokens = 1000, 113 | topP = 1, 114 | frequencyPenalty = 1, 115 | presencePenalty = 1, 116 | } = params; 117 | const { url, headers } = endpoints.v1.chat.completions; 118 | 119 | const body = { 120 | model, 121 | temperature, 122 | // eslint-disable-next-line camelcase 123 | max_tokens: maxTokens, 124 | // eslint-disable-next-line camelcase 125 | top_p: topP, 126 | // eslint-disable-next-line camelcase 127 | frequency_penalty: frequencyPenalty, 128 | // eslint-disable-next-line camelcase 129 | presence_penalty: presencePenalty, 130 | stream: true, 131 | messages: [ 132 | { role: 'system', content: prompt }, 133 | { role: 'system', content: 'Please note that your response should solely consist of the translation.' }, 134 | { role: 'user', content: query }, 135 | ], 136 | }; 137 | const response = await fetchEventSource(baseUrl + url, { 138 | method: 'POST', 139 | body: JSON.stringify(body), 140 | headers: { 141 | ...headers, 142 | Authorization: `Bearer ${token}`, 143 | }, 144 | openWhenHidden: true, 145 | ...options, 146 | }); 147 | return response; 148 | } 149 | 150 | export default { 151 | setApiBaseUrl, 152 | completions, 153 | chatCompletions, 154 | chatCompletionsStream, 155 | }; 156 | -------------------------------------------------------------------------------- /src/constants/index.ts: -------------------------------------------------------------------------------- 1 | import { getKeys } from '@/utils'; 2 | 3 | export const CHAT_MODELS_TITLES = { 4 | // Chat models 5 | 'gpt-4o-mini': 'GPT-4o-Mini (recommended)', 6 | 'gpt-4o': 'GPT-4o', 7 | 'gpt-4-turbo': 'GPT-4-Turbo', 8 | 'gpt-4': 'GPT-4', 9 | 'gpt-3.5-turbo': 'GPT-3.5-Turbo', 10 | 'gpt-4o-mini-2024-07-18': 'GPT-4o-Mini (2024-07-18)', 11 | 'gpt-4o-2024-08-06': 'GPT-4o (2024-08-06)', 12 | 'gpt-4o-2024-05-13': 'GPT-4o (2024-05-13)', 13 | 'gpt-4-turbo-preview': 'GPT-4-Turbo Preview', 14 | 'gpt-4-turbo-2024-04-09': 'GPT-4-Turbo (2024-04-09)', 15 | 'gpt-4-1106-preview': 'GPT-4 (1106 Preview)', 16 | 'gpt-4-0613': 'GPT-4 (0613)', 17 | 'gpt-4-0125-preview': 'GPT-4 (0125 Preview)', 18 | 'gpt-3.5-turbo-16k': 'GPT-3.5-Turbo (16k)', 19 | 'gpt-3.5-turbo-1106': 'GPT-3.5-Turbo (1106)', 20 | 'gpt-3.5-turbo-0125': 'GPT-3.5-Turbo (0125)', 21 | 'chatgpt-4o-latest': 'ChatGPT-4o Latest', 22 | // Reasoning models 23 | 'o1-mini': 'o1-Mini', 24 | 'o1-preview': 'o1-Preview', 25 | 'o1-mini-2024-09-12': 'o1o1-Mini (2024-09-12)', 26 | 'o1-preview-2024-09-12': 'o1 Preview (2024-09-12)', 27 | } as const; 28 | 29 | const COMPLETIONS_MODELS_TITLES = { 30 | // Completions models 31 | 'gpt-3.5-turbo-instruct': 'GPT-3.5-Turbo Instruct', 32 | 'gpt-3.5-turbo-instruct-0914': 'GPT-3.5-Turbo Instruct (0914)', 33 | 'babbage-002': 'Babbage-002', 34 | 'text-davinci-002': 'Text-Davinci-002', 35 | } as const; 36 | 37 | export const OPENAI_MODELS_TITLES = { 38 | ...CHAT_MODELS_TITLES, 39 | ...COMPLETIONS_MODELS_TITLES, 40 | } as const; 41 | 42 | export type ChatModel = keyof typeof CHAT_MODELS_TITLES; 43 | export type CompletionsModel = keyof typeof COMPLETIONS_MODELS_TITLES; 44 | export type OpenAIModel = keyof typeof OPENAI_MODELS_TITLES; 45 | 46 | export const CHAT_MODELS = getKeys(CHAT_MODELS_TITLES); 47 | export const COMPLETIONS_MODELS = getKeys(COMPLETIONS_MODELS_TITLES); 48 | export const OPENAI_MODELS = getKeys(OPENAI_MODELS_TITLES); 49 | 50 | export const LANGUAGES = { 51 | auto: 'Auto', 52 | 'zh-Hans': '简体中文', 53 | 'zh-Hant': '正體中文', 54 | en: 'English', 55 | yue: '粵語', 56 | wyw: '漢文', 57 | ja: '日本語', 58 | ko: '한국어', 59 | fr: 'Français', 60 | de: 'Deutsch', 61 | es: 'Español', 62 | it: 'Italiano', 63 | ru: 'Русский', 64 | pt: 'Português', 65 | nl: 'Nederlands', 66 | pl: 'Polski', 67 | ar: 'العربية', 68 | af: 'Afrikaans', 69 | am: 'Amharic', 70 | az: 'Azerbaijani', 71 | be: 'Belarusian', 72 | bg: 'Bulgarian', 73 | bn: 'Bengali', 74 | bs: 'Bosnian', 75 | ca: 'Catalan', 76 | ceb: 'Cebuano', 77 | co: 'Corsican', 78 | cs: 'Czech', 79 | cy: 'Welsh', 80 | da: 'Danish', 81 | el: 'Greek', 82 | eo: 'Esperanto', 83 | et: 'Estonian', 84 | eu: 'Basque', 85 | fa: 'Persian', 86 | fi: 'Finnish', 87 | fj: 'Fijian', 88 | fy: 'Frisian', 89 | ga: 'Irish', 90 | gd: 'Scots Gaelic', 91 | gl: 'Galician', 92 | gu: 'Gujarati', 93 | ha: 'Hausa', 94 | haw: 'Hawaiian', 95 | he: 'Hebrew', 96 | hi: 'Hindi', 97 | hmn: 'Hmong', 98 | hr: 'Croatian', 99 | ht: 'Haitian Creole', 100 | hu: 'Hungarian', 101 | hy: 'Armenian', 102 | id: 'Indonesian', 103 | ig: 'Igbo', 104 | is: 'Icelandic', 105 | jw: 'Javanese', 106 | ka: 'Georgian', 107 | kk: 'Kazakh', 108 | km: 'Khmer', 109 | kn: 'Kannada', 110 | ku: 'Kurdish', 111 | ky: 'Kyrgyz', 112 | la: 'Latin', 113 | lb: 'Luxembourgish', 114 | lo: 'Lao', 115 | lt: 'Lithuanian', 116 | lv: 'Latvian', 117 | mg: 'Malagasy', 118 | mi: 'Maori', 119 | mk: 'Macedonian', 120 | ml: 'Malayalam', 121 | mn: 'Mongolian', 122 | mr: 'Marathi', 123 | ms: 'Malay', 124 | mt: 'Maltese', 125 | my: 'Burmese', 126 | ne: 'Nepali', 127 | no: 'Norwegian', 128 | ny: 'Chichewa', 129 | or: 'Odia', 130 | pa: 'Punjabi', 131 | ps: 'Pashto', 132 | ro: 'Romanian', 133 | rw: 'Kinyarwanda', 134 | si: 'Sinhala', 135 | sk: 'Slovak', 136 | sl: 'Slovenian', 137 | sm: 'Samoan', 138 | sn: 'Shona', 139 | so: 'Somali', 140 | sq: 'Albanian', 141 | sr: 'Serbian', 142 | 'sr-Cyrl': 'Serbian Cyrillic', 143 | 'sr-Latn': 'Serbian Latin', 144 | st: 'Sesotho', 145 | su: 'Sundanese', 146 | sv: 'Swedish', 147 | sw: 'Swahili', 148 | ta: 'Tamil', 149 | te: 'Telugu', 150 | tg: 'Tajik', 151 | th: 'Thai', 152 | tk: 'Turkmen', 153 | tl: 'Tagalog', 154 | tr: 'Turkish', 155 | tt: 'Tatar', 156 | ug: 'Uyghur', 157 | uk: 'Ukrainian', 158 | ur: 'Urdu', 159 | uz: 'Uzbek', 160 | vi: 'Vietnamese', 161 | xh: 'Xhosa', 162 | yi: 'Yiddish', 163 | yo: 'Yoruba', 164 | zu: 'Zulu', 165 | } as const; 166 | 167 | export type Language = keyof typeof LANGUAGES; 168 | 169 | export type ConfigValues = { 170 | openaiApiUrl: string; 171 | openaiApiKey: string; 172 | streamEnabled: boolean; 173 | currentModel: OpenAIModel; 174 | temperatureParam: number; 175 | }; 176 | -------------------------------------------------------------------------------- /src/components/GlobalStore.tsx: -------------------------------------------------------------------------------- 1 | import { useLocalStorage } from '@mantine/hooks'; 2 | import { createContext, Dispatch, SetStateAction, useContext, useEffect, useMemo, useState } from 'react'; 3 | 4 | import { setApiBaseUrl } from '@/client'; 5 | import { fetchTranslation } from '@/client/fetcher'; 6 | import { type ConfigValues } from '@/constants'; 7 | import { useQueryApi } from '@/hooks/useQueryApi'; 8 | 9 | type GlobalContextValue = { 10 | configValues: ConfigValues; 11 | setConfigValues: Dispatch>; 12 | translator: { 13 | lastTranslateData: LastTranslateData; 14 | setLastTranslateData: Dispatch>; 15 | translateText: string; 16 | setTranslateText: Dispatch>; 17 | translatedText: string | undefined; 18 | mutateTranslateText: (data: Parameters[0]) => void; 19 | isTranslating: boolean; 20 | isTranslateError: boolean; 21 | }; 22 | history: { 23 | historyRecords: HistoryRecord[]; 24 | setHistoryRecords: Dispatch>; 25 | }; 26 | }; 27 | 28 | const context = createContext({ 29 | configValues: { 30 | openaiApiUrl: 'https://api.openai.com', 31 | openaiApiKey: '', 32 | streamEnabled: true, 33 | currentModel: 'gpt-4o-mini', 34 | temperatureParam: 0.7, 35 | }, 36 | setConfigValues: () => undefined, 37 | translator: { 38 | lastTranslateData: { 39 | fromLang: 'auto', 40 | toLang: 'auto', 41 | }, 42 | setLastTranslateData: () => undefined, 43 | translateText: '', 44 | setTranslateText: () => undefined, 45 | translatedText: undefined, 46 | mutateTranslateText: () => undefined, 47 | isTranslating: false, 48 | isTranslateError: false, 49 | }, 50 | history: { 51 | historyRecords: [], 52 | setHistoryRecords: () => undefined, 53 | }, 54 | }); 55 | 56 | type Props = { 57 | children: React.ReactNode; 58 | }; 59 | 60 | export function GlobalProvider(props: Props) { 61 | const { children } = props; 62 | const [translateText, setTranslateText] = useState(''); 63 | const [historyRecords, setHistoryRecords] = useLocalStorage({ 64 | key: 'history-record', 65 | defaultValue: [], 66 | getInitialValueInEffect: false, 67 | }); 68 | const [lastTranslateData, setLastTranslateData] = useLocalStorage({ 69 | key: 'last-translate-data', 70 | defaultValue: { 71 | fromLang: 'auto', 72 | toLang: 'auto', 73 | }, 74 | getInitialValueInEffect: false, 75 | }); 76 | const [configValues, setConfigValues] = useLocalStorage({ 77 | key: 'extra-config', 78 | defaultValue: { 79 | openaiApiUrl: 'https://api.openai.com', 80 | openaiApiKey: '', 81 | streamEnabled: true, 82 | currentModel: 'gpt-4o-mini', 83 | temperatureParam: 0.7, 84 | }, 85 | getInitialValueInEffect: false, 86 | }); 87 | const { 88 | openaiApiUrl = 'https://api.openai.com', 89 | openaiApiKey = '', 90 | streamEnabled = true, 91 | currentModel = 'gpt-4o-mini', 92 | temperatureParam = 0.7, 93 | } = configValues; 94 | 95 | const { 96 | data: translatedText, 97 | mutate: mutateTranslateText, 98 | isLoading: isTranslating, 99 | isError: isTranslateError, 100 | } = useQueryApi(streamEnabled); 101 | 102 | useEffect(() => setApiBaseUrl(configValues.openaiApiUrl), [configValues.openaiApiUrl]); 103 | 104 | useEffect(() => { 105 | if (!translatedText || isTranslating) { 106 | return; 107 | } 108 | setHistoryRecords((prev) => [ 109 | { 110 | id: self.crypto.randomUUID(), 111 | fromLanguage: lastTranslateData.fromLang, 112 | toLanguage: lastTranslateData.toLang, 113 | text: translateText, 114 | translation: translatedText, 115 | createdAt: Date.now(), 116 | }, 117 | ...prev, 118 | ]); 119 | // Don't need to catch translateText, lastTranslateData.fromLang, lastTranslateData.toLang 120 | // eslint-disable-next-line react-compiler/react-compiler 121 | // eslint-disable-next-line react-hooks/exhaustive-deps 122 | }, [translatedText, isTranslating, setHistoryRecords]); 123 | 124 | const contextValue = useMemo( 125 | () => ({ 126 | configValues: { openaiApiUrl, openaiApiKey, streamEnabled, currentModel, temperatureParam }, 127 | setConfigValues, 128 | translator: { 129 | lastTranslateData, 130 | setLastTranslateData, 131 | translateText, 132 | setTranslateText, 133 | translatedText, 134 | mutateTranslateText, 135 | isTranslating, 136 | isTranslateError, 137 | }, 138 | history: { 139 | historyRecords, 140 | setHistoryRecords, 141 | }, 142 | }), 143 | [ 144 | openaiApiUrl, 145 | openaiApiKey, 146 | streamEnabled, 147 | currentModel, 148 | temperatureParam, 149 | setConfigValues, 150 | lastTranslateData, 151 | setLastTranslateData, 152 | translateText, 153 | translatedText, 154 | mutateTranslateText, 155 | isTranslating, 156 | isTranslateError, 157 | historyRecords, 158 | setHistoryRecords, 159 | ], 160 | ); 161 | 162 | return {children}; 163 | } 164 | 165 | export function useGlobalStore() { 166 | const value = useContext(context); 167 | if (!value) { 168 | throw new Error('useGlobalStore must be used within a GlobalProvider'); 169 | } 170 | return value; 171 | } 172 | -------------------------------------------------------------------------------- /src/pages/HistoryRecord.tsx: -------------------------------------------------------------------------------- 1 | import { t } from 'i18next'; 2 | import { useCallback } from 'react'; 3 | import { Button } from 'react-daisyui'; 4 | import toast from 'react-hot-toast'; 5 | import { useTranslation } from 'react-i18next'; 6 | import { FaEllipsisV, FaTrashAlt } from 'react-icons/fa'; 7 | 8 | import { useGlobalStore } from '@/components/GlobalStore'; 9 | import { TTSButton } from '@/components/TTSButton'; 10 | import { Language, LANGUAGES } from '@/constants'; 11 | import { formatTime } from '@/utils'; 12 | 13 | function HistoryRecord() { 14 | const { i18n } = useTranslation(); 15 | const { 16 | history: { historyRecords, setHistoryRecords }, 17 | } = useGlobalStore(); 18 | 19 | const handleDeleteHistoryRecord = useCallback( 20 | (id: string) => { 21 | (document.activeElement as HTMLElement).blur(); 22 | setHistoryRecords((prev) => prev.filter((record) => record.id !== id)); 23 | toast.success(t('Delete history record successfully.')); 24 | }, 25 | [setHistoryRecords], 26 | ); 27 | 28 | const handleClearHistoryRecords = useCallback(() => { 29 | (document.activeElement as HTMLElement).blur(); 30 | setHistoryRecords([]); 31 | toast.success(t('Clear history records successfully.')); 32 | }, [setHistoryRecords]); 33 | 34 | const handleCopyOriginalText = useCallback( 35 | (id: string) => { 36 | (document.activeElement as HTMLElement).blur(); 37 | const record = historyRecords.find((record) => record.id === id); 38 | if (!record) { 39 | return; 40 | } 41 | navigator.clipboard.writeText(record.text); 42 | toast.success(t('Copy original text successfully.')); 43 | }, 44 | [historyRecords], 45 | ); 46 | 47 | const handleCopyTranslation = useCallback( 48 | (id: string) => { 49 | (document.activeElement as HTMLElement).blur(); 50 | const record = historyRecords.find((record) => record.id === id); 51 | if (!record) { 52 | return; 53 | } 54 | navigator.clipboard.writeText(record.translation); 55 | toast.success(t('Copy translation successfully.')); 56 | }, 57 | [historyRecords], 58 | ); 59 | 60 | return ( 61 |
62 |

63 | {t('History Record')} 64 | {!!historyRecords && !!historyRecords.length && ( 65 |
66 | 70 |
74 |
75 |

{t('Notice!')}

76 |

{t('Do you really want to clear all history?')}

77 |
78 | 81 | 84 |
85 |
86 |
87 |
88 | )} 89 |

90 | 153 |
154 | ); 155 | } 156 | export default HistoryRecord; 157 | -------------------------------------------------------------------------------- /src/pages/Config.tsx: -------------------------------------------------------------------------------- 1 | import { useCallback, useRef } from 'react'; 2 | import { Button, Input, Toggle } from 'react-daisyui'; 3 | import toast from 'react-hot-toast'; 4 | import { useTranslation } from 'react-i18next'; 5 | import { FaTimes } from 'react-icons/fa'; 6 | 7 | import { useGlobalStore } from '@/components/GlobalStore'; 8 | import { OPENAI_MODELS_TITLES, type OpenAIModel } from '@/constants'; 9 | 10 | function ConfigPage() { 11 | const { t } = useTranslation(); 12 | const { 13 | configValues: { openaiApiUrl, openaiApiKey, streamEnabled, currentModel, temperatureParam }, 14 | setConfigValues, 15 | } = useGlobalStore(); 16 | const openaiApiInputRef = useRef(null); 17 | 18 | const handleSave = useCallback( 19 | (event: React.FormEvent) => { 20 | event.preventDefault(); 21 | const formData = new FormData(event.currentTarget); 22 | const { openaiApiUrl, openaiApiKey, streamEnabled, selectedModel, temperatureParam } = Object.fromEntries( 23 | formData.entries(), 24 | ); 25 | if (!openaiApiUrl) { 26 | toast.error(t('Please enter API Url.')); 27 | return; 28 | } 29 | if (!openaiApiKey) { 30 | toast.error(t('Please enter your API Key.')); 31 | return; 32 | } 33 | if (!selectedModel) { 34 | toast.error(t('Please select a model.')); 35 | return; 36 | } 37 | setConfigValues((prev) => ({ 38 | ...prev, 39 | openaiApiUrl: `${openaiApiUrl}`, 40 | openaiApiKey: `${openaiApiKey}`, 41 | streamEnabled: streamEnabled === 'on', 42 | currentModel: selectedModel as OpenAIModel, 43 | temperatureParam: +temperatureParam, 44 | })); 45 | toast.success(t('Config Saved!')); 46 | }, 47 | [setConfigValues, t], 48 | ); 49 | 50 | const handleResetOpenaiApiUrl = useCallback( 51 | (event: React.MouseEvent) => { 52 | event.preventDefault(); 53 | const inputRef = openaiApiInputRef.current; 54 | if (!inputRef) { 55 | return; 56 | } 57 | inputRef.value = 'https://api.openai.com'; 58 | inputRef.focus(); 59 | // eslint-disable-next-line quotes 60 | toast(t("Don't forget to click the save button for the settings to take effect!")); 61 | }, 62 | [t], 63 | ); 64 | 65 | return ( 66 |
67 |

68 | {t('Config')} 69 | 76 |

77 |
78 |
79 | 83 |
84 |
85 | 93 | 102 |
103 |
104 | 117 | 124 |
125 |
126 | 129 | 141 |
142 |
143 | 147 | 156 |
157 | rad 158 | 0.5 159 | 0.6 160 | 0.7 161 | 0.8 162 | 0.9 163 | 1.0 164 |
165 |
166 |
167 | 170 |
171 |
172 |
173 | ); 174 | } 175 | 176 | export default ConfigPage; 177 | -------------------------------------------------------------------------------- /src/pages/Translator.tsx: -------------------------------------------------------------------------------- 1 | import clsx from 'clsx'; 2 | import { useCallback, useEffect, useRef } from 'react'; 3 | import { Button } from 'react-daisyui'; 4 | import toast from 'react-hot-toast'; 5 | import { useTranslation } from 'react-i18next'; 6 | import { CgArrowsExchange } from 'react-icons/cg'; 7 | import { MdClose, MdContentCopy } from 'react-icons/md'; 8 | import TextareaAutoSize from 'react-textarea-autosize'; 9 | 10 | import { useGlobalStore } from '@/components/GlobalStore'; 11 | import { SpeechRecognitionButton } from '@/components/SpeechRecognitionButton'; 12 | import { TTSButton } from '@/components/TTSButton'; 13 | import { Language, LANGUAGES } from '@/constants'; 14 | import { getTranslatePrompt } from '@/utils/prompt'; 15 | 16 | function TranslatorPage() { 17 | const { t, i18n } = useTranslation(); 18 | const translateTextAreaRef = useRef(null); 19 | 20 | const { 21 | configValues: { openaiApiKey, currentModel, temperatureParam }, 22 | translator: { 23 | lastTranslateData, 24 | setLastTranslateData, 25 | translateText, 26 | setTranslateText, 27 | translatedText, 28 | mutateTranslateText, 29 | isTranslating, 30 | isTranslateError, 31 | }, 32 | } = useGlobalStore(); 33 | 34 | useEffect(() => { 35 | if (!isTranslateError) { 36 | return; 37 | } 38 | toast.error(t('Something went wrong, please try again later.')); 39 | }, [isTranslateError, t]); 40 | 41 | const onCopyBtnClick = useCallback(() => { 42 | if (!translatedText) { 43 | toast.error(t('Nothing to copy!')); 44 | return; 45 | } 46 | navigator.clipboard 47 | .writeText(translatedText) 48 | .then(() => { 49 | toast.success(t('Copied!')); 50 | }) 51 | .catch(() => { 52 | toast.error(t('Failed to copy!')); 53 | }); 54 | }, [t, translatedText]); 55 | 56 | const onExchangeLanguageBtnClick = useCallback( 57 | () => 58 | setLastTranslateData((prev) => ({ 59 | ...prev, 60 | fromLang: prev.toLang, 61 | toLang: prev.fromLang, 62 | })), 63 | [setLastTranslateData], 64 | ); 65 | 66 | const onChangeTranscript = useCallback( 67 | (newTranscript: string) => { 68 | if (!translateTextAreaRef.current || !newTranscript) { 69 | return; 70 | } 71 | translateTextAreaRef.current.value = newTranscript; 72 | translateTextAreaRef.current.defaultValue = newTranscript; 73 | setTranslateText(newTranscript); 74 | }, 75 | [setTranslateText], 76 | ); 77 | 78 | const handleTranslate = useCallback( 79 | (event: React.FormEvent) => { 80 | event.preventDefault(); 81 | 82 | if (!openaiApiKey) { 83 | toast.error(t('Please enter your API Key in config page first!')); 84 | return; 85 | } 86 | 87 | const formData = new FormData(event.currentTarget); 88 | const { translateText, fromLang, toLang } = Object.fromEntries(formData.entries()); 89 | if (!translateText || !fromLang || !toLang) { 90 | return; 91 | } 92 | 93 | setTranslateText(translateText as string); 94 | 95 | let prompt: string; 96 | 97 | if (toLang === 'auto') { 98 | if (i18n.language.startsWith('zh')) { 99 | prompt = '翻译成简体白话文'; 100 | } else { 101 | const _toLang = LANGUAGES[i18n.language as Language] || i18n.language; 102 | prompt = `translate into ${_toLang}`; 103 | } 104 | } else { 105 | prompt = getTranslatePrompt(fromLang as Language, toLang as Language); 106 | } 107 | 108 | setLastTranslateData((prev) => ({ 109 | ...prev, 110 | fromLang: fromLang as Language, 111 | toLang: toLang as Language, 112 | })); 113 | 114 | mutateTranslateText({ 115 | token: openaiApiKey, 116 | engine: currentModel, 117 | prompt, 118 | temperatureParam, 119 | queryText: translateText as string, 120 | }); 121 | }, 122 | [ 123 | currentModel, 124 | i18n.language, 125 | mutateTranslateText, 126 | openaiApiKey, 127 | setLastTranslateData, 128 | setTranslateText, 129 | t, 130 | temperatureParam, 131 | ], 132 | ); 133 | 134 | const onClearBtnClick = useCallback(() => { 135 | if (!translateTextAreaRef.current) { 136 | return; 137 | } 138 | translateTextAreaRef.current.value = ''; 139 | }, []); 140 | 141 | // ↑ Hooks before, keep hooks order 142 | 143 | return ( 144 |
145 |
146 |
147 |
148 | 162 | 163 |
164 | 167 |
168 | 169 | 183 |
184 | 185 |
186 |
187 | setTranslateText(e.target.value)} 194 | disabled={isTranslating} 195 | required 196 | > 197 |
198 |
199 | 204 | {!!translateText && ( 205 | 209 | )} 210 |
211 | {!!translateText && ( 212 | 222 | )} 223 |
224 |
225 | 234 |
235 |
236 |
237 | 246 |
247 | 258 |
259 | {!!translatedText && ( 260 | 264 | )} 265 | {!!translatedText && !isTranslating && ( 266 | 276 | )} 277 |
278 |
279 |
280 |
281 |
282 | ); 283 | } 284 | 285 | export default TranslatorPage; 286 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------