diff --git a/docs/API/SEARCH.md b/docs/API/SEARCH.md index b67b62b..37c13ba 100644 --- a/docs/API/SEARCH.md +++ b/docs/API/SEARCH.md @@ -34,6 +34,7 @@ The API accepts a JSON object in the request body, where you define the focus mo ["assistant", "I am doing well, how can I help you today?"] ], "systemInstructions": "Focus on providing technical details about Perplexica's architecture.", + "locale": "en-US", "stream": false } ``` @@ -66,6 +67,8 @@ The API accepts a JSON object in the request body, where you define the focus mo - **`systemInstructions`** (string, optional): Custom instructions provided by the user to guide the AI's response. These instructions are treated as user preferences and have lower priority than the system's core instructions. For example, you can specify a particular writing style, format, or focus area. +- **`locale`** (string, optional): Specifies a custom locale for the search operation. If not provided, the default locale (en-US) will be used. This can be useful for tailoring search results to a specific language or region. Format: IETF BCP 47 codes ({ISO 639-1}-{ISO 3166-1 alpha-2}), see https://www.rfc-editor.org/rfc/bcp/bcp47.txt. + - **`history`** (array, optional): An array of message pairs representing the conversation history. Each pair consists of a role (either 'human' or 'assistant') and the message content. This allows the system to use the context of the conversation to refine results. Example: ```json diff --git a/next.config.mjs b/next.config.mjs index 2300ff4..1b91594 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -1,3 +1,5 @@ +import createNextIntlPlugin from 'next-intl/plugin'; + /** @type {import('next').NextConfig} */ const nextConfig = { output: 'standalone', @@ -11,4 +13,5 @@ const nextConfig = { serverExternalPackages: ['pdf-parse'], }; -export default nextConfig; +const withNextIntl = createNextIntlPlugin(); +export default withNextIntl(nextConfig); diff --git a/package.json b/package.json index 5715c2a..e35138f 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "mammoth": "^1.9.1", "markdown-to-jsx": "^7.7.2", "next": "^15.2.2", + "next-intl": "^4.3.4", "next-themes": "^0.3.0", "pdf-parse": "^1.1.1", "react": "^18", diff --git a/public/fonts/LICENSE b/public/fonts/LICENSE new file mode 100644 index 0000000..144cabd --- /dev/null +++ b/public/fonts/LICENSE @@ -0,0 +1,36 @@ +Noto Sans Traditional Chinese + +License +Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source' +This Font Software is licensed under the SIL Open Font License, Version 1.1 . This license is copied below, and is also available with a FAQ at: https://openfontlicense.org + +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the copyright statement(s). + +"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). +"Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: + +Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. +Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. +No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. +The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. +The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. +TERMINATION +This license becomes null and void if any of the above conditions are not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/public/fonts/NotoSansTC-Bold.ttf b/public/fonts/NotoSansTC-Bold.ttf new file mode 100644 index 0000000..46bb6f6 Binary files /dev/null and b/public/fonts/NotoSansTC-Bold.ttf differ diff --git a/public/fonts/NotoSansTC-Regular.ttf b/public/fonts/NotoSansTC-Regular.ttf new file mode 100644 index 0000000..6fd45d3 Binary files /dev/null and b/public/fonts/NotoSansTC-Regular.ttf differ diff --git a/public/fonts/README.md b/public/fonts/README.md new file mode 100644 index 0000000..b8e31cd --- /dev/null +++ b/public/fonts/README.md @@ -0,0 +1,13 @@ +Place font files here for client-side PDF generation. + +Recommended (Noto Sans TC - SIL Open Font License 1.1): + +- NotoSansTC-Regular.ttf +- NotoSansTC-Bold.ttf + +You can download from: + +- https://fonts.google.com/noto/specimen/Noto+Sans+TC +- https://github.com/googlefonts/noto-cjk (Sans/TTF) + +These fonts will be fetched via relative URLs at runtime by jsPDF. diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.ts index ba88da6..f9cbe6e 100644 --- a/src/app/api/chat/route.ts +++ b/src/app/api/chat/route.ts @@ -46,6 +46,7 @@ type Body = { chatModel: ChatModel; embeddingModel: EmbeddingModel; systemInstructions: string; + locale: string; }; const handleEmitterEvents = async ( @@ -284,6 +285,7 @@ export const POST = async (req: Request) => { body.optimizationMode, body.files, body.systemInstructions, + body.locale, ); const responseStream = new TransformStream(); diff --git a/src/app/api/discover/route.ts b/src/app/api/discover/route.ts index 415aee8..0d06412 100644 --- a/src/app/api/discover/route.ts +++ b/src/app/api/discover/route.ts @@ -1,4 +1,5 @@ import { searchSearxng } from '@/lib/searxng'; +import { DEFAULT_LOCALE } from '@/i18n/locales'; const websitesForTopic = { tech: { @@ -46,9 +47,9 @@ export const GET = async (req: Request) => { selectedTopic.query.map(async (query) => { return ( await searchSearxng(`site:${link} ${query}`, { - engines: ['bing news'], + engines: ['google news', 'bing news'], pageno: 1, - language: 'en', + language: DEFAULT_LOCALE, }) ).results; }), @@ -68,9 +69,9 @@ export const GET = async (req: Request) => { await searchSearxng( `site:${selectedTopic.links[Math.floor(Math.random() * selectedTopic.links.length)]} ${selectedTopic.query[Math.floor(Math.random() * selectedTopic.query.length)]}`, { - engines: ['bing news'], + engines: ['google news', 'bing news'], pageno: 1, - language: 'en', + language: DEFAULT_LOCALE, }, ) ).results; diff --git a/src/app/api/search/route.ts b/src/app/api/search/route.ts index 5f752ec..e2e297f 100644 --- a/src/app/api/search/route.ts +++ b/src/app/api/search/route.ts @@ -13,6 +13,7 @@ import { getCustomOpenaiModelName, } from '@/lib/config'; import { searchHandlers } from '@/lib/search'; +import { DEFAULT_LOCALE } from '@/i18n/locales'; interface chatModel { provider: string; @@ -35,6 +36,7 @@ interface ChatRequestBody { history: Array<[string, string]>; stream?: boolean; systemInstructions?: string; + locale?: string; } export const POST = async (req: Request) => { @@ -126,6 +128,7 @@ export const POST = async (req: Request) => { body.optimizationMode, [], body.systemInstructions || '', + body.locale || DEFAULT_LOCALE, ); if (!body.stream) { diff --git a/src/app/api/suggestions/route.ts b/src/app/api/suggestions/route.ts index 99179d2..78167e4 100644 --- a/src/app/api/suggestions/route.ts +++ b/src/app/api/suggestions/route.ts @@ -8,6 +8,7 @@ import { getAvailableChatModelProviders } from '@/lib/providers'; import { BaseChatModel } from '@langchain/core/language_models/chat_models'; import { AIMessage, BaseMessage, HumanMessage } from '@langchain/core/messages'; import { ChatOpenAI } from '@langchain/openai'; +import { DEFAULT_LOCALE } from '@/i18n/locales'; interface ChatModel { provider: string; @@ -17,6 +18,7 @@ interface ChatModel { interface SuggestionsGenerationBody { chatHistory: any[]; chatModel?: ChatModel; + locale?: string; } export const POST = async (req: Request) => { @@ -66,6 +68,7 @@ export const POST = async (req: Request) => { const suggestions = await generateSuggestions( { chat_history: chatHistory, + locale: body.locale || DEFAULT_LOCALE, }, llm, ); diff --git a/src/app/api/weather/route.ts b/src/app/api/weather/route.ts index afaf8a6..f1979aa 100644 --- a/src/app/api/weather/route.ts +++ b/src/app/api/weather/route.ts @@ -1,5 +1,8 @@ +import { getTranslations } from 'next-intl/server'; + export const POST = async (req: Request) => { try { + const t = await getTranslations('weather.conditions'); const body: { lat: number; lng: number; @@ -58,104 +61,104 @@ export const POST = async (req: Request) => { switch (code) { case 0: weather.icon = `clear-${dayOrNight}`; - weather.condition = 'Clear'; + weather.condition = t('clear'); break; case 1: - weather.condition = 'Mainly Clear'; + weather.condition = t('mainlyClear'); case 2: - weather.condition = 'Partly Cloudy'; + weather.condition = t('partlyCloudy'); case 3: weather.icon = `cloudy-1-${dayOrNight}`; - weather.condition = 'Cloudy'; + weather.condition = t('cloudy'); break; case 45: - weather.condition = 'Fog'; + weather.condition = t('fog'); case 48: weather.icon = `fog-${dayOrNight}`; - weather.condition = 'Fog'; + weather.condition = t('fog'); break; case 51: - weather.condition = 'Light Drizzle'; + weather.condition = t('lightDrizzle'); case 53: - weather.condition = 'Moderate Drizzle'; + weather.condition = t('moderateDrizzle'); case 55: weather.icon = `rainy-1-${dayOrNight}`; - weather.condition = 'Dense Drizzle'; + weather.condition = t('denseDrizzle'); break; case 56: - weather.condition = 'Light Freezing Drizzle'; + weather.condition = t('lightFreezingDrizzle'); case 57: weather.icon = `frost-${dayOrNight}`; - weather.condition = 'Dense Freezing Drizzle'; + weather.condition = t('denseFreezingDrizzle'); break; case 61: - weather.condition = 'Slight Rain'; + weather.condition = t('slightRain'); case 63: - weather.condition = 'Moderate Rain'; + weather.condition = t('moderateRain'); case 65: - weather.condition = 'Heavy Rain'; + weather.condition = t('heavyRain'); weather.icon = `rainy-2-${dayOrNight}`; break; case 66: - weather.condition = 'Light Freezing Rain'; + weather.condition = t('lightFreezingRain'); case 67: - weather.condition = 'Heavy Freezing Rain'; + weather.condition = t('heavyFreezingRain'); weather.icon = 'rain-and-sleet-mix'; break; case 71: - weather.condition = 'Slight Snow Fall'; + weather.condition = t('slightSnowFall'); case 73: - weather.condition = 'Moderate Snow Fall'; + weather.condition = t('moderateSnowFall'); case 75: - weather.condition = 'Heavy Snow Fall'; + weather.condition = t('heavySnowFall'); weather.icon = `snowy-2-${dayOrNight}`; break; case 77: - weather.condition = 'Snow'; + weather.condition = t('snow'); weather.icon = `snowy-1-${dayOrNight}`; break; case 80: - weather.condition = 'Slight Rain Showers'; + weather.condition = t('slightRainShowers'); case 81: - weather.condition = 'Moderate Rain Showers'; + weather.condition = t('moderateRainShowers'); case 82: - weather.condition = 'Heavy Rain Showers'; + weather.condition = t('heavyRainShowers'); weather.icon = `rainy-3-${dayOrNight}`; break; case 85: - weather.condition = 'Slight Snow Showers'; + weather.condition = t('slightSnowShowers'); case 86: - weather.condition = 'Moderate Snow Showers'; + weather.condition = t('moderateSnowShowers'); case 87: - weather.condition = 'Heavy Snow Showers'; + weather.condition = t('heavySnowShowers'); weather.icon = `snowy-3-${dayOrNight}`; break; case 95: - weather.condition = 'Thunderstorm'; + weather.condition = t('thunderstorm'); weather.icon = `scattered-thunderstorms-${dayOrNight}`; break; case 96: - weather.condition = 'Thunderstorm with Slight Hail'; + weather.condition = t('thunderstormSlightHail'); case 99: - weather.condition = 'Thunderstorm with Heavy Hail'; + weather.condition = t('thunderstormHeavyHail'); weather.icon = 'severe-thunderstorm'; break; default: weather.icon = `clear-${dayOrNight}`; - weather.condition = 'Clear'; + weather.condition = t('clear'); break; } diff --git a/src/app/discover/page.tsx b/src/app/discover/page.tsx index 8e20e50..e0a51ad 100644 --- a/src/app/discover/page.tsx +++ b/src/app/discover/page.tsx @@ -1,8 +1,10 @@ 'use client'; import { Search } from 'lucide-react'; -import { useEffect, useState } from 'react'; +import { useCallback, useEffect, useState } from 'react'; +import { useTranslations } from 'next-intl'; import Link from 'next/link'; +import Image from 'next/image'; import { toast } from 'sonner'; import { cn } from '@/lib/utils'; @@ -13,64 +15,55 @@ interface Discover { thumbnail: string; } -const topics: { key: string; display: string }[] = [ - { - display: 'Tech & Science', - key: 'tech', - }, - { - display: 'Finance', - key: 'finance', - }, - { - display: 'Art & Culture', - key: 'art', - }, - { - display: 'Sports', - key: 'sports', - }, - { - display: 'Entertainment', - key: 'entertainment', - }, +const topics: { + key: 'tech' | 'finance' | 'art' | 'sports' | 'entertainment'; +}[] = [ + { key: 'tech' }, + { key: 'finance' }, + { key: 'art' }, + { key: 'sports' }, + { key: 'entertainment' }, ]; const Page = () => { const [discover, setDiscover] = useState(null); const [loading, setLoading] = useState(true); const [activeTopic, setActiveTopic] = useState(topics[0].key); + const t = useTranslations('pages.discover'); - const fetchArticles = async (topic: string) => { - setLoading(true); - try { - const res = await fetch(`/api/discover?topic=${topic}`, { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - }, - }); + const fetchArticles = useCallback( + async (topic: string) => { + setLoading(true); + try { + const res = await fetch(`/api/discover?topic=${topic}`, { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + }); - const data = await res.json(); + const data = await res.json(); - if (!res.ok) { - throw new Error(data.message); + if (!res.ok) { + throw new Error(data.message); + } + + data.blogs = data.blogs.filter((blog: Discover) => blog.thumbnail); + + setDiscover(data.blogs); + } catch (err: any) { + console.error('Error fetching data:', err.message); + toast.error(t('errorFetchingData')); + } finally { + setLoading(false); } - - data.blogs = data.blogs.filter((blog: Discover) => blog.thumbnail); - - setDiscover(data.blogs); - } catch (err: any) { - console.error('Error fetching data:', err.message); - toast.error('Error fetching data'); - } finally { - setLoading(false); - } - }; + }, + [t], + ); useEffect(() => { fetchArticles(activeTopic); - }, [activeTopic]); + }, [activeTopic, fetchArticles]); return ( <> @@ -78,24 +71,24 @@ const Page = () => {
-

Discover

+

{t('title')}


- {topics.map((t, i) => ( + {topics.map((topic, i) => (
setActiveTopic(t.key)} + onClick={() => setActiveTopic(topic.key)} > - {t.display} + {t(`topics.${topic.key}`)}
))}
@@ -129,15 +122,20 @@ const Page = () => { className="max-w-sm rounded-lg overflow-hidden bg-light-secondary dark:bg-dark-secondary hover:-translate-y-[1px] transition duration-200" target="_blank" > - {item.title} +
+ {item.title} +
{item.title.slice(0, 100)}... diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 684a99c..8b885ca 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -5,6 +5,10 @@ import { cn } from '@/lib/utils'; import Sidebar from '@/components/Sidebar'; import { Toaster } from 'sonner'; import ThemeProvider from '@/components/theme/Provider'; +import { NextIntlClientProvider } from 'next-intl'; +import { getLocale, getTranslations } from 'next-intl/server'; +import LocaleBootstrap from '@/components/LocaleBootstrap'; +import { LOCALES, DEFAULT_LOCALE, type AppLocale } from '@/i18n/locales'; const montserrat = Montserrat({ weight: ['300', '400', '500', '700'], @@ -13,32 +17,43 @@ const montserrat = Montserrat({ fallback: ['Arial', 'sans-serif'], }); -export const metadata: Metadata = { - title: 'Perplexica - Chat with the internet', - description: - 'Perplexica is an AI powered chatbot that is connected to the internet.', -}; +export async function generateMetadata(): Promise { + const t = await getTranslations('metadata'); + return { + title: t('title'), + description: t('description'), + }; +} -export default function RootLayout({ +export default async function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { + const locale = await getLocale(); + const appLocale: AppLocale = (LOCALES as readonly string[]).includes( + locale as string, + ) + ? (locale as AppLocale) + : DEFAULT_LOCALE; return ( - + - - {children} - - + + + + {children} + + + ); diff --git a/src/app/library/layout.tsx b/src/app/library/layout.tsx index 00d4a3b..43c5a90 100644 --- a/src/app/library/layout.tsx +++ b/src/app/library/layout.tsx @@ -1,9 +1,13 @@ import { Metadata } from 'next'; import React from 'react'; +import { getTranslations } from 'next-intl/server'; -export const metadata: Metadata = { - title: 'Library - Perplexica', -}; +export async function generateMetadata(): Promise { + const t = await getTranslations('pages.library'); + return { + title: `${t('title')} - Perplexica`, + }; +} const Layout = ({ children }: { children: React.ReactNode }) => { return
{children}
; diff --git a/src/app/library/page.tsx b/src/app/library/page.tsx index 9c40b2b..7d0407c 100644 --- a/src/app/library/page.tsx +++ b/src/app/library/page.tsx @@ -1,10 +1,11 @@ 'use client'; import DeleteChat from '@/components/DeleteChat'; -import { cn, formatTimeDifference } from '@/lib/utils'; +import { cn, formatRelativeTime } from '@/lib/utils'; import { BookOpenText, ClockIcon, Delete, ScanEye } from 'lucide-react'; import Link from 'next/link'; import { useEffect, useState } from 'react'; +import { useLocale, useTranslations } from 'next-intl'; export interface Chat { id: string; @@ -16,6 +17,8 @@ export interface Chat { const Page = () => { const [chats, setChats] = useState([]); const [loading, setLoading] = useState(true); + const t = useTranslations('pages.library'); + const locale = useLocale(); useEffect(() => { const fetchChats = async () => { @@ -61,14 +64,14 @@ const Page = () => {
-

Library

+

{t('title')}


{chats.length === 0 && (

- No chats found. + {t('empty')}

)} @@ -94,7 +97,7 @@ const Page = () => {

- {formatTimeDifference(new Date(), chat.createdAt)} Ago + {formatRelativeTime(new Date(), chat.createdAt, locale)}

{ + const t = await getTranslations('manifest'); return { - name: 'Perplexica - Chat with the internet', - short_name: 'Perplexica', - description: - 'Perplexica is an AI powered chatbot that is connected to the internet.', + name: t('name'), + short_name: t('shortName'), + description: t('description'), start_url: '/', display: 'standalone', background_color: '#0a0a0a', diff --git a/src/app/page.tsx b/src/app/page.tsx index 25981b5..6dae504 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -2,11 +2,15 @@ import ChatWindow from '@/components/ChatWindow'; import { ChatProvider } from '@/lib/hooks/useChat'; import { Metadata } from 'next'; import { Suspense } from 'react'; +import { getTranslations } from 'next-intl/server'; -export const metadata: Metadata = { - title: 'Chat - Perplexica', - description: 'Chat with the internet, chat with Perplexica.', -}; +export async function generateMetadata(): Promise { + const t = await getTranslations('pages.home'); + return { + title: t('title'), + description: t('description'), + }; +} const Home = () => { return ( diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index 6fb8255..d34898b 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -5,9 +5,11 @@ import { useEffect, useState } from 'react'; import { cn } from '@/lib/utils'; import { Switch } from '@headlessui/react'; import ThemeSwitcher from '@/components/theme/Switcher'; +import LocaleSwitcher from '@/components/LocaleSwitcher'; import { ImagesIcon, VideoIcon } from 'lucide-react'; import Link from 'next/link'; import { PROVIDER_METADATA } from '@/lib/providers'; +import { useTranslations } from 'next-intl'; interface SettingsType { chatModelProviders: { @@ -129,6 +131,7 @@ const SettingsSection = ({ ); const Page = () => { + const t = useTranslations('pages.settings'); const [config, setConfig] = useState(null); const [chatModels, setChatModels] = useState>({}); const [embeddingModels, setEmbeddingModels] = useState>( @@ -398,7 +401,7 @@ const Page = () => {
-

Settings

+

{t('title')}


@@ -426,16 +429,16 @@ const Page = () => { ) : ( config && (
- +

- Theme + {t('preferences.theme')}

- Measurement Units + {t('preferences.measurementUnits')}