Delete routes
Browse files- routes/agent.js +0 -224
- routes/audio.js +0 -50
- routes/chat.js +0 -92
- routes/image.js +0 -76
- routes/proxy.js +0 -31
- routes/search.js +0 -84
- routes/title.js +0 -41
- routes/upload.js +0 -66
routes/agent.js
DELETED
|
@@ -1,224 +0,0 @@
|
|
| 1 |
-
import express from "express";
|
| 2 |
-
import { Document, Packer, Paragraph, HeadingLevel, TextRun, AlignmentType, BorderStyle } from "docx";
|
| 3 |
-
import PptxGenJS from "pptxgenjs";
|
| 4 |
-
import ExcelJS from "exceljs";
|
| 5 |
-
import PDFDocument from "pdfkit";
|
| 6 |
-
|
| 7 |
-
const router = express.Router();
|
| 8 |
-
const PURPLE = "7C3AED";
|
| 9 |
-
const LIGHT = "F3E8FF";
|
| 10 |
-
|
| 11 |
-
function sendBuffer(res, buf, filename, mime) {
|
| 12 |
-
res.setHeader("Content-Type", mime);
|
| 13 |
-
res.setHeader("Content-Disposition", `attachment; filename="${encodeURIComponent(filename)}"`);
|
| 14 |
-
res.send(buf);
|
| 15 |
-
}
|
| 16 |
-
|
| 17 |
-
/* ---- قراءة مرنة للمحتوى ---- */
|
| 18 |
-
// يحوّل أي شكل قد يرسله النموذج إلى مصفوفة فقرات/أقسام موحّدة
|
| 19 |
-
function normalizeBlocks(content) {
|
| 20 |
-
const blocks = [];
|
| 21 |
-
if (!content) return blocks;
|
| 22 |
-
if (typeof content === "string") { blocks.push({ type: "p", text: content }); return blocks; }
|
| 23 |
-
if (content.heading) blocks.push({ type: "h", text: content.heading });
|
| 24 |
-
// paragraphs
|
| 25 |
-
(content.paragraphs || []).forEach(p => blocks.push({ type: "p", text: asText(p) }));
|
| 26 |
-
// sections: {title, body|content|text|bullets}
|
| 27 |
-
(content.sections || []).forEach(s => {
|
| 28 |
-
if (s.title) blocks.push({ type: "h", text: s.title });
|
| 29 |
-
const body = s.body || s.content || s.text;
|
| 30 |
-
if (body) blocks.push({ type: "p", text: asText(body) });
|
| 31 |
-
(s.bullets || s.points || []).forEach(b => blocks.push({ type: "li", text: asText(b) }));
|
| 32 |
-
});
|
| 33 |
-
// bullets/points على المستوى الأعلى
|
| 34 |
-
(content.bullets || content.points || []).forEach(b => blocks.push({ type: "li", text: asText(b) }));
|
| 35 |
-
return blocks;
|
| 36 |
-
}
|
| 37 |
-
function asText(v) {
|
| 38 |
-
if (v == null) return "";
|
| 39 |
-
if (typeof v === "string") return v;
|
| 40 |
-
if (Array.isArray(v)) return v.map(asText).join("\n");
|
| 41 |
-
if (typeof v === "object") return v.text || v.body || v.content || JSON.stringify(v);
|
| 42 |
-
return String(v);
|
| 43 |
-
}
|
| 44 |
-
// للعروض: استخرج شرائح موحّدة {title, bullets[]}
|
| 45 |
-
function normalizeSlides(content, fallbackTitle) {
|
| 46 |
-
let slides = [];
|
| 47 |
-
if (content?.slides?.length) {
|
| 48 |
-
slides = content.slides.map(s => ({
|
| 49 |
-
title: s.title || s.heading || fallbackTitle || "",
|
| 50 |
-
bullets: normalizeBullets(s),
|
| 51 |
-
}));
|
| 52 |
-
} else {
|
| 53 |
-
// اصنع شرائح من sections أو paragraphs
|
| 54 |
-
const secs = content?.sections || [];
|
| 55 |
-
if (secs.length) {
|
| 56 |
-
slides = secs.map(s => ({ title: s.title || "", bullets: normalizeBullets(s) }));
|
| 57 |
-
} else {
|
| 58 |
-
slides = [{ title: fallbackTitle || "Slide", bullets: (content?.paragraphs || []).map(asText) }];
|
| 59 |
-
}
|
| 60 |
-
}
|
| 61 |
-
return slides.filter(s => s.title || (s.bullets && s.bullets.length));
|
| 62 |
-
}
|
| 63 |
-
function normalizeBullets(s) {
|
| 64 |
-
if (Array.isArray(s.bullets)) return s.bullets.map(asText);
|
| 65 |
-
if (Array.isArray(s.points)) return s.points.map(asText);
|
| 66 |
-
const body = s.body || s.content || s.text;
|
| 67 |
-
if (Array.isArray(body)) return body.map(asText);
|
| 68 |
-
if (typeof body === "string") return body.split(/\n|•/).map(x => x.trim()).filter(Boolean);
|
| 69 |
-
return [];
|
| 70 |
-
}
|
| 71 |
-
|
| 72 |
-
/* ---- WORD (تصميم جميل) ---- */
|
| 73 |
-
async function buildDocx(title, content) {
|
| 74 |
-
const blocks = normalizeBlocks(content);
|
| 75 |
-
const children = [
|
| 76 |
-
new Paragraph({
|
| 77 |
-
alignment: AlignmentType.CENTER,
|
| 78 |
-
spacing: { after: 300 },
|
| 79 |
-
border: { bottom: { color: PURPLE, space: 6, style: BorderStyle.SINGLE, size: 18 } },
|
| 80 |
-
children: [new TextRun({ text: title || "Document", bold: true, size: 48, color: PURPLE })],
|
| 81 |
-
}),
|
| 82 |
-
];
|
| 83 |
-
for (const b of blocks) {
|
| 84 |
-
if (b.type === "h")
|
| 85 |
-
children.push(new Paragraph({ spacing: { before: 200, after: 100 }, children: [new TextRun({ text: b.text, bold: true, size: 30, color: PURPLE })] }));
|
| 86 |
-
else if (b.type === "li")
|
| 87 |
-
children.push(new Paragraph({ bullet: { level: 0 }, spacing: { after: 60 }, children: [new TextRun({ text: b.text, size: 24 })] }));
|
| 88 |
-
else
|
| 89 |
-
children.push(new Paragraph({ spacing: { after: 120 }, children: [new TextRun({ text: b.text, size: 24 })] }));
|
| 90 |
-
}
|
| 91 |
-
if (blocks.length === 0) children.push(new Paragraph({ children: [new TextRun(asText(content))] }));
|
| 92 |
-
const doc = new Document({ sections: [{ children }] });
|
| 93 |
-
return Packer.toBuffer(doc);
|
| 94 |
-
}
|
| 95 |
-
|
| 96 |
-
/* ---- POWERPOINT (قالب إبداعي + أنيميشن) ---- */
|
| 97 |
-
async function buildPptx(title, content) {
|
| 98 |
-
const pptx = new PptxGenJS();
|
| 99 |
-
pptx.defineLayout({ name: "WIDE", width: 13.333, height: 7.5 });
|
| 100 |
-
pptx.layout = "WIDE";
|
| 101 |
-
|
| 102 |
-
// قالب رئيسي بخلفية متدرّجة وأشكال
|
| 103 |
-
pptx.defineSlideMaster({
|
| 104 |
-
title: "GENISI",
|
| 105 |
-
background: { color: "FFFFFF" },
|
| 106 |
-
objects: [
|
| 107 |
-
{ rect: { x: 0, y: 0, w: 13.333, h: 0.25, fill: { color: PURPLE } } },
|
| 108 |
-
{ rect: { x: 0, y: 7.25, w: 13.333, h: 0.25, fill: { color: "C084FC" } } },
|
| 109 |
-
],
|
| 110 |
-
});
|
| 111 |
-
|
| 112 |
-
// شريحة العنوان
|
| 113 |
-
const cover = pptx.addSlide({ masterName: "GENISI" });
|
| 114 |
-
cover.background = { color: PURPLE };
|
| 115 |
-
cover.addShape(pptx.ShapeType.ellipse, { x: 10.5, y: -1.5, w: 4, h: 4, fill: { color: "9333EA" } });
|
| 116 |
-
cover.addShape(pptx.ShapeType.ellipse, { x: -1, y: 5, w: 3.5, h: 3.5, fill: { color: "A855F7" } });
|
| 117 |
-
cover.addText(title || "Presentation", { x: 0.8, y: 2.8, w: 11.7, h: 1.5, fontSize: 44, bold: true, color: "FFFFFF", align: "center" });
|
| 118 |
-
cover.addText("Genisi", { x: 0.8, y: 4.4, w: 11.7, h: 0.6, fontSize: 18, color: "E9D5FF", align: "center" });
|
| 119 |
-
|
| 120 |
-
const slides = normalizeSlides(content, title);
|
| 121 |
-
slides.forEach((s, idx) => {
|
| 122 |
-
const slide = pptx.addSlide({ masterName: "GENISI" });
|
| 123 |
-
// شكل زخرفي
|
| 124 |
-
slide.addShape(pptx.ShapeType.roundRect, { x: 0.5, y: 0.5, w: 0.5, h: 0.9, fill: { color: PURPLE }, rectRadius: 0.1 });
|
| 125 |
-
slide.addText(s.title || `Slide ${idx + 1}`, { x: 1.2, y: 0.5, w: 11, h: 0.9, fontSize: 30, bold: true, color: PURPLE });
|
| 126 |
-
// نقاط مع أنيميشن (ظهور تدريجي عبر options)
|
| 127 |
-
const bullets = (s.bullets || []).map(b => ({ text: b, options: { bullet: { code: "2022" }, fontSize: 20, color: "1F2937", paraSpaceAfter: 10 } }));
|
| 128 |
-
if (bullets.length) {
|
| 129 |
-
slide.addText(bullets, { x: 1.2, y: 1.7, w: 11, h: 5, valign: "top" });
|
| 130 |
-
}
|
| 131 |
-
// أنيميشن: تأثير دخول للشريحة (transition)
|
| 132 |
-
slide.transition = { type: "fade", duration: 0.6 };
|
| 133 |
-
slide.addText(`${idx + 1}`, { x: 12.4, y: 6.7, w: 0.7, h: 0.4, fontSize: 12, color: "9CA3AF", align: "right" });
|
| 134 |
-
});
|
| 135 |
-
|
| 136 |
-
const data = await pptx.write("nodebuffer");
|
| 137 |
-
return Buffer.isBuffer(data) ? data : Buffer.from(data);
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
/* ---- EXCEL (تصميم جميل) ---- */
|
| 141 |
-
async function buildXlsx(title, content) {
|
| 142 |
-
const wb = new ExcelJS.Workbook();
|
| 143 |
-
wb.creator = "Genisi";
|
| 144 |
-
const sheets = content?.sheets?.length
|
| 145 |
-
? content.sheets
|
| 146 |
-
: [{ name: title || "Sheet1", headers: content?.headers || [], rows: content?.rows || [] }];
|
| 147 |
-
sheets.forEach(sh => {
|
| 148 |
-
const ws = wb.addWorksheet((sh.name || "Sheet").slice(0, 31));
|
| 149 |
-
if (sh.headers?.length) {
|
| 150 |
-
const hr = ws.addRow(sh.headers);
|
| 151 |
-
hr.eachCell(c => {
|
| 152 |
-
c.font = { bold: true, color: { argb: "FFFFFFFF" } };
|
| 153 |
-
c.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FF7C3AED" } };
|
| 154 |
-
c.alignment = { horizontal: "center", vertical: "middle" };
|
| 155 |
-
c.border = { bottom: { style: "thin", color: { argb: "FFCCCCCC" } } };
|
| 156 |
-
});
|
| 157 |
-
}
|
| 158 |
-
(sh.rows || []).forEach((r, i) => {
|
| 159 |
-
const row = ws.addRow(r);
|
| 160 |
-
if (i % 2) row.eachCell(c => (c.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFF6F0FF" } }));
|
| 161 |
-
});
|
| 162 |
-
ws.columns.forEach(c => (c.width = 22));
|
| 163 |
-
});
|
| 164 |
-
const buf = await wb.xlsx.writeBuffer();
|
| 165 |
-
return Buffer.from(buf);
|
| 166 |
-
}
|
| 167 |
-
|
| 168 |
-
function buildCsv(content) {
|
| 169 |
-
const headers = content?.headers || content?.sheets?.[0]?.headers || [];
|
| 170 |
-
const rows = content?.rows || content?.sheets?.[0]?.rows || [];
|
| 171 |
-
const esc = v => `"${String(v ?? "").replace(/"/g, '""')}"`;
|
| 172 |
-
const lines = [];
|
| 173 |
-
if (headers.length) lines.push(headers.map(esc).join(","));
|
| 174 |
-
rows.forEach(r => lines.push(r.map(esc).join(",")));
|
| 175 |
-
return Buffer.from("\uFEFF" + lines.join("\n"), "utf8");
|
| 176 |
-
}
|
| 177 |
-
|
| 178 |
-
/* ---- PDF (تصميم جميل) ---- */
|
| 179 |
-
function buildPdf(title, content) {
|
| 180 |
-
return new Promise((resolve, reject) => {
|
| 181 |
-
const doc = new PDFDocument({ margin: 54, size: "A4" });
|
| 182 |
-
const chunks = [];
|
| 183 |
-
doc.on("data", c => chunks.push(c));
|
| 184 |
-
doc.on("end", () => resolve(Buffer.concat(chunks)));
|
| 185 |
-
doc.on("error", reject);
|
| 186 |
-
|
| 187 |
-
// شريط علوي
|
| 188 |
-
doc.rect(0, 0, doc.page.width, 70).fill("#7C3AED");
|
| 189 |
-
doc.fillColor("#fff").fontSize(24).text(title || "Document", 54, 26, { width: doc.page.width - 108 });
|
| 190 |
-
doc.moveDown(2).fillColor("#000");
|
| 191 |
-
|
| 192 |
-
const blocks = normalizeBlocks(content);
|
| 193 |
-
if (blocks.length === 0) { doc.fontSize(12).text(asText(content)); doc.end(); return; }
|
| 194 |
-
let y = 100;
|
| 195 |
-
doc.y = y;
|
| 196 |
-
for (const b of blocks) {
|
| 197 |
-
if (b.type === "h") { doc.moveDown(0.6).fontSize(15).fillColor("#7C3AED").text(b.text); doc.fillColor("#000"); }
|
| 198 |
-
else if (b.type === "li") { doc.fontSize(12).fillColor("#000").text("• " + b.text, { indent: 12 }); }
|
| 199 |
-
else { doc.fontSize(12).fillColor("#000").text(b.text); }
|
| 200 |
-
doc.moveDown(0.3);
|
| 201 |
-
}
|
| 202 |
-
doc.end();
|
| 203 |
-
});
|
| 204 |
-
}
|
| 205 |
-
|
| 206 |
-
router.post("/document", async (req, res) => {
|
| 207 |
-
try {
|
| 208 |
-
const { format = "pdf", title = "Genisi Document", content = {} } = req.body;
|
| 209 |
-
const safe = (title || "document").replace(/[^\w\u0600-\u06FF\- ]/g, "_").slice(0, 60);
|
| 210 |
-
switch (format) {
|
| 211 |
-
case "docx": return sendBuffer(res, await buildDocx(title, content), `${safe}.docx`, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
|
| 212 |
-
case "pptx": return sendBuffer(res, await buildPptx(title, content), `${safe}.pptx`, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
|
| 213 |
-
case "xlsx": return sendBuffer(res, await buildXlsx(title, content), `${safe}.xlsx`, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
| 214 |
-
case "csv": return sendBuffer(res, buildCsv(content), `${safe}.csv`, "text/csv; charset=utf-8");
|
| 215 |
-
case "pdf":
|
| 216 |
-
default: return sendBuffer(res, await buildPdf(title, content), `${safe}.pdf`, "application/pdf");
|
| 217 |
-
}
|
| 218 |
-
} catch (err) {
|
| 219 |
-
console.error("document error:", err);
|
| 220 |
-
res.status(500).json({ error: "document_failed", message: String(err?.message || err) });
|
| 221 |
-
}
|
| 222 |
-
});
|
| 223 |
-
|
| 224 |
-
export default router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
routes/audio.js
DELETED
|
@@ -1,50 +0,0 @@
|
|
| 1 |
-
import express from "express";
|
| 2 |
-
import { MsEdgeTTS, OUTPUT_FORMAT } from "msedge-tts";
|
| 3 |
-
|
| 4 |
-
const router = express.Router();
|
| 5 |
-
|
| 6 |
-
// إزالة الإيموجي والرموز قبل النطق
|
| 7 |
-
function stripEmoji(text) {
|
| 8 |
-
return text
|
| 9 |
-
.replace(/[\u{1F000}-\u{1FAFF}\u{2600}-\u{27BF}\u{1F1E6}-\u{1F1FF}\u{2190}-\u{21FF}\u{2B00}-\u{2BFF}\uFE0F\u200D]/gu, "")
|
| 10 |
-
.replace(/[`*_#>~]/g, "")
|
| 11 |
-
.replace(/\s+/g, " ")
|
| 12 |
-
.trim();
|
| 13 |
-
}
|
| 14 |
-
|
| 15 |
-
// اختيار صوت مناسب حسب لغة النص
|
| 16 |
-
function pickVoice(text) {
|
| 17 |
-
const hasArabic = /[\u0600-\u06FF]/.test(text);
|
| 18 |
-
const hasFrench = /[àâçéèêëîïôûùüÿœ]/i.test(text);
|
| 19 |
-
if (hasArabic) return "ar-DZ-AminaNeural"; // عربي (لهجة جزائرية)
|
| 20 |
-
if (hasFrench) return "fr-FR-DeniseNeural"; // فرنسي
|
| 21 |
-
return "en-US-AriaNeural"; // إنجليزي افتراضي
|
| 22 |
-
}
|
| 23 |
-
|
| 24 |
-
// POST /api/tts { text } -> audio/mpeg
|
| 25 |
-
router.post("/tts", async (req, res) => {
|
| 26 |
-
try {
|
| 27 |
-
const raw = (req.body?.text || "").toString();
|
| 28 |
-
const text = stripEmoji(raw);
|
| 29 |
-
if (!text) return res.status(400).json({ error: "empty_text" });
|
| 30 |
-
|
| 31 |
-
const voice = pickVoice(text);
|
| 32 |
-
const tts = new MsEdgeTTS();
|
| 33 |
-
await tts.setMetadata(voice, OUTPUT_FORMAT.AUDIO_24KHZ_48KBITRATE_MONO_MP3);
|
| 34 |
-
|
| 35 |
-
const { audioStream } = tts.toStream(text);
|
| 36 |
-
res.setHeader("Content-Type", "audio/mpeg");
|
| 37 |
-
audioStream.on("data", (d) => res.write(d));
|
| 38 |
-
audioStream.on("end", () => res.end());
|
| 39 |
-
audioStream.on("error", (e) => {
|
| 40 |
-
console.error("tts stream error:", e);
|
| 41 |
-
if (!res.headersSent) res.status(500).json({ error: "tts_failed" });
|
| 42 |
-
else res.end();
|
| 43 |
-
});
|
| 44 |
-
} catch (err) {
|
| 45 |
-
console.error("tts error:", err);
|
| 46 |
-
if (!res.headersSent) res.status(500).json({ error: "tts_failed", message: String(err?.message || err) });
|
| 47 |
-
}
|
| 48 |
-
});
|
| 49 |
-
|
| 50 |
-
export default router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
routes/chat.js
DELETED
|
@@ -1,92 +0,0 @@
|
|
| 1 |
-
import express from "express";
|
| 2 |
-
import OpenAI from "openai";
|
| 3 |
-
import { buildSystemPrompt } from "../lib/systemPrompt.js";
|
| 4 |
-
import { MODEL_CAPS } from "../lib/modelCaps.js";
|
| 5 |
-
|
| 6 |
-
const router = express.Router();
|
| 7 |
-
|
| 8 |
-
// خريطة النماذج في Pollinations.ai
|
| 9 |
-
const MODEL_MAP = {
|
| 10 |
-
flash: "polly", // سريع وذكي
|
| 11 |
-
pro: "gemini-flash", // أكثر دقة مع تفكير
|
| 12 |
-
};
|
| 13 |
-
|
| 14 |
-
const pollinations = new OpenAI({
|
| 15 |
-
apiKey: "sk_FIXoxsQ3GBtb5jOsgp1sVOgspge37i0z",
|
| 16 |
-
baseURL: "https://gen.pollinations.ai/v1",
|
| 17 |
-
});
|
| 18 |
-
|
| 19 |
-
function normalizeMessage(m, caps) {
|
| 20 |
-
const role = m.role === "assistant" ? "assistant" : "user";
|
| 21 |
-
const atts = Array.isArray(m.attachments) ? m.attachments : [];
|
| 22 |
-
const images = atts.filter(a => a && a.kind === "image" && a.dataUrl);
|
| 23 |
-
const texts = atts.filter(a => a && a.kind === "text" && a.text);
|
| 24 |
-
|
| 25 |
-
let textContent = (m.content || "").toString();
|
| 26 |
-
for (const d of texts) textContent += `\n\n[Attached file: ${d.name}]\n${d.text}`;
|
| 27 |
-
|
| 28 |
-
if (caps.vision && images.length) {
|
| 29 |
-
const parts = [];
|
| 30 |
-
if (textContent.trim()) parts.push({ type: "text", text: textContent });
|
| 31 |
-
for (const img of images) parts.push({ type: "image_url", image_url: { url: img.dataUrl } });
|
| 32 |
-
if (parts.length) return { role, content: parts };
|
| 33 |
-
}
|
| 34 |
-
return { role, content: textContent.trim() || " " };
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
router.post("/chat", async (req, res) => {
|
| 38 |
-
try {
|
| 39 |
-
const { messages = [], model = "flash", user = {}, interests = [], think = false } = req.body;
|
| 40 |
-
const modelId = MODEL_MAP[model] || MODEL_MAP.flash;
|
| 41 |
-
const caps = MODEL_CAPS[model] || MODEL_CAPS.flash;
|
| 42 |
-
|
| 43 |
-
const cleaned = (Array.isArray(messages) ? messages : [])
|
| 44 |
-
.filter(m => m && (m.role === "user" || m.role === "assistant"))
|
| 45 |
-
.map(m => normalizeMessage(m, caps))
|
| 46 |
-
.filter(m => (typeof m.content === "string" ? m.content.trim().length > 0 : Array.isArray(m.content) && m.content.length > 0));
|
| 47 |
-
|
| 48 |
-
if (!cleaned.length) return res.status(400).json({ error: "empty_messages" });
|
| 49 |
-
|
| 50 |
-
let sys = buildSystemPrompt(user, interests);
|
| 51 |
-
if (!think) sys += `\n\n# وضع الإجابة المباشرة\nلا تُظهر أي مرحلة تفكير. لا تكتب "Thinking..." إطلاقاً. أجب مباشرةً.`;
|
| 52 |
-
const fullMessages = [{ role: "system", content: sys }, ...cleaned];
|
| 53 |
-
|
| 54 |
-
res.setHeader("Content-Type", "text/event-stream");
|
| 55 |
-
res.setHeader("Cache-Control", "no-cache");
|
| 56 |
-
res.setHeader("Connection", "keep-alive");
|
| 57 |
-
res.flushHeaders?.();
|
| 58 |
-
|
| 59 |
-
let stream;
|
| 60 |
-
try {
|
| 61 |
-
stream = await pollinations.chat.completions.create({
|
| 62 |
-
model: modelId,
|
| 63 |
-
messages: fullMessages,
|
| 64 |
-
stream: false,
|
| 65 |
-
});
|
| 66 |
-
} catch (e) {
|
| 67 |
-
console.error("pollinations create error:", e?.error || e?.message || e);
|
| 68 |
-
res.write(`data: ${JSON.stringify({ error: "Model error. Try again or switch model." })}\n\n`);
|
| 69 |
-
return res.end();
|
| 70 |
-
}
|
| 71 |
-
|
| 72 |
-
try {
|
| 73 |
-
for await (const chunk of stream) {
|
| 74 |
-
const delta = chunk?.choices?.[0]?.delta?.content || "";
|
| 75 |
-
if (delta) res.write(`data: ${JSON.stringify({ delta })}\n\n`);
|
| 76 |
-
}
|
| 77 |
-
} catch (e) {
|
| 78 |
-
console.error("pollinations stream error:", e?.error || e?.message || e);
|
| 79 |
-
res.write(`data: ${JSON.stringify({ error: "Streaming interrupted. Please retry." })}\n\n`);
|
| 80 |
-
return res.end();
|
| 81 |
-
}
|
| 82 |
-
|
| 83 |
-
res.write(`data: ${JSON.stringify({ done: true })}\n\n`);
|
| 84 |
-
res.end();
|
| 85 |
-
} catch (err) {
|
| 86 |
-
console.error("chat error:", err?.error || err?.message || err);
|
| 87 |
-
if (!res.headersSent) res.status(500).json({ error: "chat_failed", message: String(err?.message || err) });
|
| 88 |
-
else { res.write(`data: ${JSON.stringify({ error: String(err?.message || err) })}\n\n`); res.end(); }
|
| 89 |
-
}
|
| 90 |
-
});
|
| 91 |
-
|
| 92 |
-
export default router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
routes/image.js
DELETED
|
@@ -1,76 +0,0 @@
|
|
| 1 |
-
import express from "express";
|
| 2 |
-
import fetch from "node-fetch";
|
| 3 |
-
import { checkUserQuota, recordUserHit, enqueue } from "../lib/rateLimiter.js";
|
| 4 |
-
|
| 5 |
-
const router = express.Router();
|
| 6 |
-
const INVOKE_URL = "https://ai.api.nvidia.com/v1/genai/black-forest-labs/flux.1-dev";
|
| 7 |
-
|
| 8 |
-
// POST /api/image { prompt, clientId }
|
| 9 |
-
router.post("/image", async (req, res) => {
|
| 10 |
-
try {
|
| 11 |
-
const { prompt, clientId = "anon" } = req.body;
|
| 12 |
-
if (!prompt || !prompt.trim()) {
|
| 13 |
-
return res.status(400).json({ error: "missing_prompt" });
|
| 14 |
-
}
|
| 15 |
-
|
| 16 |
-
// حد المستخدم: 3 صور / 3 ساعات
|
| 17 |
-
const quota = checkUserQuota(clientId);
|
| 18 |
-
if (!quota.allowed) {
|
| 19 |
-
const mins = Math.ceil(quota.retryMs / 60000);
|
| 20 |
-
return res.status(429).json({
|
| 21 |
-
error: "rate_limited",
|
| 22 |
-
message: `وصلت إلى حد 3 صور كل 3 ساعات. حاول مجدداً بعد ${mins} دقيقة.`,
|
| 23 |
-
retryMs: quota.retryMs,
|
| 24 |
-
});
|
| 25 |
-
}
|
| 26 |
-
|
| 27 |
-
// إعدادات واقعية ودقيقة جداً
|
| 28 |
-
const payload = {
|
| 29 |
-
prompt: `${prompt}, ultra realistic, highly detailed, photorealistic, 8k, sharp focus, natural lighting, professional photography`,
|
| 30 |
-
mode: "base",
|
| 31 |
-
cfg_scale: 3.5,
|
| 32 |
-
width: 1024,
|
| 33 |
-
height: 1024,
|
| 34 |
-
seed: Math.floor(Math.random() * 1_000_000),
|
| 35 |
-
steps: 50,
|
| 36 |
-
};
|
| 37 |
-
|
| 38 |
-
// عبر الطابور العالمي (<= 40/دقيقة)
|
| 39 |
-
const data = await enqueue(async () => {
|
| 40 |
-
const r = await fetch(INVOKE_URL, {
|
| 41 |
-
method: "POST",
|
| 42 |
-
headers: {
|
| 43 |
-
Authorization: `Bearer ${process.env.NVIDIA_API_KEY}`,
|
| 44 |
-
Accept: "application/json",
|
| 45 |
-
"Content-Type": "application/json",
|
| 46 |
-
},
|
| 47 |
-
body: JSON.stringify(payload),
|
| 48 |
-
});
|
| 49 |
-
if (r.status !== 200) {
|
| 50 |
-
const errBody = await r.text();
|
| 51 |
-
throw new Error(`NVIDIA ${r.status}: ${errBody}`);
|
| 52 |
-
}
|
| 53 |
-
return r.json();
|
| 54 |
-
});
|
| 55 |
-
|
| 56 |
-
recordUserHit(clientId);
|
| 57 |
-
|
| 58 |
-
// FLUX يرجع base64 في artifacts[0].base64 (أو image)
|
| 59 |
-
const b64 =
|
| 60 |
-
data?.artifacts?.[0]?.base64 ||
|
| 61 |
-
data?.image ||
|
| 62 |
-
data?.data?.[0]?.b64_json ||
|
| 63 |
-
null;
|
| 64 |
-
|
| 65 |
-
if (!b64) {
|
| 66 |
-
return res.status(502).json({ error: "no_image", raw: data });
|
| 67 |
-
}
|
| 68 |
-
|
| 69 |
-
res.json({ image: `data:image/png;base64,${b64}`, remaining: quota.remaining - 1 });
|
| 70 |
-
} catch (err) {
|
| 71 |
-
console.error("image error:", err);
|
| 72 |
-
res.status(500).json({ error: "image_failed", message: String(err?.message || err) });
|
| 73 |
-
}
|
| 74 |
-
});
|
| 75 |
-
|
| 76 |
-
export default router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
routes/proxy.js
DELETED
|
@@ -1,31 +0,0 @@
|
|
| 1 |
-
import express from "express";
|
| 2 |
-
import fetch from "node-fetch";
|
| 3 |
-
|
| 4 |
-
const router = express.Router();
|
| 5 |
-
|
| 6 |
-
// GET /api/img?u=<encoded image url> -> يعيد الصورة من نفس الأصل (يحل CORS للـ canvas)
|
| 7 |
-
router.get("/img", async (req, res) => {
|
| 8 |
-
try {
|
| 9 |
-
const u = req.query.u;
|
| 10 |
-
if (!u) return res.status(400).send("missing url");
|
| 11 |
-
const url = decodeURIComponent(u);
|
| 12 |
-
if (!/^https?:\/\//i.test(url)) return res.status(400).send("bad url");
|
| 13 |
-
|
| 14 |
-
const r = await fetch(url, {
|
| 15 |
-
headers: { "User-Agent": "Mozilla/5.0", Accept: "image/*" },
|
| 16 |
-
});
|
| 17 |
-
if (!r.ok) return res.status(502).send("fetch failed");
|
| 18 |
-
|
| 19 |
-
const type = r.headers.get("content-type") || "image/jpeg";
|
| 20 |
-
res.setHeader("Content-Type", type);
|
| 21 |
-
res.setHeader("Cache-Control", "public, max-age=86400");
|
| 22 |
-
res.setHeader("Access-Control-Allow-Origin", "*");
|
| 23 |
-
const buf = Buffer.from(await r.arrayBuffer());
|
| 24 |
-
res.send(buf);
|
| 25 |
-
} catch (err) {
|
| 26 |
-
console.error("img proxy error:", err);
|
| 27 |
-
res.status(500).send("proxy error");
|
| 28 |
-
}
|
| 29 |
-
});
|
| 30 |
-
|
| 31 |
-
export default router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
routes/search.js
DELETED
|
@@ -1,84 +0,0 @@
|
|
| 1 |
-
import express from "express";
|
| 2 |
-
import fetch from "node-fetch";
|
| 3 |
-
|
| 4 |
-
const router = express.Router();
|
| 5 |
-
const UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36";
|
| 6 |
-
|
| 7 |
-
function clean(s) {
|
| 8 |
-
return (s || "")
|
| 9 |
-
.replace(/<[^>]+>/g, "")
|
| 10 |
-
.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
|
| 11 |
-
.replace(/"/g, '"').replace(/'|'/g, "'").replace(/ /g, " ")
|
| 12 |
-
.replace(/\s+/g, " ").trim();
|
| 13 |
-
}
|
| 14 |
-
|
| 15 |
-
// بحث نصي عبر DuckDuckGo HTML
|
| 16 |
-
async function ddgText(query) {
|
| 17 |
-
const url = "https://html.duckduckgo.com/html/?q=" + encodeURIComponent(query);
|
| 18 |
-
const r = await fetch(url, { headers: { "User-Agent": UA, Accept: "text/html" } });
|
| 19 |
-
if (!r.ok) throw new Error("ddg " + r.status);
|
| 20 |
-
const html = await r.text();
|
| 21 |
-
const results = [];
|
| 22 |
-
const re = /<a[^>]*class="result__a"[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/g;
|
| 23 |
-
const snipRe = /<a[^>]*class="result__snippet"[^>]*>([\s\S]*?)<\/a>/g;
|
| 24 |
-
const snippets = []; let sm;
|
| 25 |
-
while ((sm = snipRe.exec(html)) !== null) snippets.push(clean(sm[1]));
|
| 26 |
-
let m, i = 0;
|
| 27 |
-
while ((m = re.exec(html)) !== null && results.length < 6) {
|
| 28 |
-
let link = m[1];
|
| 29 |
-
const w = link.match(/[?&]uddg=([^&]+)/);
|
| 30 |
-
if (w) link = decodeURIComponent(w[1]);
|
| 31 |
-
results.push({ title: clean(m[2]), url: link, snippet: snippets[i] || "" });
|
| 32 |
-
i++;
|
| 33 |
-
}
|
| 34 |
-
return results;
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
// بحث صور: نحصل على vqd ثم نستعلم i.js
|
| 38 |
-
async function ddgImages(query) {
|
| 39 |
-
// 1) احصل على vqd token
|
| 40 |
-
const tokRes = await fetch("https://duckduckgo.com/?q=" + encodeURIComponent(query), { headers: { "User-Agent": UA } });
|
| 41 |
-
const tokHtml = await tokRes.text();
|
| 42 |
-
const vqdMatch = tokHtml.match(/vqd=["']?([\d-]+)["']?/) || tokHtml.match(/vqd=([\d-]+)&/);
|
| 43 |
-
const vqd = vqdMatch ? vqdMatch[1] : null;
|
| 44 |
-
if (!vqd) throw new Error("no vqd");
|
| 45 |
-
|
| 46 |
-
// 2) استعلم نقطة الصور
|
| 47 |
-
const url = `https://duckduckgo.com/i.js?l=us-en&o=json&q=${encodeURIComponent(query)}&vqd=${vqd}&f=,,,&p=1`;
|
| 48 |
-
const r = await fetch(url, {
|
| 49 |
-
headers: { "User-Agent": UA, Accept: "application/json", Referer: "https://duckduckgo.com/" },
|
| 50 |
-
});
|
| 51 |
-
if (!r.ok) throw new Error("img " + r.status);
|
| 52 |
-
const data = await r.json();
|
| 53 |
-
return (data.results || []).slice(0, 12).map(x => ({
|
| 54 |
-
image: x.image, thumbnail: x.thumbnail, title: clean(x.title || ""), width: x.width, height: x.height,
|
| 55 |
-
}));
|
| 56 |
-
}
|
| 57 |
-
|
| 58 |
-
// POST /api/search { query }
|
| 59 |
-
router.post("/search", async (req, res) => {
|
| 60 |
-
try {
|
| 61 |
-
const { query } = req.body;
|
| 62 |
-
if (!query || !query.trim()) return res.status(400).json({ error: "missing_query" });
|
| 63 |
-
const results = await ddgText(query.trim());
|
| 64 |
-
res.json({ query, results });
|
| 65 |
-
} catch (err) {
|
| 66 |
-
console.error("search error:", err);
|
| 67 |
-
res.status(500).json({ error: "search_failed", message: String(err?.message || err) });
|
| 68 |
-
}
|
| 69 |
-
});
|
| 70 |
-
|
| 71 |
-
// POST /api/image-search { query }
|
| 72 |
-
router.post("/image-search", async (req, res) => {
|
| 73 |
-
try {
|
| 74 |
-
const { query } = req.body;
|
| 75 |
-
if (!query || !query.trim()) return res.status(400).json({ error: "missing_query" });
|
| 76 |
-
const images = await ddgImages(query.trim());
|
| 77 |
-
res.json({ query, images });
|
| 78 |
-
} catch (err) {
|
| 79 |
-
console.error("image-search error:", err);
|
| 80 |
-
res.status(500).json({ error: "image_search_failed", message: String(err?.message || err), images: [] });
|
| 81 |
-
}
|
| 82 |
-
});
|
| 83 |
-
|
| 84 |
-
export default router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
routes/title.js
DELETED
|
@@ -1,41 +0,0 @@
|
|
| 1 |
-
import express from "express";
|
| 2 |
-
import OpenAI from "openai";
|
| 3 |
-
|
| 4 |
-
const router = express.Router();
|
| 5 |
-
|
| 6 |
-
const pollinations = new OpenAI({
|
| 7 |
-
apiKey: "sk_fKErV9NKtE7OJFaFfozOGBriXqYJvJHa",
|
| 8 |
-
baseURL: "https://gen.pollinations.ai/v1",
|
| 9 |
-
});
|
| 10 |
-
|
| 11 |
-
router.post("/title", async (req, res) => {
|
| 12 |
-
try {
|
| 13 |
-
const { messages = [] } = req.body;
|
| 14 |
-
const convo = messages
|
| 15 |
-
.map(m => `${m.role === "user" ? "User" : "Genisi"}: ${m.content}`)
|
| 16 |
-
.join("\n")
|
| 17 |
-
.slice(0, 2000);
|
| 18 |
-
|
| 19 |
-
const r = await pollinations.chat.completions.create({
|
| 20 |
-
model: "polly", // نموذج مناسب للعنوان
|
| 21 |
-
messages: [
|
| 22 |
-
{
|
| 23 |
-
role: "system",
|
| 24 |
-
content:
|
| 25 |
-
"اكتب عنواناً قصيراً جداً (3 إلى 6 كلمات) يلخص موضوع المحادثة بنفس لغة المستخدم. " +
|
| 26 |
-
"بدون علامات اقتباس، بدون نقطة، بدون إيموجي. أعد العنوان فقط.",
|
| 27 |
-
},
|
| 28 |
-
{ role: "user", content: convo },
|
| 29 |
-
],
|
| 30 |
-
});
|
| 31 |
-
|
| 32 |
-
let title = (r.choices?.[0]?.message?.content || "").trim().replace(/^["'«»]+|["'«».]+$/g, "");
|
| 33 |
-
if (title.length > 60) title = title.slice(0, 60);
|
| 34 |
-
res.json({ title: title || "محادثة جديدة" });
|
| 35 |
-
} catch (err) {
|
| 36 |
-
console.error("title error:", err);
|
| 37 |
-
res.status(500).json({ error: "title_failed", title: "محادثة جديدة" });
|
| 38 |
-
}
|
| 39 |
-
});
|
| 40 |
-
|
| 41 |
-
export default router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
routes/upload.js
DELETED
|
@@ -1,66 +0,0 @@
|
|
| 1 |
-
import express from "express";
|
| 2 |
-
import multer from "multer";
|
| 3 |
-
import mammoth from "mammoth";
|
| 4 |
-
import { MODEL_CAPS, MAX_FILE_BYTES } from "../lib/modelCaps.js";
|
| 5 |
-
|
| 6 |
-
const router = express.Router();
|
| 7 |
-
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_FILE_BYTES } });
|
| 8 |
-
|
| 9 |
-
function extOf(name = "") { return (name.split(".").pop() || "").toLowerCase(); }
|
| 10 |
-
|
| 11 |
-
async function extractText(file) {
|
| 12 |
-
const ext = extOf(file.originalname);
|
| 13 |
-
if (["txt", "md", "csv", "json", "js", "ts", "py", "html", "css", "java", "c", "cpp"].includes(ext)) {
|
| 14 |
-
return file.buffer.toString("utf8");
|
| 15 |
-
}
|
| 16 |
-
if (ext === "docx") {
|
| 17 |
-
const { value } = await mammoth.extractRawText({ buffer: file.buffer });
|
| 18 |
-
return value;
|
| 19 |
-
}
|
| 20 |
-
if (ext === "pdf") {
|
| 21 |
-
// pdf-parse عبر import ديناميكي (CJS)
|
| 22 |
-
const pdfParse = (await import("pdf-parse")).default;
|
| 23 |
-
const data = await pdfParse(file.buffer);
|
| 24 |
-
return data.text;
|
| 25 |
-
}
|
| 26 |
-
return "";
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
// POST /api/upload (multipart: file, model)
|
| 30 |
-
router.post("/upload", upload.single("file"), async (req, res) => {
|
| 31 |
-
try {
|
| 32 |
-
const model = (req.body.model || "flash").toLowerCase();
|
| 33 |
-
const caps = MODEL_CAPS[model] || MODEL_CAPS.flash;
|
| 34 |
-
const file = req.file;
|
| 35 |
-
if (!file) return res.status(400).json({ error: "no_file" });
|
| 36 |
-
|
| 37 |
-
const ext = extOf(file.originalname);
|
| 38 |
-
const isImage = file.mimetype.startsWith("image/");
|
| 39 |
-
|
| 40 |
-
// تحقق من دعم النموذج لهذا النوع
|
| 41 |
-
if (isImage) {
|
| 42 |
-
if (!caps.vision || !caps.imageMimes.includes(file.mimetype)) {
|
| 43 |
-
return res.status(415).json({ error: "unsupported", message: `النموذج (${model}) لا يدعم الصور.` });
|
| 44 |
-
}
|
| 45 |
-
const b64 = file.buffer.toString("base64");
|
| 46 |
-
return res.json({
|
| 47 |
-
kind: "image",
|
| 48 |
-
name: file.originalname,
|
| 49 |
-
dataUrl: `data:${file.mimetype};base64,${b64}`,
|
| 50 |
-
});
|
| 51 |
-
}
|
| 52 |
-
|
| 53 |
-
if (!caps.docExts.includes(ext)) {
|
| 54 |
-
return res.status(415).json({ error: "unsupported", message: `النموذج (${model}) لا يدعم ملفات .${ext}` });
|
| 55 |
-
}
|
| 56 |
-
|
| 57 |
-
let text = await extractText(file);
|
| 58 |
-
if (text.length > 20000) text = text.slice(0, 20000) + "\n...[truncated]";
|
| 59 |
-
return res.json({ kind: "text", name: file.originalname, text });
|
| 60 |
-
} catch (err) {
|
| 61 |
-
console.error("upload error:", err);
|
| 62 |
-
res.status(500).json({ error: "upload_failed", message: String(err?.message || err) });
|
| 63 |
-
}
|
| 64 |
-
});
|
| 65 |
-
|
| 66 |
-
export default router;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|