Download server.ts from Musabek/BilimWay: direct link, hf CLI and curl.
- Browser
- Download file 55.4 kB
-
https://huggingface.co/spaces/Musabek/BilimWay/resolve/main/server.ts
- Command line
-
hf download hf://spaces/Musabek/BilimWay/server.ts
-
curl -L -o server.ts https://huggingface.co/spaces/Musabek/BilimWay/resolve/main/server.ts
55.4 kB
import express from "express";
import path from "path";
import fs from "fs";
import { GoogleGenAI, Type } from "@google/genai";
import dotenv from "dotenv";
import multer from "multer";
dotenv.config();
// Create uploads directory if it doesn't exist
const uploadsDir = path.join(process.cwd(), "uploads");
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
// Multer storage setup
const multerStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadsDir);
},
filename: (req, file, cb) => {
// Sanitary file name replacement to ensure it's ASCII/URL safe
const safeName = file.originalname.replace(/[^a-zA-Z0-9.\-_]/g, "_");
cb(null, `${Date.now()}_${safeName}`);
}
});
// Configure upload limits - up to 1GB
const upload = multer({
storage: multerStorage,
limits: { fileSize: 1024 * 1024 * 1024 } // 1GB limit
});
let aiClient: GoogleGenAI | null = null;
function getGeminiClient(): GoogleGenAI {
if (!aiClient) {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
console.warn("WARN: GEMINI_API_KEY is not defined in environment variables.");
}
aiClient = new GoogleGenAI({
apiKey: apiKey || "MOCK_KEY_UNUSED",
httpOptions: {
headers: {
'User-Agent': 'aistudio-build',
}
}
});
}
return aiClient;
}
// Helper function to call generateContent with retry and fallback models to prevent 503 UNAVAILABLE errors
async function generateContentWithFallback(client: GoogleGenAI, originalParams: any) {
const modelsToTry = [
"gemini-3.5-flash",
"gemini-3.1-flash-lite",
"gemini-flash-latest"
];
let lastError: any = null;
for (const modelName of modelsToTry) {
let retries = 2; // 2 retries per model
while (retries >= 0) {
try {
const response = await client.models.generateContent({
...originalParams,
model: modelName
});
return response;
} catch (err: any) {
lastError = err;
const errMsg = String(err.message || err);
console.warn(`Attempt with model ${modelName} failed (retries left: ${retries}). Error: ${errMsg}`);
// If it's a 503 (Overloaded / Unavailable) or 429 (Rate limit) or "high demand"
if (
errMsg.includes("503") ||
errMsg.includes("UNAVAILABLE") ||
errMsg.includes("429") ||
errMsg.includes("RESOURCE_EXHAUSTED") ||
errMsg.includes("demand") ||
errMsg.includes("overloaded") ||
errMsg.includes("spikes")
) {
retries--;
if (retries >= 0) {
const waitTime = (2 - retries) * 1000; // 1000ms, then 2000ms
await new Promise((resolve) => setTimeout(resolve, waitTime));
continue;
}
} else {
// For syntax / user-facing errors, don't retry, just fail-over early or throw
break;
}
}
}
}
throw lastError || new Error("All Gemini models failed to generate content.");
}
async function startServer() {
const app = express();
const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
// Increase payload limit to receive base64 images of handwritten homework
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ limit: "50mb", extended: true }));
// Enable CORS globally to handle cross-subdomain requests safely (e.g. from dev to pre subdomains and iframes)
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Range");
res.setHeader("Access-Control-Expose-Headers", "Content-Range, Content-Length, Accept-Ranges");
if (req.method === "OPTIONS") {
res.sendStatus(204);
return;
}
next();
});
// Serve static uploaded files locally with cross-origin & flawless HTML5 video range-request streaming support
app.get("/uploads/:filename", (req, res) => {
try {
const fileName = req.params.filename;
const filePath = path.join(uploadsDir, fileName);
// Prevent directory traversal attacks
if (!filePath.startsWith(uploadsDir)) {
return res.status(403).send("Ruxsat etilmagan kirish.");
}
if (!fs.existsSync(filePath)) {
return res.status(404).send("Fayl topilmadi.");
}
// Add full CORS and stream support headers
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Range, Content-Type, Authorization");
res.setHeader("Access-Control-Expose-Headers", "Content-Range, Content-Length, Accept-Ranges");
res.setHeader("Accept-Ranges", "bytes");
// Express res.sendFile natively handles:
// - Correct MIME type detection using extensive mime DB (handles uppercase, mov, webm, mp4, etc.)
// - Browser range requests with HTTP 206 Partial Content out of the box
// - Full handshake for Safari/Chrome media pre-flight requests
return res.sendFile(filePath);
} catch (err: any) {
console.error(" uploads streaming handler error:", err);
if (!res.headersSent) {
res.status(500).send("Faylni uzatish xatosi.");
}
}
});
// Fallback static files middleware just in case
app.use("/uploads", express.static(uploadsDir, {
setHeaders: (res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Range, Content-Type, Authorization");
res.setHeader("Access-Control-Expose-Headers", "Content-Range, Content-Length, Accept-Ranges");
res.setHeader("Accept-Ranges", "bytes");
}
}));
// local file upload endpoint
app.post("/api/upload", upload.single("file"), (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ success: false, error: "Fayl yuklanmadi." });
}
const fileUrl = `/uploads/${req.file.filename}`;
res.json({
success: true,
fileUrl: fileUrl,
size: req.file.size,
mimetype: req.file.mimetype,
originalname: req.file.originalname
});
} catch (err: any) {
console.error("Local upload api error:", err);
res.status(500).json({ success: false, error: err.message });
}
});
// chunked file upload endpoint to handle large payloads and avoid 413 Entity Too Large errors
app.post("/api/upload-chunk", upload.single("chunk"), (req, res) => {
try {
const { uploadId, chunkIndex, totalChunks, fileName } = req.body;
if (!req.file) {
return res.status(400).json({ success: false, error: "Chunk file was not uploaded." });
}
const cIdx = parseInt(chunkIndex, 10);
const totChunks = parseInt(totalChunks, 10);
// Create a temporary directory for chunks
const chunkDir = path.join(uploadsDir, `temp_${uploadId}`);
if (!fs.existsSync(chunkDir)) {
fs.mkdirSync(chunkDir, { recursive: true });
}
// Move uploaded chunk file of this index inside the temporary dir
const chunkPath = path.join(chunkDir, `chunk_${cIdx}`);
try {
fs.renameSync(req.file.path, chunkPath);
} catch (renameErr) {
console.warn("fs.renameSync failed, falling back to copyFileSync:", renameErr);
fs.copyFileSync(req.file.path, chunkPath);
try {
fs.unlinkSync(req.file.path);
} catch (unlinkErr) {
console.warn("Could not remove source file after copying:", unlinkErr);
}
}
// If it's the last chunk, assemble all parts
if (cIdx === totChunks - 1) {
// Create final file name
const safeName = fileName.replace(/[^a-zA-Z0-9.\-_]/g, "_");
const finalFileName = `${Date.now()}_${safeName}`;
const finalFilePath = path.join(uploadsDir, finalFileName);
// Delete any existing file at this path
if (fs.existsSync(finalFilePath)) {
fs.unlinkSync(finalFilePath);
}
// Assemble all chunks synchronously to guarantee the file is fully written before response
for (let i = 0; i < totChunks; i++) {
const currentChunkPath = path.join(chunkDir, `chunk_${i}`);
if (!fs.existsSync(currentChunkPath)) {
return res.status(500).json({ success: false, error: `Missing chunk at index ${i}` });
}
const data = fs.readFileSync(currentChunkPath);
fs.appendFileSync(finalFilePath, data);
// Delete chunk file immediately to clean space
fs.unlinkSync(currentChunkPath);
}
// Clean up the temp directory
try {
fs.rmdirSync(chunkDir);
} catch (e) {
console.warn("Could not remove temp chunk directory:", e);
}
return res.json({
success: true,
fileUrl: `/uploads/${finalFileName}`,
assembled: true
});
}
return res.json({
success: true,
assembled: false,
chunkIndex: cIdx
});
} catch (err: any) {
console.error("Chunked upload error:", err);
res.status(500).json({ success: false, error: err.message });
}
});
// Dynamic lesson contents creator using real Gemini AI
app.post("/api/generate-lesson-content", async (req, res) => {
const { language, level, topic, title } = req.body;
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
// Return high quality pre-saved/simulated fallback if no Gemini key is provided, ensuring seamless UX
return res.json(getFallbackLesson(language, level, topic, title));
}
try {
const client = getGeminiClient();
const prompt = `Siz chet tillarini o'rgatuvchi professional AI o'qituvchisiz.
Mavzu: "${title}" (Kategoriya: ${topic}, Daraja: ${level}, O'rganilayotgan til: ${language === 'en' ? 'Ingliz tili' : 'Rus tili'}).
Foydalanuvchi interfeysi tili: O'zbekcha.
Quyidagi tuzilmaga ega to'liq dars materialini JSON formatida yaratib bering:
1. "explanation": Dynamic dars tushuntirishi (Markdown strukturada, chiroyli qoidalari, misollar jadvali va o'rgatuvchi tushuntirishlari bilan O'zbek tilida).
2. "exercises": 2 ta mashiq. Har bir mashiq ichida aniq 6 tadan gap bo'lsin. Har bir gapda darsga aloqador 1 ta so'z/iborani tushirib qoldiring (masalan, "I _____ to school" yoki "Я _____ в школу"). Ushbu blank uchun 4 ta variant ("options") taqdim etilsin va to'g'ri javob indexi ("correctOption", 0 dan 3 gacha bo'lgan raqam) belgilansin.
3. "homework": 1 ta amaliy uyga vazifa ko'rsatmasi. Foydalanuvchidan buni qog'ozga yozib rasmga tushirishi so'ralishi kerak (moroqli va ijodiy topshiriq).
JSON formati quyidagicha bo'lsin:
{
"explanation": "...",
"exercises": [
{
"title": "Mashiq 1: ...",
"questions": [
{ "sentence": "...", "options": ["...", "...", "...", "..."], "correctOption": 1 }
]
},
{
"title": "Mashiq 2: ...",
"questions": [
{ "sentence": "...", "options": ["...", "...", "...", "..."], "correctOption": 2 }
]
}
],
"homework": "..."
}`;// @ts-ignore
const response = await generateContentWithFallback(client, {
contents: prompt,
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
explanation: { type: Type.STRING },
exercises: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
title: { type: Type.STRING },
questions: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
sentence: { type: Type.STRING },
options: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
correctOption: { type: Type.INTEGER }
},
required: ["sentence", "options", "correctOption"]
}
}
},
required: ["title", "questions"]
}
},
homework: { type: Type.STRING }
},
required: ["explanation", "exercises", "homework"]
}
}
});
const responseText = response.text;
if (responseText) {
const parsedData = JSON.parse(responseText.trim());
return res.json({ success: true, data: parsedData });
} else {
throw new Error("Bo'sh javob qaytdi.");
}
} catch (error: any) {
console.error("Gemini lesson generation error:", error);
return res.json({
success: false,
error: error.message,
fallback: getFallbackLesson(language, level, topic, title).data
});
}
});
// AI Chat API route
app.post("/api/chat", async (req, res) => {
const { messages, language } = req.body;
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
// Fallback simple simulation response
const lastMsg = messages && messages.length > 0 ? messages[messages.length - 1].content : "";
return res.json({
success: true,
reply: `**[Simulyatsiya rejimi - API kalit topilmadi]**
Sizning savolingiz: *"${lastMsg}"*
Men **BilimWay AI** aqlli yordamchisiman. Chet tillarini qulay o'rganishingiz uchun xizmat qilaman! 🌟
Haqiqiy sun'iy intellekt javobini olish uchun AI Studio Secrets qismida \`GEMINI_API_KEY\` ni sozlang.
Sizga ${language === 'en' ? 'Ingliz tili' : 'Rus tili'} bo'yicha yordam berishdan mamnunman! Qanday savolingiz bor?`
});
}
try {
const client = getGeminiClient();
const contents = messages.map((m: any) => ({
role: m.role === 'user' ? 'user' : 'model',
parts: [{ text: m.content || "" }]
}));
const sysInstruction = `Siz 'BilimWay AI' ilovasining aqlli va yordamchi chatbotisiz. Foydalanuvchilar siz bilan asosan zamonaviy tillarni o'rganish, savol-javob va matnlar ustida ishlash uchun muloqot qilishadi. Sizning javoblaringiz mobil telefon ekranida o'qishga juda qulay bo'lishi shart.
Muloqot va matn ko'rinishi qoidalari:
1. Qisqalik va aniqlik: Gapni ko'p aylantirmasdan, savolga to'g'ridan-to'g'ri va qisqa javob bering. Uzun matnlarni o'qish mobil ekranda noqulay.
2. Tuzilma (Struktura): Katta matnli devorlar (dense text) yaratmang. Matnni doimo paragraflarga bo'ling, muhim joylarni bold (to'q rangda) qiling va sanab o'tishda emoji yoki bullet pointlardan (*) foydalaning.
3. Formatlash: Agar jadval kerak bo'lsa, ixcham Markdown jadvallaridan foydalaning. Kod yozsangiz, tushunarli bloklar ichiga oling.
4. Ohang: Foydalanuvchiga samimiy, rag'batlantiruvchi va do'stona munosabatda bo'ling. Murakkab qoidalarni eng sodda tilda tushuntiring.
5. Til: Foydalanuvchi qaysi tilda murojaat qilsa (o'zbek, rus, ingliz), aynan o'sha tilda javob qaytaring.`;
const response = await generateContentWithFallback(client, {
contents: contents,
config: {
systemInstruction: sysInstruction
}
});
return res.json({ success: true, reply: response.text || "Kechirasiz, sun'iy intellektdan javob ololmadim." });
} catch (error: any) {
console.error("AI Chat error:", error);
return res.json({ success: false, error: error.message });
}
});
// Deep Topic Study Chat API
app.post("/api/study-chat", async (req, res) => {
const { messages, language, topic } = req.body;
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
const lastMsg = messages && messages.length > 0 ? messages[messages.length - 1].content : "";
return res.json({
success: true,
reply: `**[Simulyatsiya rejimi]**
Ushbu dars mavzusi: **"${topic}"** bo'yicha tahliliy muloqot (Dars tili: ${language === 'uz' ? "O'zbek tili" : language === 'ru' ? "Rus tili" : "Ingliz tili"}).
Siz so'ragan qoida bo'yicha qisqacha tushuntirish:
Ushbu darsda mavzu chuqur tushuntirilishi lozim, ammo hozirda simulyatsiya rejimida ishlanmoqda.
Mavzu bo'yicha to'liq dars tushuntirib bo'lindi.
**Sizga test va mashqlar tuzib beraymi?**
Marhamat, menga nechta test va nechta mashq kerakligini yozing (Masalan: "3 ta test va 2 ta mashq tuzib ber" deb yuboring), men dars mavzusi doirasida aynan siz aytgan sondagicha test va mashqlarni tuzib beraman!`
});
}
try {
const client = getGeminiClient();
const contents = messages.map((m: any) => ({
role: m.role === 'user' ? 'user' : 'model',
parts: [{ text: m.content || "" }]
}));
const sysInstruction = `Siz 'BilimWay AI' darslik platformasining "Chuqur Mavzu Darsi" o'qituvchi chatbotisiz. Vazifangiz foydalanuvchilar tanlagan yoki so'ragan til o'rganish mavzularini (Masalan: Present Perfect, Artikllar, Harakat Fe'llari va h.k.) juda chuqur, batafsil, jadvallar va hayotiy misollar yordamida o'rgatishdir.
MULOQOT STRUKTURASI VA QOIDALAR:
1. Birinchi marta dars boshlanganda, foydalanuvchi so'ragan "${topic}" mavzusini mukammal, o'ta qiziqarli va batafsil tushuntirib bering. Iloji boricha Markdown jadvallari, qoidalar, o'zbekcha tarjimalar va muloqot iboralaridan foydalaning.
2. Mavzu tushuntirib bo'lingach, xabar oxirida FOYDALANUVCHIDAN ALBATTA ushbu iborani yoki unga yaqin ma'nodagi savolni so'rang:
"Sizga test va mashqlar tuzib beraymi?"
3. Agar foydalanuvchi sizdan ma'lum miqdorda test va mashqlar tuzib berishni so'rasa, masalan: "3 ta test va 2 ta mashq" yoki "5 ta test" yoki "2 ta mashq" va h.k. deb yozsa:
- Soni esingizdan chiqib ketmasligi juda muhim! Foydalanuvchi aytgan sonni qat'iy yodda tuting.
- Kiritilgan sonigacha borib, aynan o'sha miqdordagi testlarni (variantlari: A, B, C, D va to'g'ri javobi bilan) va mashqlarni (gaplar tarjimasi, bo'shliqni to'ldirish yoki gap tuzish kabi qiziqarli mashqlar) tuzib berasiz.
- Testlar va mashqlarning javoblarini dars oxirida (yoki foydalanuvchi tekshirishni so'raganda) taqdim eting.
4. Javob berishda dars tili: ${language === 'uz' ? "O'zbek tili" : language === 'ru' ? "Rus tili" : "Ingliz tili"} bo'lsin. Juda sodda, tushunarli, aniq tushuntiring va muloqotni do'stona tarzda olib boring. Matematik aniqlik bilan test/mashqlar soniga amal qiling.`;
const response = await generateContentWithFallback(client, {
contents: contents,
config: {
systemInstruction: sysInstruction
}
});
return res.json({ success: true, reply: response.text || "Kechirasiz, sun'iy intellektdan dars javobini ololmadim." });
} catch (error: any) {
console.error("Study Chat error:", error);
return res.json({ success: false, error: error.message });
}
});
// Deep Topic Study API
app.post("/api/study-topic", async (req, res) => {
const { topic, explanationLanguage } = req.body;
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
return res.json(getFallbackStudyTopic(topic, explanationLanguage));
}
try {
const client = getGeminiClient();
const prompt = `Foydalanuvchi o'rganmoqchi bo'lgan maxsus dars mavzusi: "${topic}".
Tushuntirish va dars tili: ${explanationLanguage === 'uz' ? 'O\'zbek tili (Uzbek)' : explanationLanguage === 'ru' ? 'Rus tili (Russian)' : 'Ingliz tili (English)'}.
Iltimos, ushbu darsni barcha grammatical/vocabulary qoidalari, real hayotiy misollari, jadvallari va tushunarli sodda uslubda mukammal tushuntirib bering.
Shuningdek, ushbu darsga oid to'liq mashiq qilish uchun aniq 4 ta interaktiv test savollarini hamda 1 ta qiziqarli amaliy yozma/rasmli uyga vazifa topshirig'ini yaratib bering.
Javobni quyidagi qat'iy JSON formatida qaytaring:
{
"topicTitle": "${topic}",
"explanation": "Markdown formatda batafsil dars qo'llanmasi jadvallari, misollari bilan...",
"exercises": [
{
"sentence": "Savol matni yoki bo'sh joy qoldirilgan gap...",
"options": ["variant1", "variant2", "variant3", "variant4"],
"correctOption": 0
}
],
"homework": "Yozma yoki rasmli uyga vazifa topshirig'i tavsifi..."
}`;
const response = await generateContentWithFallback(client, {
contents: prompt,
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
topicTitle: { type: Type.STRING },
explanation: { type: Type.STRING },
exercises: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
sentence: { type: Type.STRING },
options: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
correctOption: { type: Type.INTEGER }
},
required: ["sentence", "options", "correctOption"]
}
},
homework: { type: Type.STRING }
},
required: ["topicTitle", "explanation", "exercises", "homework"]
}
}
});
const responseText = response.text;
if (responseText) {
const parsedData = JSON.parse(responseText.trim());
return res.json({ success: true, ...parsedData });
} else {
throw new Error("Bo'sh javob qaytdi.");
}
} catch (error: any) {
console.error("Gemini topic study generation error:", error);
return res.json({
success: false,
error: error.message,
...getFallbackStudyTopic(topic, explanationLanguage)
});
}
});
// Comprehensive Exam Generation (60 Questions: 12 Questions per each of the 5 saved topics)
app.post("/api/generate-mega-exam", async (req, res) => {
const { topics, language } = req.body;
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey || !topics || topics.length < 5) {
return res.json(getFallbackMegaExam(topics || ["Mavzu 1", "Mavzu 2", "Mavzu 3", "Mavzu 4", "Mavzu 5"], language));
}
try {
const client = getGeminiClient();
const prompt = `Foydalanuvchi o'rgangan 5 ta mavzu ro'yxati: ${JSON.stringify(topics)}.
Siz ushbu 5 ta darsning har biriga tegishli 12 tadan, jami to'ppa-to'g'ri 60 ta interaktiv test savollarini ingliz/rus grammatikasi va leksikasini tekshirish uchun tuzib bering.
Savollar ${language === 'uz' ? 'O\'zbek tilida' : language === 'ru' ? 'Rus tilida' : 'Ingliz tilida'} tushuntirilsin.
Har bir savol ko'p variantli bo'lib, uning to'g'ri javob indexi (0, 1, 2, 3) belgilanishi lozim.
Javobni quyidagi qisqa JSON ko'rinishida qaytaring:
{
"questions": [
{
"q": "Savol matni or gap strukturasi...",
"options": ["A", "B", "C", "D"],
"correct": 0,
"topic": "Ushbu savol qaysi mavzuga tegishli ekanligi"
}
]
}`;
const response = await generateContentWithFallback(client, {
contents: prompt,
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
questions: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
q: { type: Type.STRING },
options: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
correct: { type: Type.INTEGER },
topic: { type: Type.STRING }
},
required: ["q", "options", "correct", "topic"]
}
}
},
required: ["questions"]
}
}
});
const responseText = response.text;
if (responseText) {
const parsedData = JSON.parse(responseText.trim());
return res.json({ success: true, ...parsedData });
} else {
throw new Error("Bo'sh imtihon javobi qaytdi.");
}
} catch (error: any) {
console.error("Gemini exam generation error:", error);
return res.json({
success: false,
error: error.message,
...getFallbackMegaExam(topics, language)
});
}
});
// Homework check API with image understanding using server-side Gemini
app.post("/api/check-homework", async (req, res) => {
const { language, topic, title, homeworkPrompt, imageData, textDraft } = req.body;
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
// Simulate review if API key is not configured yet
const randomScore = textDraft || imageData ? Math.floor(Math.random() * 2) + 4 : 3; // 4 or 5 normally
const simFeedback = `[Simulyatsiya rejimi]: Uyga vazifangiz tahlil qilindi!
Siz mavzuni juda yaxshi o'zlashtiribsiz. Quyida tahlil natijalari:
- Grammatik xatolar: Yo'q
- So'z boyligi qo'llanilishi: A'lo darajada.
${randomScore < 4 ? "\nQayta topshirish uchun yangi topshiriq: Mavzu doirasida yana 3 ta gap tuzing." : "\nKelgusi darslarga omad!"}`;
return res.json({
success: true,
score: randomScore,
feedback: simFeedback,
alternativeHomework: randomScore < 4 ? "Yangi vazifa: Mavzu bo'yicha mustaqil ravishda o'zingiz haqingizda 4 ta sodda gap yozib yuklang." : null
});
}
try {
const client = getGeminiClient();
const parts: any[] = [];
parts.push({
text: `Siz til o'rgatish o'quv markazining tajribali AI o'qituvchisisiz.
Vazifa mavzusi: "${title}" (${topic})
Berilgan topshiriq: "${homeworkPrompt}"
O'rganilayotgan til: ${language === 'en' ? 'Ingliz' : 'Rus'} tili.
Foydalanuvchi dars oxiridagi uyga vazifasini qog'ozga yozib rasmga tushirib yubordi yoki matn shaklida kiritdi.
Iltimos, ushbu yuklangan uyga vazifani tahlil qiling:
1. Imlo xatolari, grammatik xatolar va so'zlarning to'g'ri ishlatilganligini tekshiring.
2. Har bir xatoni O'zbek tilida dona-dona tushuntirib bering.
3. 5 ballik baholash tizimida unga baho qo'ying (1 dan 5 gacha butun son).
4. Baho 4 ball yoki undan yuqori bo'lsa (yaxshi va a'lo), uni samimiy tabriklang va tavsiyalar bering.
5. Agar baho 4 dandan kichik bo'lsa (masalan 1, 2, 3), unda xatolardan kelib chiqib, shu mavzuni mustahkamlash uchun MUTLAQO YANGI va boshqacha uyga vazifa tuzib bering ("alternativeHomework" maydoniga).
Javobni aniq JSON formatida quyidagi tuzilma bilan qaytaring:
{
"score": 5, // 1 dan 5 gacha butun son
"feedback": "...", // tahlil va xatolar haqida to'liq hisobot (O'zbek tilida)
"alternativeHomework": "..." // baho 4 dan past bo'lgandagina yoziladi, bo'lmasa null yoki bo'sh bo'ladi
}`
});
if (imageData) {
// base64 parsing: remove dataURI metadata if present
const cleanBase64 = imageData.replace(/^data:image\/\w+;base64,/, "");
parts.push({
inlineData: {
mimeType: "image/png",
data: cleanBase64
}
});
}
if (textDraft) {
parts.push({
text: `Foydalanuvchining matnli/yozma javobi: "${textDraft}"`
});
}
const response = await generateContentWithFallback(client, {
contents: { parts },
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
score: { type: Type.INTEGER },
feedback: { type: Type.STRING },
alternativeHomework: { type: Type.STRING }
},
required: ["score", "feedback"]
}
}
});
const responseText = response.text;
if (responseText) {
const parsed = JSON.parse(responseText.trim());
return res.json({ success: true, ...parsed });
} else {
throw new Error("AI darsni tahlil qila olmadi.");
}
} catch (error: any) {
console.error("Gemini check-homework error:", error);
return res.json({
success: false,
error: error.message,
score: 3,
feedback: "Kechirasiz, rasm yoki matnni tahlil qilishda nosozlik yuz berdi. Tizim avtomatik ravishda 3 baho qo'ydi. Iltimos, qayta urinib ko'ring.",
alternativeHomework: "Qayta urinish: Dars ko'rsatmalariga muvofiq gaplarni chiroyli yozib qayta yuklang."
});
}
});
// Dynamic system to generate adaptive chess questions or battle questions
app.post("/api/generate-duel-question", async (req, res) => {
const { language, level } = req.body;
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
return res.json({ success: true, ...getMockDuelQuestion(language, level) });
}
try {
const client = getGeminiClient();
const prompt = `Chet tili dueli uchun 1 ta qiziqarli test savolini JSON shaklida yarating.
O'rganilayotgan til: ${language === 'en' ? 'Ingliz' : 'Rus'}.
Daraja: ${level || 'Normal'}.
Savol turi: Grammatika yoki so'z boyligi bo'yicha tushib qolgan so'z variantlari.
Savolda 4 ta variant bo'lishi va bitta to'g'ri o'rin belgilanishi kerak.
Quyidagi strukturada javob bering:
{
"question": "Oynadagi gap yozuvi, masalan: This is the man _____ car was stolen.",
"options": ["who", "whose", "which", "whom"],
"correctIndex": 1,
"explanation": "Tushuntirish: O'zbek tilida gap qoidasining qisqacha izohi."
}`;
const response = await generateContentWithFallback(client, {
contents: prompt,
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
question: { type: Type.STRING },
options: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
correctIndex: { type: Type.INTEGER },
explanation: { type: Type.STRING }
},
required: ["question", "options", "correctIndex", "explanation"]
}
}
});
const responseText = response.text;
if (responseText) {
const parsed = JSON.parse(responseText.trim());
return res.json({ success: true, ...parsed });
} else {
throw new Error("Bo'sh duel savoli.");
}
} catch (e) {
return res.json({ success: true, ...getMockDuelQuestion(language, level) });
}
});
// Dynamic system to generate custom Sonsiz Yulduz questions based on user-entered topics
app.post("/api/generate-star-questions", async (req, res) => {
const { topic, language, difficulty = "medium", count = 10, previousSentences = [] } = req.body;
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
// Return count mock questions as high-quality simulated fallback
const mockQuestions = [];
const verbPool = ["play", "study", "work", "visit", "write", "speak", "learn", "watch", "read", "listen", "eat", "drink", "travel", "live", "buy", "sell", "understand", "explain", "choose", "receive"];
for (let i = 1; i <= count; i++) {
const verb = verbPool[(i + previousSentences.length) % verbPool.length];
mockQuestions.push({
id: `mockst_${previousSentences.length + i}`,
sentence: `[${topic} - ${difficulty.toUpperCase()} - Savol ${previousSentences.length + i}] Complete the sentence: We always ________ to improve our understanding of this topic.`,
options: [`${verb}s`, `${verb}`, `${verb}ing`, `to ${verb}`],
correct: verb,
hint: `Mavzu: ${topic} (${difficulty}). To'g'ri javob: '${verb}'. Berilgan mavzudagi grammatika qoidasi.`
});
}
return res.json({
success: true,
questions: mockQuestions
});
}
try {
const client = getGeminiClient();
let accumulatedQuestions: any[] = [];
let attempts = 0;
// We run in batches of 10 to safely generate the exact requested count of unique questions
while (accumulatedQuestions.length < count && attempts < 5) {
attempts++;
const batchSize = Math.min(10, count - accumulatedQuestions.length);
const currentExcluded = [...previousSentences, ...accumulatedQuestions.map(q => q.sentence)];
const prompt = `Chet tilini o'rganayotgan o'quvchilar uchun "${topic}" mavzusi bo'yicha ${batchSize} ta mutlaqo yangi, sifatli va takrorlanmas test savollarini yaratib bering.
Qiyinchilik darajasi: ${difficulty === 'easy' ? 'Boshlang\'ich (Easy - A1-A2)' : difficulty === 'hard' ? 'Qiyin (Hard - C1-C2)' : 'O\'rta (Medium - B1-B2)'}.
O'rganish tili: ${language === 'en' ? 'Ingliz tili' : 'Rus tili'}.
Interfeys va tushuntirish (hint) tili: O'zbekcha.
TAKRORLANMASLIK MAS'ULIYATI: Quyidagi savollar matnini umuman takrorlamang:
${JSON.stringify(currentExcluded.slice(-45))}
Har bir savol 4 ta variant (options) dan tashkil topgan ko'p tanlovli (multiple choice) test bo'lishi kerak. 'correct' maydoniga ushbu variantlardan aynan to'g'ri keladigan matnni o'zini yozing.
Quyidagi tizimli JSON formatini qaytaring:
{
"questions": [
{
"id": "q",
"sentence": "Savol matni (masalan: She _______ her homework every evening.)",
"options": ["do", "does", "doing", "done"],
"correct": "does",
"hint": "Qisqacha o'zbekcha qoida va tushuntirish"
}
]
}`;
const response = await generateContentWithFallback(client, {
contents: prompt,
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
questions: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
id: { type: Type.STRING },
sentence: { type: Type.STRING },
options: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
correct: { type: Type.STRING },
hint: { type: Type.STRING }
},
required: ["id", "sentence", "options", "correct", "hint"]
}
}
},
required: ["questions"]
}
}
});
const responseText = response.text;
if (responseText) {
const parsed = JSON.parse(responseText.trim());
if (parsed && parsed.questions && parsed.questions.length > 0) {
for (const q of parsed.questions) {
const duplicated = [...previousSentences, ...accumulatedQuestions.map(ea => ea.sentence)].some(existing =>
existing.toLowerCase().trim() === q.sentence.toLowerCase().trim()
);
if (!duplicated && accumulatedQuestions.length < count) {
q.id = `q_${previousSentences.length + accumulatedQuestions.length + 1}`;
accumulatedQuestions.push(q);
}
}
}
}
}
// Safe padding if still short of requested count
if (accumulatedQuestions.length < count) {
const remainingNeeded = count - accumulatedQuestions.length;
for (let i = 0; i < remainingNeeded; i++) {
const qIdNum = previousSentences.length + accumulatedQuestions.length + 1;
accumulatedQuestions.push({
id: `q_${qIdNum}`,
sentence: `[${topic} - ${difficulty.toUpperCase()} - Savol ${qIdNum}] Complete the phrase: We must ________ our lesson carefully.`,
options: ["studies", "study", "studying", "to study"],
correct: "study",
hint: "Must yordamchi fe'lidan keyin fe'lning asosi keladi."
});
}
}
return res.json({ success: true, questions: accumulatedQuestions });
} catch (e: any) {
console.error("Gemini star questions generation error:", e);
// Fallback
const mockQuestions = [];
const verbPool = ["play", "study", "work", "visit", "write", "speak", "learn", "watch", "read", "listen", "eat", "drink", "travel", "live", "buy", "sell", "understand", "explain", "choose", "receive"];
for (let i = 1; i <= count; i++) {
const verb = verbPool[(i + previousSentences.length) % verbPool.length];
mockQuestions.push({
id: `fbst_${previousSentences.length + i}`,
sentence: `[${topic} - Savol ${previousSentences.length + i}] Complete the sentence: I ________ English every single day to expand my skills.`,
options: [`${verb}s`, `${verb}`, `${verb}ing`, `to ${verb}`],
correct: verb,
hint: `Mavzu: ${topic}. To'g'ri javob: '${verb}'.`
});
}
return res.json({ success: true, questions: mockQuestions });
}
});
// Dynamic speaking practice phrase generator using Gemini
app.post("/api/generate-speaking-phrase", async (req, res) => {
const { language } = req.body;
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
const phrases = language === 'en' ? [
{ phrase: "Practice makes perfect in every venture.", translation: "Har bir ishda mashq mukammallikka yetaklaydi.", tip: "p va f tovushlarini portlovchi qilib, lablarni keng ochib talaffuz eting." },
{ phrase: "The climate is changing rapidly around the globe.", translation: "Butun dunyo bo'ylab iqlim juda tez o'zgarmoqda.", tip: "Climate so'zida c harfini k kabi va rapidly dagi r ni muloyim yengil ayting." }
] : [
{ phrase: "Повторение — мать истинного учения.", translation: "Takrorlash — haqiqiy bilimning onasidir.", tip: "p va t tovushlarini qattiq, r ni esa aniq titratib ayting." },
{ phrase: "Сегодня прекрасная погода для семейной прогулки в парке.", translation: "Bugun parkda oilaviy sayr qilish uchun ajoyib ob-havo.", tip: "сегодня dagi g tovushi v kabi o'qilishiga diqqat qiling." }
];
const selected = phrases[Math.floor(Math.random() * phrases.length)];
return res.json({ success: true, ...selected });
}
try {
const client = getGeminiClient();
const prompt = `Chet tilini o'rganayotgan yoshlar talaffuzi (speaking) mashqi uchun 1 ta mutlaqo yangi, hayotiy, foydali bo'lgan gap (phrase) yaratib bering.
O'rganish tili: ${language === 'en' ? 'Ingliz tili' : 'Rus tili'}.
Interfeys va maslahat tili: O'zbekcha.
Quyidagi tizimli JSON formatini qaytaring:
{
"phrase": "Yaratilgan gap (masalan: I want to optimize my accent.)",
"translation": "O'zbekcha tarjimasi (masalan: Men talaffuzimni yaxshilamoqchiman.)",
"tip": "Ushbu gapning to'g'ri va mukammal talaffuzi bo'yicha o'zbekcha qisqa va aniq 1 ta maslahat."
}`;
const response = await generateContentWithFallback(client, {
contents: prompt,
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
phrase: { type: Type.STRING },
translation: { type: Type.STRING },
tip: { type: Type.STRING }
},
required: ["phrase", "translation", "tip"]
}
}
});
const responseText = response.text;
if (responseText) {
const parsed = JSON.parse(responseText.trim());
return res.json({ success: true, ...parsed });
} else {
throw new Error("Bo'sh javob.");
}
} catch (e) {
console.error("Gemini speaking phrase generation error:", e);
return res.json({
success: true,
phrase: language === 'en' ? "Welcome to the future of immersive language learning!" : "Добро пожаловать в будущее интерактивного обучения!",
translation: language === 'en' ? "Immersiv til o'rganish kelajagiga xush kelibsiz!" : "Interaktiv ta'lim kelajagiga xush kelibsiz!",
tip: "Welcome so'zini boshida lablarni aylana (w) shakliga keltirib, keyin yoying."
});
}
});
// Vite middleware setup with standard configuration
let distPath = "";
console.log(`[Startup Info] process.cwd(): ${process.cwd()}`);
if (typeof __dirname !== "undefined") {
console.log(`[Startup Info] __dirname: ${__dirname}`);
const dirAbs = path.resolve(__dirname);
if (fs.existsSync(path.join(dirAbs, "index.html"))) {
distPath = dirAbs;
} else if (fs.existsSync(path.join(dirAbs, "dist", "index.html"))) {
distPath = path.join(dirAbs, "dist");
}
}
if (!distPath) {
const cwdAbs = path.resolve(process.cwd());
distPath = path.join(cwdAbs, 'dist');
if (!fs.existsSync(path.join(distPath, 'index.html'))) {
distPath = cwdAbs;
}
}
distPath = path.resolve(distPath);
const hasBuiltAssets = fs.existsSync(path.join(distPath, 'index.html'));
console.log(`[Startup Info] Resolved distPath: ${distPath}`);
console.log(`[Startup Info] hasBuiltAssets (index.html exists): ${hasBuiltAssets}`);
// Determine if we should run in production static mode
const isCompiledBundle = typeof __filename !== "undefined" && (__filename.endsWith(".cjs") || __filename.endsWith(".js") || __filename.includes("dist"));
const isProductionMode = process.env.NODE_ENV === "production" || isCompiledBundle;
if (!isProductionMode || !hasBuiltAssets) {
console.log("Starting server in development / on-demand compilation mode...");
// Dynamically import Vite only when needed in development to prevent load-time failures in production
const { createServer: createViteServer } = await import("vite");
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
// Serve index.html translated through Vite's dev server for SPA routes
app.get('*', async (req, res, next) => {
// Exclude API requests from being intercepted
if (req.originalUrl.startsWith('/api/')) {
return next();
}
try {
const htmlPath = path.resolve(process.cwd(), 'index.html');
if (fs.existsSync(htmlPath)) {
let template = fs.readFileSync(htmlPath, 'utf-8');
// Apply Vite's internal HTML transforms (resolves hot-module, scripts, CSS tags dynamically)
template = await vite.transformIndexHtml(req.originalUrl, template);
res.status(200).set({ 'Content-Type': 'text/html' }).end(template);
} else {
res.status(404).send("Error: index.html not found in development root.");
}
} catch (err) {
vite.ssrFixStacktrace(err as Error);
next(err);
}
});
} else {
console.log(`Starting server in production static mode... distPath=${distPath}`);
app.use(express.static(distPath));
app.get('*', (req, res) => {
const indexPath = path.join(distPath, 'index.html');
res.sendFile(indexPath, (err) => {
if (err) {
console.error(`Error sending index.html: ${err}`);
res.status(500).send(`Server Error: Failed to load application assets. distPath is "${distPath}". Please ensure the app has been built successfully.`);
}
});
});
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
// Fallback lesson contents
function getFallbackLesson(language: string, level: string, topic: string, title: string) {
const isEn = language === "en";
if (isEn) {
return {
success: true,
data: {
explanation: `### 📘 ${title || 'Lesson Overview'}\n\nUshbu dars Ingliz tilida so'zlashuv va muloqot qoidalarini rivojlantirishga qaratilgan.\n\n#### Qoidalar:\n1. **Sodda gaplar**: Ingliz tilida har doim subject + verb ko'rinishidan foydalaning. Masalan: *I like learning languages.*\n2. **Tushunish kalitlari**: Gap tuzishda fe'l va zamon mosligiga e'tibor qarating.\n\n#### Misollar:\n| Inglizcha | O'zbekcha tushunilishi | Izoh |\n| :--- | :--- | :--- |\n| *I am reading a book.* | Men kitob o'qiyapman. | Hozirgi davomli zamon. |\n| *We went to the beach.* | Biz plyajga bordik. | O'tgan zamon (Past Simple). |`,
exercises: [
{
title: "Mashiq 1: Fe'llarni moslashtirish",
questions: [
{ sentence: "She _______ her homework every evening.", options: ["do", "does", "doing", "done"], correctOption: 1 },
{ sentence: "They _______ football in the park yesterday.", options: ["play", "played", "playing", "plays"], correctOption: 1 },
{ sentence: "We are _______ our next family trip.", options: ["plan", "planning", "planned", "plans"], correctOption: 1 },
{ sentence: "He has _______ this film three times.", options: ["see", "saw", "seen", "seeing"], correctOption: 2 },
{ sentence: "If it rains, I _______ stay at home.", options: ["will", "would", "shall", "am"], correctOption: 0 },
{ sentence: "Listen! Somebody is _______ the piano.", options: ["play", "plays", "played", "playing"], correctOption: 3 }
]
},
{
title: "Mashiq 2: Predmet va so'z mosligi",
questions: [
{ sentence: "This is the most _______ book I have ever read.", options: ["interest", "interesting", "interested", "interests"], correctOption: 1 },
{ sentence: "Would you like _______ cup of tea?", options: ["another", "other", "others", "the other"], correctOption: 0 },
{ sentence: "She is afraid _______ spiders.", options: ["of", "at", "about", "with"], correctOption: 0 },
{ sentence: "We must protect _______ environment.", options: ["a", "an", "the", "no article"], correctOption: 2 },
{ sentence: "He Speaks English very _______.", options: ["good", "well", "better", "best"], correctOption: 1 },
{ sentence: "My brother is older _______ me.", options: ["then", "than", "to", "as"], correctOption: 1 }
]
}
],
homework: "Uyga vazifa:\nMavzuga aloqador kamida 5 ta gap yozing. Gaplaringizda hozirgi yoki o'tgan zamon fe'llaridan unumli foydalaning. Yozgan gaplaringizni toza qog'ozga ruchka bilan yozib, rasmga olib bu yerga yuklang."
}
}
} else {
return {
success: true,
data: {
explanation: `### 📘 ${title || 'Урок'}\n\nUshbu dars Rus tili grammatikasi va jumlalar tuzilishiga bag'ishlangan.\n\n#### Asosiy ma'lumotlar:\n1. **Rus tilida otlar va fe'llar mosligi**: Otlarning rodlari va unga mos ravishda fe'llarning o'zgarishini ko'rib chiqamiz. \n2. **Kelimelar kelishuvi**: *Я иду, ты идешь, он идет*.\n\n#### Misollar:\n| Ruscha gap | Tarjimasi | Izoh |\n| :--- | :--- | :--- |\n| *Я изучаю русский язык.* | Men rus tilini o'rganyapman. | Hozirgi zamon ko'rinishi |\n| *Мы купили новую книгу.* | Biz yangi kitob sotib oldik. | O'tgan zamonda ko'plik formasi |`,
exercises: [
{
title: "Упражнение 1: Глаголы и окончания",
questions: [
{ sentence: "Вчера мы _______ фильм в кинотеатре.", options: ["смотрим", "смотрели", "посмотреть", "смотрят"], correctOption: 1 },
{ sentence: "Я хочу _______ чаю с лимоном.", options: ["выпить", "пьет", "выпила", "выпивать"], correctOption: 0 },
{ sentence: "Она _______ в школе учителем русского языка.", options: ["работает", "работал", "работать", "работают"], correctOption: 0 },
{ sentence: "Ты уже _______ это домашнее задание?", options: ["сделать", "сделал", "делаешь", "сделаешь"], correctOption: 1 },
{ sentence: "Они _______ на поезде в Ташкент в следующую субботу.", options: ["поедут", "ехал", "поехали", "едет"], correctOption: 0 },
{ sentence: "Мы очень любим _______ в горах летом.", options: ["отдыхаем", "отдохнули", "отдыхать", "отдыхают"], correctOption: 2 }
]
},
{
title: "Упражнение 2: Падежи и предлоги",
questions: [
{ sentence: "Книга лежит _______ столе в комнате.", options: ["на", "в", "у", "над"], correctOption: 0 },
{ sentence: "Мы пошли гулять в парк _______ друзьями.", options: ["с", "к", "без", "около"], correctOption: 0 },
{ sentence: "Я часто звоню своим _______.", options: ["родители", "родителей", "родителям", "родителями"], correctOption: 2 },
{ sentence: "Она мечтает поехать _______ Москву летом.", options: ["в", "на", "к", "для"], correctOption: 0 },
{ sentence: "Этот подарок приготовлен _______ тебя.", options: ["для", "к", "без", "через"], correctOption: 0 },
{ sentence: "Они говорят _______ интересном проекте.", options: ["о", "в", "от", "для"], correctOption: 0 }
]
}
],
homework: "Домашнее задание:\nRus tilida ruscha fe'llar va otlar mos keladigan 5 ta chiroyli gap tuzing va daftarga yozing. So'ngra daftaringizni rasmga olib bu yerga tekshirish uchun yuklang."
}
}
}
}
// Generate fallback duel question
function getMockDuelQuestion(language: string, level: string) {
const isEn = language === "en";
if (isEn) {
const list = [
{ question: "Choose the correct past simple form of 'go':", options: ["goed", "goes", "gone", "went"], correctIndex: 3, explanation: "'go' fe'lining o'tgan zamoni noto'g'ri fe'llar jadvalida 'went' bo'ladi." },
{ question: "She is really good _______ playing soccer.", options: ["at", "in", "on", "for"], correctIndex: 0, explanation: "'good at doing something' iborasi biror narsaga qobiliyatli bo'lishni anglatadi." },
{ question: "I haven't seen him _______ five years.", options: ["since", "for", "during", "before"], correctIndex: 1, explanation: "Vaqt oralig'i (5 yil) ko'rsatilganligi sababli 'for' ishlatiladi." }
];
return list[Math.floor(Math.random() * list.length)];
} else {
const list = [
{ question: "Выберите правильное местоимение: Это книга _______.", options: ["мой", "моя", "мое", "мои"], correctIndex: 1, explanation: "'Книга' женский род (ая) bo'lganligi sababli 'моя' bo'ladi." },
{ question: "Как будет правильно: Я еду _______ автобусе.", options: ["на", "в", "к", "о"], correctIndex: 0, explanation: "Transportda harakatlanish uchun ko'pincha 'на автобусе' ishlatiladi." },
{ question: "Вчера мы _______ в новый музей.", options: ["идем", "ходили", "пойти", "идешь"], correctIndex: 1, explanation: "O'tgan zamonda bir necha bor borib kelishni ko'rsatish uchun 'ходили' ishlatiladi." }
];
return list[Math.floor(Math.random() * list.length)];
}
}
// Generate fallback study topic resources if Gemini key is missing
function getFallbackStudyTopic(topic: string, explanationLanguage: string) {
const t = topic || "Noma'lum Mavzu";
const langLabel = explanationLanguage === 'uz' ? 'O\'zbekcha' : explanationLanguage === 'ru' ? 'Ruscha' : 'Inglizcha';
return {
success: true,
topicTitle: t,
explanation: `### 📘 ${t} (Tushuntirish tili: ${langLabel})\n\nUshbu dars **${t}** mavzusini chuqur o'rganishga bag'ishlangan.\n\n#### 🌟 Mavzu Qoidalari va Tahlili:\n1. **Chuqur Tushuncha**: To'g'ri o'rganish sizning chet tilida erkin so'zlashingizni kafolatlaydi. Ushbu darsda tahlil qilingan grammatik, talaffuz va amaliy foydalanish qoidalariga diqqat qiling.\n2. **Tavsiyalar**: Kundalik nutqda ushbu dars qoidalariga mos misollarni ko'p qo'llang va so'z boyligini kengaytiring.\n\n#### 📝 Foydali Misollar:\n* *Today is a great day to practice.* - Bugun mashiq qilish uchun ajoyib kun.\n* *Practice makes perfect.* - Amaliyot mukammallikka yetaklaydi.\n\n[Simulyatsiya rejimi]: Tizim to'liq Gemini API orqali ishlashi uchun AI Studio Secrets orqali \`GEMINI_API_KEY\` ni qo'shing. Ushbu dars namunaviy shakllantirildi.`,
exercises: [
{ sentence: `Siz hozirgina "${t}" mavzusini o'rgandingiz. Ushbu mavzuga mos eng to'g'ri bog'lovchini tanlang: "She is afraid ______ spiders."`, options: ["of", "at", "about", "with"], correctOption: 0 },
{ sentence: `Mavzu bo'yicha eng to'g'ri fe'l shaklini tanlang: "We ______ to work tomorrow."`, options: ["will go", "went", "going", "goes"], correctOption: 0 },
{ sentence: `Mazmun jihatidan quyidagilardan qaysi biri to'g'ri? "They ______ soccer right now."`, options: ["are playing", "plays", "played", "play"], correctOption: 0 },
{ sentence: `Qaysi variant to'g'ri tanlangan? "This is ______ orange book."`, options: ["an", "a", "the", "no article"], correctOption: 0 }
],
homework: `Uyga vazifa:\n"${t}" mavzusiga doir eng muhim 3 ta qoidani daftaringizga o'zbek tilida yozing, dars so'zlaridan foydalanib 3 ta gap tuzing. Uni ruchka bilan toza qog'ozga yozib rasmga tushiring va bu yerga yuklang yoki quyidagi matn maydoniga yozib yuboring.`
};
}
// Generate fallback mega exam of 60 questions if Gemini key is missing
function getFallbackMegaExam(topics: string[], language: string) {
const quizQuestions: any[] = [];
const listTopics = (topics && topics.length >= 5) ? topics.slice(0, 5) : ["Present Simple", "Kelishiklar (Падежи)", "Past Simple", "Predloqlar (Предлоги)", "Present Perfect"];
// For each of the 5 topics, generate 12 questions
listTopics.forEach((topic) => {
for (let i = 1; i <= 12; i++) {
quizQuestions.push({
q: `[${topic}] bo'yicha ${i}-nazorat savoli: Ushbu qoidaga mos eng ma'qul gap yoki fe'l shaklini belgilang.`,
options: [
`To'g'ri javob varianti (${topic} qoidasi bo'yicha)`,
`Noto'g'ri variant A (${topic})`,
`Noto'g'ri variant B (${topic})`,
`Noto'g'ri variant C (${topic})`
],
correct: 0,
topic: topic
});
}
});
return { success: true, questions: quizQuestions };
}
startServer();
import express from "express";
import path from "path";
import fs from "fs";
import { GoogleGenAI, Type } from "@google/genai";
import dotenv from "dotenv";
import multer from "multer";
dotenv.config();
// Create uploads directory if it doesn't exist
const uploadsDir = path.join(process.cwd(), "uploads");
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
// Multer storage setup
const multerStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadsDir);
},
filename: (req, file, cb) => {
// Sanitary file name replacement to ensure it's ASCII/URL safe
const safeName = file.originalname.replace(/[^a-zA-Z0-9.\-_]/g, "_");
cb(null, `${Date.now()}_${safeName}`);
}
});
// Configure upload limits - up to 1GB
const upload = multer({
storage: multerStorage,
limits: { fileSize: 1024 * 1024 * 1024 } // 1GB limit
});
let aiClient: GoogleGenAI | null = null;
function getGeminiClient(): GoogleGenAI {
if (!aiClient) {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
console.warn("WARN: GEMINI_API_KEY is not defined in environment variables.");
}
aiClient = new GoogleGenAI({
apiKey: apiKey || "MOCK_KEY_UNUSED",
httpOptions: {
headers: {
'User-Agent': 'aistudio-build',
}
}
});
}
return aiClient;
}
// Helper function to call generateContent with retry and fallback models to prevent 503 UNAVAILABLE errors
async function generateContentWithFallback(client: GoogleGenAI, originalParams: any) {
const modelsToTry = [
"gemini-3.5-flash",
"gemini-3.1-flash-lite",
"gemini-flash-latest"
];
let lastError: any = null;
for (const modelName of modelsToTry) {
let retries = 2; // 2 retries per model
while (retries >= 0) {
try {
const response = await client.models.generateContent({
...originalParams,
model: modelName
});
return response;
} catch (err: any) {
lastError = err;
const errMsg = String(err.message || err);
console.warn(`Attempt with model ${modelName} failed (retries left: ${retries}). Error: ${errMsg}`);
// If it's a 503 (Overloaded / Unavailable) or 429 (Rate limit) or "high demand"
if (
errMsg.includes("503") ||
errMsg.includes("UNAVAILABLE") ||
errMsg.includes("429") ||
errMsg.includes("RESOURCE_EXHAUSTED") ||
errMsg.includes("demand") ||
errMsg.includes("overloaded") ||
errMsg.includes("spikes")
) {
retries--;
if (retries >= 0) {
const waitTime = (2 - retries) * 1000; // 1000ms, then 2000ms
await new Promise((resolve) => setTimeout(resolve, waitTime));
continue;
}
} else {
// For syntax / user-facing errors, don't retry, just fail-over early or throw
break;
}
}
}
}