Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
353d4639b4 | ||
|
|
dfbb61f75f | ||
|
|
c1d7f61a45 | ||
|
|
c200159afd | ||
|
|
ebc97e03a4 | ||
|
|
b088f68fd7 | ||
|
|
1ceb7cb156 | ||
|
|
e571b19f4a | ||
|
|
bcd2b756ed | ||
|
|
e8010b1e79 | ||
|
|
7c2eeda232 | ||
|
|
7e4605d2b7 | ||
|
|
7d78a1fc58 | ||
|
|
324298c9d7 | ||
|
|
2d1c670715 | ||
|
|
450d5dd239 | ||
|
|
f0f483a9d1 | ||
|
|
00abef23df | ||
|
|
29dc8459f7 | ||
|
|
afcace4fa3 | ||
|
|
2ca30178ed | ||
|
|
40ec3d406b | ||
|
|
b801867611 | ||
|
|
3a72752598 | ||
|
|
b2af06397a | ||
|
|
838cc01190 | ||
|
|
adedb9ea41 | ||
|
|
e5fc0e1705 | ||
|
|
e2f6853c2c | ||
|
|
9bf2a30f8d | ||
|
|
ad151bbae7 | ||
|
|
8865149aab | ||
|
|
879481df9f | ||
|
|
2c58978c78 | ||
|
|
3c17bd5081 | ||
|
|
adcb288064 | ||
|
|
016b4074d8 | ||
|
|
5e2d5dfabb | ||
|
|
9759ab2698 | ||
|
|
82e33fb0e0 | ||
|
|
9dab4f929c | ||
|
|
bef132f82f | ||
|
|
07570bd14a | ||
|
|
d68db09810 | ||
|
|
573d4ab452 | ||
|
|
436acf3cca | ||
|
|
2c4fd5a9d4 | ||
|
|
cf6e71839b | ||
|
|
99ecb0fa9f | ||
|
|
bd310e8d18 | ||
|
|
27a9a82a37 | ||
|
|
00e7490912 | ||
|
|
23e0c97822 | ||
|
|
2556bbfa1b | ||
|
|
f05cd8b820 | ||
|
|
d16db803ba | ||
|
|
1b491357ab | ||
|
|
61a2e95278 | ||
|
|
426dc783df | ||
|
|
575e4868be | ||
|
|
41ead01e02 | ||
|
|
4e2ecaa69e | ||
|
|
632edaf081 | ||
|
|
d56dff2a2f | ||
|
|
696cec2fb5 | ||
|
|
729b19bc12 | ||
|
|
6f1f42ba7a | ||
|
|
68863eb44e | ||
|
|
679195b590 | ||
|
|
b070125f51 | ||
|
|
d513512b87 | ||
|
|
30038d5103 | ||
|
|
d2ed1b1c76 | ||
|
|
5530c141a2 | ||
|
|
cb6fd6f5af | ||
|
|
1800909661 | ||
|
|
c0eaac1daa | ||
|
|
79ebe69221 | ||
|
|
e5fe31f6ba | ||
|
|
05945099a1 | ||
|
|
399a76da8e | ||
|
|
659b1a1943 | ||
|
|
fb1d53d97a | ||
|
|
79813ff52c | ||
|
|
1b571387df | ||
|
|
e1bf404455 | ||
|
|
18e226ad47 | ||
|
|
182a1bb674 | ||
|
|
0c87a287a3 | ||
|
|
edcbd0dc58 | ||
|
|
5cf7b51686 | ||
|
|
531e8d63c1 | ||
|
|
dc7a92f040 | ||
|
|
11552d6124 | ||
|
|
7b4783bb3e | ||
|
|
98c7977a19 | ||
|
|
c9e0720764 | ||
|
|
87b744c9c7 | ||
|
|
275c3d6bb3 | ||
|
|
ef619c635e | ||
|
|
d55c8cc1e5 | ||
|
|
9d0015808c | ||
|
|
8600d2d4a3 | ||
|
|
846682ac4a | ||
|
|
f7105a62cc | ||
|
|
0628344dcf | ||
|
|
d25db9367c | ||
|
|
1d29e50852 | ||
|
|
853ad67db5 | ||
|
|
851e3fc2dc | ||
|
|
74770cd99d | ||
|
|
ce0735d775 | ||
|
|
805f4594d4 | ||
|
|
7a0defc3d4 | ||
|
|
fe6957bf83 | ||
|
|
049291c109 | ||
|
|
53673d0f9b | ||
|
|
9d55f521a0 | ||
|
|
35c03ef35e | ||
|
|
bb6c586d99 | ||
|
|
4fb57dfd67 | ||
|
|
6b49d035c2 | ||
|
|
6bb6226e06 | ||
|
|
9242b87677 | ||
|
|
20c95e73b3 | ||
|
|
5837e4b0d9 | ||
|
|
1fb5d57da1 | ||
|
|
8abc70dcf1 | ||
|
|
f2e5a9e58b | ||
|
|
5ae5421c5c | ||
|
|
c169703a17 | ||
|
|
07da45467b | ||
|
|
4b9cc13163 | ||
|
|
f1046a6598 | ||
|
|
5731eda438 | ||
|
|
17bddd3adf | ||
|
|
2ad3ad7367 | ||
|
|
b31124e1e4 | ||
|
|
a29deb8bb1 | ||
|
|
17345daa81 | ||
|
|
2c96562b66 | ||
|
|
70cf9616c1 | ||
|
|
cfe5512ec7 | ||
|
|
8f11df99ea | ||
|
|
b7d29d1028 | ||
|
|
5ed082631e | ||
|
|
6e422ec3dc | ||
|
|
bf3c67f405 | ||
|
|
3a7c7b0908 | ||
|
|
897fac4f15 | ||
|
|
1fde4e30fc |
@@ -0,0 +1,251 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { BotIcon, SendIcon, SparklesIcon, XIcon } from 'lucide-react';
|
||||
import { track } from '../analytics';
|
||||
|
||||
type ChatMessage = {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
streaming?: boolean;
|
||||
error?: boolean;
|
||||
};
|
||||
|
||||
type SseFrame = {
|
||||
content?: string;
|
||||
error?: string;
|
||||
done?: boolean;
|
||||
};
|
||||
|
||||
/** شناسه گفتگو برای هر نشست — در sessionStorage میماند تا رفرش صفحه تاریخچه را نگه دارد */
|
||||
function getThreadId(): string {
|
||||
const KEY = 'chat_thread_id';
|
||||
let id = sessionStorage.getItem(KEY);
|
||||
if (!id) {
|
||||
id = `t_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
|
||||
sessionStorage.setItem(KEY, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/** خواندن فریمهای SSE از پاسخ fetch (استریم توکنبهتوکن) */
|
||||
async function readSse(response: Response, onFrame: (frame: SseFrame) => void) {
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) throw new Error('پاسخ استریمی ندارد');
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() ?? '';
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.startsWith('data: ')) {
|
||||
try {
|
||||
onFrame(JSON.parse(trimmed.slice(6)) as SseFrame);
|
||||
} catch {
|
||||
// فریم ناقص — نادیده بگیر
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function ChatWidget() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [suggestions, setSuggestions] = useState<string[]>([]);
|
||||
const scrollEndRef = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const assistantIndexRef = useRef<number | null>(null);
|
||||
|
||||
// پیشنهاد پرسشها فقط یک بار برای هر بازشدن اول
|
||||
useEffect(() => {
|
||||
if (!open || suggestions.length > 0) return;
|
||||
fetch('/chat/suggestions')
|
||||
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
|
||||
.then((d) => setSuggestions((d.questions ?? []).slice(0, 4)))
|
||||
.catch(() => setSuggestions([]));
|
||||
}, [open, suggestions.length]);
|
||||
|
||||
useEffect(() => {
|
||||
scrollEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' });
|
||||
}, [messages, open]);
|
||||
|
||||
const sendMessage = async (text: string) => {
|
||||
const question = text.trim();
|
||||
if (!question || isLoading) return;
|
||||
track('chat-question')
|
||||
setInput('');
|
||||
setIsLoading(true);
|
||||
setMessages((prev) => {
|
||||
const next: ChatMessage[] = [
|
||||
...prev,
|
||||
{ role: 'user', content: question },
|
||||
{ role: 'assistant', content: '', streaming: true },
|
||||
];
|
||||
assistantIndexRef.current = next.length - 1;
|
||||
return next;
|
||||
});
|
||||
|
||||
const patchAssistant = (patch: Partial<ChatMessage>) => {
|
||||
setMessages((prev) => {
|
||||
const idx = assistantIndexRef.current;
|
||||
if (idx === null || !prev[idx]) return prev;
|
||||
const updated = [...prev];
|
||||
updated[idx] = { ...updated[idx], ...patch };
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({ message: question, thread_id: getThreadId() });
|
||||
const response = await fetch(`/chat/stream?${params.toString()}`, {
|
||||
headers: { Accept: 'text/event-stream' },
|
||||
});
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
|
||||
let accumulated = '';
|
||||
await readSse(response, (frame) => {
|
||||
if (frame.error) {
|
||||
patchAssistant({ content: frame.error, streaming: false, error: true });
|
||||
return;
|
||||
}
|
||||
if (frame.content) {
|
||||
accumulated += frame.content;
|
||||
patchAssistant({ content: accumulated });
|
||||
}
|
||||
if (frame.done) patchAssistant({ content: accumulated || 'پاسخی دریافت نشد.', streaming: false });
|
||||
});
|
||||
patchAssistant({ streaming: false });
|
||||
} catch (err) {
|
||||
patchAssistant({
|
||||
content: 'سرویس گفتگو در دسترس نیست؛ لطفاً کمی بعد دوباره تلاش کنید.',
|
||||
streaming: false,
|
||||
error: true,
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* دکمه شناور — گوشه راستپایین (دکمه تماس سمت چپ است) */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setOpen((v) => {
|
||||
if (!v) track('chat-open');
|
||||
return !v;
|
||||
});
|
||||
}}
|
||||
aria-label={open ? 'بستن گفتگو' : 'گفتگو با دستیار هوشمند'}
|
||||
className="group fixed bottom-8 right-8 z-40 flex h-14 w-14 items-center justify-center rounded-full bg-ivory text-ink shadow-[0_10px_30px_rgba(0,0,0,0.45)] transition-transform duration-200 ease-lux hover:scale-105">
|
||||
<span className="absolute inset-0 rounded-full border border-ivory/60 opacity-0 transition-transform duration-300 ease-lux group-hover:scale-125 group-hover:opacity-100" />
|
||||
{open ? <XIcon className="h-5 w-5" /> : <BotIcon className="h-5 w-5" />}
|
||||
</button>
|
||||
|
||||
{/* پنل گفتگو */}
|
||||
{open && (
|
||||
<div
|
||||
className="fixed bottom-24 right-4 z-40 flex h-[min(560px,72vh)] w-[min(380px,calc(100vw-2rem))] flex-col overflow-hidden rounded-2xl border border-copper/30 bg-char shadow-lux sm:right-8">
|
||||
{/* سربرگ */}
|
||||
<div className="flex items-center gap-3 border-b border-ivory/10 bg-ink px-4 py-3">
|
||||
<span className="flex h-9 w-9 items-center justify-center rounded-full bg-copper/15 text-copper">
|
||||
<SparklesIcon className="h-4 w-4" />
|
||||
</span>
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-bold text-ivory">دستیار هوشمند آرامش</p>
|
||||
<p className="text-[11px] font-light text-ivory/50">پاسخ از محتوای همین سایت</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
aria-label="بستن"
|
||||
className="rounded-full p-1.5 text-ivory/50 transition-colors hover:bg-ivory/10 hover:text-ivory">
|
||||
<XIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* پیامها */}
|
||||
<div className="flex-1 space-y-3 overflow-y-auto px-4 py-4">
|
||||
{messages.length === 0 && (
|
||||
<div className="mt-6 text-center">
|
||||
<BotIcon className="mx-auto h-8 w-8 text-copper/60" />
|
||||
<p className="mt-3 text-sm font-light leading-7 text-ivory/60">
|
||||
سلام! هر سؤالی درباره خدمات، پروژهها و مقالات
|
||||
<span className="font-bold text-ivory"> گروه ساختمانی آرامش </span>
|
||||
دارید بپرسید.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{messages.map((msg, i) => (
|
||||
<div key={i} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
|
||||
<div
|
||||
className={`max-w-[85%] whitespace-pre-wrap rounded-2xl px-3.5 py-2.5 text-[13px] leading-6 ${
|
||||
msg.role === 'user'
|
||||
? 'rounded-bl-md bg-copper text-char'
|
||||
: msg.error
|
||||
? 'rounded-br-md border border-red-400/30 bg-red-400/10 text-red-200'
|
||||
: 'rounded-br-md border border-ivory/10 bg-ink text-ivory'
|
||||
}`}>
|
||||
{msg.content || (msg.streaming ? '…' : '')}
|
||||
{msg.streaming && msg.content && (
|
||||
<span className="ms-1 inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-copper align-middle" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div ref={scrollEndRef} />
|
||||
</div>
|
||||
|
||||
{/* پیشنهاد پرسشها */}
|
||||
{suggestions.length > 0 && messages.length === 0 && (
|
||||
<div className="flex flex-wrap gap-1.5 border-t border-ivory/10 px-3 py-2.5">
|
||||
{suggestions.map((q) => (
|
||||
<button
|
||||
key={q}
|
||||
type="button"
|
||||
onClick={() => sendMessage(q)}
|
||||
className="rounded-full border border-copper/30 px-2.5 py-1 text-[11px] text-copper transition-colors hover:bg-copper hover:text-char">
|
||||
{q}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ورودی */}
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
sendMessage(input);
|
||||
}}
|
||||
className="flex items-center gap-2 border-t border-ivory/10 bg-ink px-3 py-3">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
placeholder="پرسش خود را بنویسید…"
|
||||
disabled={isLoading}
|
||||
className="flex-1 rounded-full border border-ivory/15 bg-char px-4 py-2 text-[13px] text-ivory placeholder:text-ivory/30 focus:border-copper/60 focus:outline-none disabled:opacity-50"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading || !input.trim()}
|
||||
aria-label="ارسال"
|
||||
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-copper text-char transition-transform hover:scale-105 disabled:bg-ivory/15 disabled:text-ivory/40 disabled:hover:scale-100">
|
||||
<SendIcon className="h-4 w-4 -scale-x-100" />
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
"""سرویس چتبات سایت آرامش — FastAPI با استریم SSE و بازیابی ترکیبی روی محتوای دیتابیس."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from collections import defaultdict, deque
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Query, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from langchain_core.messages import AIMessage, HumanMessage
|
||||
|
||||
from . import content as content_mod
|
||||
from . import pipeline
|
||||
from . import vectorstore
|
||||
from .config import settings
|
||||
from .indexing import INDEX, sync_index
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
||||
)
|
||||
log = logging.getLogger("chatbot")
|
||||
|
||||
|
||||
# --- چرخه حیات: ساخت ایندکس در شروع + بازسازی خودکار وقتی محتوا عوض شود ---
|
||||
|
||||
_refresh_task: asyncio.Task | None = None
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
try:
|
||||
await asyncio.to_thread(sync_index)
|
||||
except Exception as e:
|
||||
log.critical("Initial index sync failed: %s — chat will be unavailable until reindex", e)
|
||||
global _refresh_task
|
||||
_refresh_task = asyncio.create_task(_refresh_loop())
|
||||
yield
|
||||
_refresh_task.cancel()
|
||||
|
||||
|
||||
async def _refresh_loop() -> None:
|
||||
interval = settings.index_refresh_seconds
|
||||
if interval <= 0:
|
||||
return
|
||||
while True:
|
||||
await asyncio.sleep(interval)
|
||||
try:
|
||||
# همگامسازی افزایشی است — فقط سطرهای جدید/تغییریافته امبد میشوند
|
||||
await asyncio.to_thread(sync_index)
|
||||
except Exception as e:
|
||||
log.warning("Background index refresh failed: %s", e)
|
||||
|
||||
|
||||
api = FastAPI(
|
||||
title="Aramesh Site Chatbot",
|
||||
version="1.0.0",
|
||||
description="دستیار گفتگوی محتوای سایت — بازیابی ترکیبی (pgvector + BM25) با ریرنکر BGE",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
api.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=False,
|
||||
allow_methods=["GET", "POST"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
# --- محدودسازی نرخ درخواست سبک در حافظه (پنجره لغزان per-IP) ---
|
||||
|
||||
_hits: dict[str, deque] = defaultdict(deque)
|
||||
_last_sweep = 0.0
|
||||
|
||||
|
||||
def _rate_limited(ip: str) -> bool:
|
||||
global _last_sweep
|
||||
now = time.time()
|
||||
# پاکسازی دورهای کلیدهای بیمصرف تا دیکشنری بینهایت بزرگ نشود
|
||||
if now - _last_sweep > settings.rate_limit_window:
|
||||
stale = [k for k, q in _hits.items() if not q or now - q[-1] > settings.rate_limit_window]
|
||||
for k in stale:
|
||||
_hits.pop(k, None)
|
||||
_last_sweep = now
|
||||
window = _hits[ip]
|
||||
while window and now - window[0] > settings.rate_limit_window:
|
||||
window.popleft()
|
||||
if len(window) >= settings.rate_limit_messages:
|
||||
return True
|
||||
window.append(now)
|
||||
return False
|
||||
|
||||
|
||||
def _client_ip(request: Request | None) -> str:
|
||||
if request is None:
|
||||
return "?"
|
||||
forwarded = request.headers.get("x-forwarded-for")
|
||||
return forwarded.split(",")[0].strip() if forwarded else (request.client.host if request.client else "?")
|
||||
|
||||
|
||||
# --- کمکیهای SSE ---
|
||||
|
||||
def _sse(payload: dict) -> str:
|
||||
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
def _chunk_text(chunk) -> str:
|
||||
"""استخراج متن از قطعه استریم LLM (رشته یا لیست بخشها)."""
|
||||
content = getattr(chunk, "content", "")
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
return "".join(p.get("text", "") for p in content if isinstance(p, dict))
|
||||
return ""
|
||||
|
||||
|
||||
async def _stream_answer(message: str, thread_id: str):
|
||||
if not INDEX.ready:
|
||||
yield _sse({"error": "ایندکس محتوا هنوز آماده نیست؛ چند لحظه بعد دوباره تلاش کنید.", "done": True})
|
||||
return
|
||||
if pipeline.get_llm() is None:
|
||||
yield _sse({"error": pipeline.LLM_UNAVAILABLE, "done": True})
|
||||
return
|
||||
|
||||
config = {"configurable": {"thread_id": thread_id}}
|
||||
inputs = {"messages": [HumanMessage(content=message)]}
|
||||
try:
|
||||
async for event in pipeline.graph.astream_events(inputs, config=config, version="v2"):
|
||||
# فقط توکنهای پاسخ نهایی — نه فراخوانیهای کمکی (بازنویسی/گسترش پرسش)
|
||||
if event["event"] == "on_chat_model_stream" and "generate" in (event.get("tags") or []):
|
||||
text = _chunk_text(event["data"]["chunk"])
|
||||
if text:
|
||||
yield _sse({"content": text, "done": False})
|
||||
yield _sse({"content": "", "done": True})
|
||||
except Exception as e:
|
||||
log.exception("Streaming failed")
|
||||
yield _sse({"error": f"خطا در تولید پاسخ: {e}", "done": True})
|
||||
|
||||
|
||||
# --- مسیرها ---
|
||||
|
||||
@api.get("/chat/healthz")
|
||||
async def healthz():
|
||||
return {
|
||||
"status": "ok",
|
||||
"index_ready": INDEX.ready,
|
||||
"documents": len(INDEX.docs),
|
||||
"vectors": await asyncio.to_thread(vectorstore.vector_count),
|
||||
"llm_configured": bool(settings.llm_base_url),
|
||||
"reranker_enabled": settings.reranker_enabled,
|
||||
}
|
||||
|
||||
|
||||
@api.get("/chat/suggestions")
|
||||
async def suggestions():
|
||||
return {"questions": _get_suggestions()}
|
||||
|
||||
|
||||
@api.get("/chat/eval")
|
||||
async def eval_question(message: str = Query(...)):
|
||||
"""مخصوص ارزیابی RAGAS — پاسخ + اسناد بازیابیشده، با thread تازه."""
|
||||
if not INDEX.ready:
|
||||
return {"error": "index not ready", "question": message, "answer": "", "contexts": []}
|
||||
if pipeline.get_llm() is None:
|
||||
return {"error": "llm not configured", "question": message, "answer": "", "contexts": []}
|
||||
|
||||
thread_id = f"eval_{uuid.uuid4().hex[:10]}"
|
||||
config = {"configurable": {"thread_id": thread_id}}
|
||||
inputs = {"messages": [HumanMessage(content=message)]}
|
||||
final_state = await pipeline.graph.ainvoke(inputs, config=config)
|
||||
|
||||
answer = ""
|
||||
for msg in reversed(final_state.get("messages", [])):
|
||||
if isinstance(msg, AIMessage):
|
||||
answer = msg.content if isinstance(msg.content, str) else str(msg.content)
|
||||
break
|
||||
return {
|
||||
"question": message,
|
||||
"contextualized_query": final_state.get("contextualized_query") or message,
|
||||
"answer": answer,
|
||||
"contexts": final_state.get("documents", []),
|
||||
"thread_id": thread_id,
|
||||
}
|
||||
|
||||
|
||||
@api.post("/chat/reindex")
|
||||
async def reindex(request: Request):
|
||||
"""همگامسازی اجباری (امبد دوباره همه سطرها) — با توکن محافظت میشود."""
|
||||
if settings.reindex_token and request.headers.get("x-reindex-token") != settings.reindex_token:
|
||||
raise HTTPException(status_code=403, detail="invalid reindex token")
|
||||
stats = await asyncio.to_thread(sync_index, True)
|
||||
return {"status": "ok", "documents": len(INDEX.docs), "stats": stats}
|
||||
|
||||
|
||||
# سازگاری با eval_ragas.py قدیمی که آدرس را /chat/{username}/eval میسازد
|
||||
|
||||
@api.get("/chat/{scope}/stream")
|
||||
async def stream_chat_scoped(scope: str, message: str = Query(...), thread_id: str = Query(default=""), request: Request = None):
|
||||
return await stream_chat(message=message, thread_id=thread_id, request=request)
|
||||
|
||||
|
||||
@api.get("/chat/{scope}/eval")
|
||||
async def eval_scoped(scope: str, message: str = Query(...)):
|
||||
return await eval_question(message=message)
|
||||
|
||||
|
||||
@api.get("/chat/{scope}/suggestions")
|
||||
async def suggestions_scoped(scope: str):
|
||||
return {"questions": _get_suggestions()}
|
||||
|
||||
|
||||
@api.get("/chat/stream")
|
||||
async def stream_chat(message: str = Query(...), thread_id: str = Query(default=""), request: Request = None):
|
||||
"""استریم توکنبهتوکن پاسخ با SSE."""
|
||||
if _rate_limited(_client_ip(request)):
|
||||
raise HTTPException(status_code=429, detail="تعداد پیامهای شما زیاد است؛ کمی بعد دوباره تلاش کنید.")
|
||||
|
||||
thread_id = thread_id or f"t_{uuid.uuid4().hex[:10]}"
|
||||
|
||||
async def generate():
|
||||
async for chunk in _stream_answer(message, thread_id):
|
||||
yield chunk
|
||||
|
||||
return StreamingResponse(
|
||||
generate(),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
|
||||
# --- پیشنهاد پرسشها (کششده) ---
|
||||
|
||||
_suggestions_cache: tuple[float, list[str]] = (0.0, [])
|
||||
|
||||
|
||||
def _get_suggestions() -> list[str]:
|
||||
global _suggestions_cache
|
||||
now = time.time()
|
||||
if _suggestions_cache[1] and now - _suggestions_cache[0] < settings.suggestions_ttl:
|
||||
return _suggestions_cache[1]
|
||||
|
||||
questions: list[str] = []
|
||||
if INDEX.ready:
|
||||
faqs = [d for d in INDEX.docs if d["type"] == "faq"][:8]
|
||||
titles = [d["title"] for d in INDEX.docs if d["type"] == "article"][:10]
|
||||
model = pipeline.get_llm()
|
||||
if model and (faqs or titles):
|
||||
material = "\n".join([d["text"][:200] for d in faqs] + titles)
|
||||
try:
|
||||
prompt = (
|
||||
"بر اساس محتوای سایت «گروه ساختمانی آرامش» ۴ پرسش کوتاه و جذاب بنویس که بازدیدکننده "
|
||||
"احتمالاً میپرسد. هر پرسش حداکثر ۱۰ کلمه و به فارسی.\n"
|
||||
'فقط آرایه JSON رشتهای برگردان: ["پرسش ۱", "پرسش ۲", ...]\n\n'
|
||||
f"محتوا:\n{material[:2000]}"
|
||||
)
|
||||
resp = model.invoke([HumanMessage(content=prompt)])
|
||||
text = resp.content if isinstance(resp.content, str) else ""
|
||||
if text.startswith("```"):
|
||||
text = text.split("```")[1]
|
||||
text = text[4:] if text.startswith("json") else text
|
||||
import re
|
||||
match = re.search(r"\[.*\]", text, re.DOTALL)
|
||||
if match:
|
||||
questions = [q.strip() for q in json.loads(match.group()) if isinstance(q, str) and q.strip()][:4]
|
||||
except Exception as e:
|
||||
log.warning("Suggestion generation failed: %s", e)
|
||||
if not questions and faqs:
|
||||
# جایگزین: خود پرسشهای متداول
|
||||
questions = [d["text"].split("\n")[0].removeprefix("پرسش: ") for d in faqs[:4]]
|
||||
|
||||
_suggestions_cache = (now, questions)
|
||||
return questions
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(api, host="0.0.0.0", port=8000)
|
||||
@@ -0,0 +1,315 @@
|
||||
"""خواندن محتوای سایت از PostgreSQL و تبدیل آن به سندهای قابل ایندکس.
|
||||
|
||||
هر سند یک dict با کلیدهای text / type / title / url است. بدنه مقالهها و
|
||||
پروژهها هم میتواند آرایه پاراگراف باشد و هم سند TipTap (JSON) — هر دو
|
||||
پشتیبانی میشوند. مقالههای پیشنویس ایندکس نمیشوند.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from .persian import normalize
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# URL پایه صفحات — چتبات مسیر نسبی میدهد؛ فرانتاند روی همان دامنه است
|
||||
_ARTICLE_URL = "/blog/{slug}"
|
||||
_PROJECT_URL = "/projects/{slug}"
|
||||
|
||||
|
||||
def _psycopg_dsn(database_url: str) -> str:
|
||||
"""DATABASE_URL فرمت SQLAlchemy (postgresql+psycopg://) را به DSN psycopg3 تبدیل میکند."""
|
||||
return database_url.replace("+psycopg", "").replace("+asyncpg", "")
|
||||
|
||||
|
||||
def _fetch_rows(dsn: str, sql: str) -> list[dict[str, Any]]:
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
with psycopg.connect(dsn, row_factory=dict_row, connect_timeout=10) as conn:
|
||||
cur = conn.execute(sql)
|
||||
return cur.fetchall()
|
||||
|
||||
|
||||
def tiptap_blocks(node: Any) -> list[str]:
|
||||
"""متن بلوکبهبلوک از سند TipTap (یا هر JSON تو در تو) بیرون میکشد."""
|
||||
if not isinstance(node, dict):
|
||||
return []
|
||||
ntype = node.get("type")
|
||||
if ntype in ("paragraph", "heading", "codeBlock"):
|
||||
text = _inline_text(node).strip()
|
||||
return [text] if text else []
|
||||
blocks: list[str] = []
|
||||
for child in node.get("content") or []:
|
||||
blocks.extend(tiptap_blocks(child))
|
||||
return blocks
|
||||
|
||||
|
||||
def _inline_text(node: dict) -> str:
|
||||
parts: list[str] = []
|
||||
for child in node.get("content") or []:
|
||||
ctype = child.get("type")
|
||||
if ctype == "text":
|
||||
parts.append(child.get("text", ""))
|
||||
elif ctype == "hardBreak":
|
||||
parts.append(" ")
|
||||
elif ctype == "image":
|
||||
alt = (child.get("attrs") or {}).get("alt") or ""
|
||||
if alt:
|
||||
parts.append(f"[تصویر: {alt}]")
|
||||
else:
|
||||
parts.append(_inline_text(child))
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def body_to_text(body: Any) -> str:
|
||||
"""بدنه مقاله/پروژه (آرایه پاراگراف یا سند TipTap) → متن یکپارچه."""
|
||||
if not body:
|
||||
return ""
|
||||
if isinstance(body, list):
|
||||
# فرمت قدیمی: آرایه رشتهای پاراگرافها
|
||||
return "\n".join(str(p).strip() for p in body if str(p).strip())
|
||||
blocks = tiptap_blocks(body)
|
||||
return "\n".join(b for b in blocks if b)
|
||||
|
||||
|
||||
def _doc(text: str, dtype: str, title: str, url: str) -> dict | None:
|
||||
text = (text or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
return {"text": text, "type": dtype, "title": title, "url": url}
|
||||
|
||||
|
||||
def _clean(value: Any) -> str:
|
||||
return normalize(str(value or "")).strip()
|
||||
|
||||
|
||||
def fetch_site_documents(database_url: str) -> list[dict]:
|
||||
"""همه محتوای عمومی سایت را به سند تبدیل میکند (بدون وابستگی به ORM بکاند)."""
|
||||
dsn = _psycopg_dsn(database_url)
|
||||
docs: list[dict] = []
|
||||
|
||||
# --- برند و اطلاعات تماس (رکورد یگانه) ---
|
||||
brand_rows = _fetch_rows(dsn, "SELECT name, phone, email, address FROM brand LIMIT 1")
|
||||
if brand_rows:
|
||||
b = brand_rows[0]
|
||||
contact = "\n".join(
|
||||
filter(None, [
|
||||
f"نام مجموعه: {_clean(b['name'])}",
|
||||
f"تلفن تماس: {_clean(b['phone'])}",
|
||||
f"ایمیل: {_clean(b['email'])}",
|
||||
f"آدرس: {_clean(b['address'])}",
|
||||
])
|
||||
)
|
||||
d = _doc(contact, "contact", "اطلاعات تماس", "/contact")
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- دفاتر ---
|
||||
for row in _fetch_rows(dsn, "SELECT city, address, hours FROM offices ORDER BY position"):
|
||||
d = _doc(
|
||||
f"دفتر {_clean(row['city'])} — آدرس: {_clean(row['address'])} — ساعت کاری: {_clean(row['hours'])}",
|
||||
"office", f"دفتر {_clean(row['city'])}", "/contact",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- خدمات ---
|
||||
for row in _fetch_rows(dsn, 'SELECT title, "desc" FROM services ORDER BY position'):
|
||||
d = _doc(
|
||||
f"خدمت «{_clean(row['title'])}»: {_clean(row['desc'])}",
|
||||
"service", _clean(row["title"]), "/services",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- پرسشهای متداول ---
|
||||
for row in _fetch_rows(dsn, "SELECT question, answer FROM faqs ORDER BY position"):
|
||||
d = _doc(
|
||||
f"پرسش: {_clean(row['question'])}\nپاسخ: {_clean(row['answer'])}",
|
||||
"faq", _clean(row["question"]), "/faq",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- پروژهها ---
|
||||
for row in _fetch_rows(
|
||||
dsn,
|
||||
"SELECT slug, title, location, year, status, area, floors, units, client, summary, body FROM projects ORDER BY position",
|
||||
):
|
||||
meta = "\n".join(filter(None, [
|
||||
f"مکان: {_clean(row['location'])}" if row["location"] else "",
|
||||
f"سال: {_clean(row['year'])}" if row["year"] else "",
|
||||
f"وضعیت: {'در حال ساخت' if row['status'] == 'progress' else 'تکمیلشده'}",
|
||||
f"متراژ: {_clean(row['area'])}" if row["area"] else "",
|
||||
f"طبقات: {_clean(row['floors'])}" if row["floors"] else "",
|
||||
f"واحدها: {_clean(row['units'])}" if row["units"] else "",
|
||||
f"کارفرما: {_clean(row['client'])}" if row["client"] else "",
|
||||
]))
|
||||
text = "\n".join(filter(None, [meta, _clean(row["summary"]), body_to_text(row["body"])]))
|
||||
d = _doc(text, "project", _clean(row["title"]), _PROJECT_URL.format(slug=row["slug"]))
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- مقالهها (فقط منتشرشده) ---
|
||||
for row in _fetch_rows(
|
||||
dsn,
|
||||
"SELECT slug, title, date, category, excerpt, body FROM articles WHERE status = 'published' ORDER BY position",
|
||||
):
|
||||
text = "\n".join(filter(None, [
|
||||
f"دستهبندی: {_clean(row['category'])}" if row["category"] else "",
|
||||
_clean(row["excerpt"]),
|
||||
body_to_text(row["body"]),
|
||||
]))
|
||||
d = _doc(text, "article", _clean(row["title"]), _ARTICLE_URL.format(slug=row["slug"]))
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- مدلهای سرمایهگذاری ---
|
||||
for row in _fetch_rows(dsn, 'SELECT title, "desc", points FROM investment_models ORDER BY position'):
|
||||
points = "؛ ".join(_clean(p) for p in (row["points"] or []))
|
||||
d = _doc(
|
||||
"\n".join(filter(None, [
|
||||
f"«{_clean(row['title'])}»: {_clean(row['desc'])}",
|
||||
f"نکات: {points}" if points else "",
|
||||
])),
|
||||
"investment", _clean(row["title"]), "/investment",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- مراحل همکاری ---
|
||||
for row in _fetch_rows(dsn, 'SELECT step, title, "desc" FROM process_steps ORDER BY position'):
|
||||
d = _doc(
|
||||
f"مرحله {_clean(row['step'])} — {_clean(row['title'])}: {_clean(row['desc'])}",
|
||||
"process", _clean(row["title"]), "/investment",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- چرا ما / تیم / نظرسنجی / تایملاین / داستان ما ---
|
||||
for row in _fetch_rows(dsn, 'SELECT title, "desc" FROM why_us ORDER BY position'):
|
||||
d = _doc(f"{_clean(row['title'])}: {_clean(row['desc'])}", "about", _clean(row["title"]), "/about")
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
for row in _fetch_rows(dsn, "SELECT name, role, bio FROM team ORDER BY position"):
|
||||
d = _doc(
|
||||
f"{_clean(row['name'])} — {_clean(row['role'])}. {_clean(row['bio'])}",
|
||||
"team", _clean(row["name"]), "/about",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
for row in _fetch_rows(dsn, "SELECT name, role, quote FROM testimonials ORDER BY position"):
|
||||
d = _doc(
|
||||
f"نظر {_clean(row['name'])} ({_clean(row['role'])}): {_clean(row['quote'])}",
|
||||
"testimonial", _clean(row["name"]), "/",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
for row in _fetch_rows(dsn, 'SELECT year, title, "desc" FROM timeline ORDER BY position'):
|
||||
d = _doc(
|
||||
f"سال {_clean(row['year'])} — {_clean(row['title'])}: {_clean(row['desc'])}",
|
||||
"timeline", _clean(row["title"]), "/about",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
story_rows = _fetch_rows(dsn, "SELECT title, paragraphs, quote FROM story LIMIT 1")
|
||||
if story_rows and story_rows[0]:
|
||||
s = story_rows[0]
|
||||
paragraphs = "\n".join(_clean(p) for p in (s["paragraphs"] or []) if _clean(p))
|
||||
text = "\n".join(filter(None, [_clean(s["title"]), paragraphs, _clean(s["quote"])]))
|
||||
d = _doc(text, "about", _clean(s["title"]) or "درباره ما", "/about")
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
log.info("Fetched %d documents from site database", len(docs))
|
||||
return docs
|
||||
|
||||
|
||||
def chunk_documents(docs: list[dict], chunk_size: int = 700, overlap: int = 120) -> list[dict]:
|
||||
"""متنهای بلند (مقاله/پروژه) را به قطعات همپوشان تقسیم میکند.
|
||||
|
||||
هر قطعه یک doc_id پایدار میگیرد («type:ترتیب در همان url:شماره قطعه») تا
|
||||
همگامسازی افزایشی pgvector بتواند فقط سطرهای تغییر یافته را امبد کند.
|
||||
"""
|
||||
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
||||
|
||||
from .vectorstore import chunk_content_hash
|
||||
|
||||
splitter = RecursiveCharacterTextSplitter(
|
||||
chunk_size=chunk_size,
|
||||
chunk_overlap=overlap,
|
||||
separators=["\n", "۔", ".", "،", " ", ""],
|
||||
)
|
||||
|
||||
# شماره ردیف هر سند در میان سندهای همtype و هم-url (برای FAQs که url یکسان دارند)
|
||||
occurrence: dict[str, int] = {}
|
||||
|
||||
out: list[dict] = []
|
||||
for doc in docs:
|
||||
key = f"{doc['type']}|{doc['url']}"
|
||||
occ = occurrence.get(key, 0)
|
||||
occurrence[key] = occ + 1
|
||||
|
||||
pieces = splitter.split_text(doc["text"]) if len(doc["text"]) > chunk_size * 1.3 else [doc["text"]]
|
||||
for i, piece in enumerate(pieces, 1):
|
||||
chunk = {
|
||||
"doc_id": f"{doc['type']}:{occ}:{i}",
|
||||
"text": piece if len(pieces) == 1 else f"[{doc['title']} — بخش {i} از {len(pieces)}]\n{piece}",
|
||||
"type": doc["type"],
|
||||
"title": doc["title"],
|
||||
"url": doc["url"],
|
||||
}
|
||||
chunk["content_hash"] = chunk_content_hash(chunk)
|
||||
out.append(chunk)
|
||||
|
||||
log.info("Chunked %d documents into %d pieces", len(docs), len(out))
|
||||
return out
|
||||
|
||||
|
||||
def content_fingerprint(docs: list[dict]) -> str:
|
||||
"""هش کل محتوا — فقط برای لاگ؛ تشخیص تغییر ردیفی در vectorstore انجام میشود."""
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
payload = json.dumps(docs, ensure_ascii=False, sort_keys=True)
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
# --- زمینه همیشهتازه سایت (بلوک کوتاه تماس/خدمات برای پرامپت) ---
|
||||
_site_context_cache: tuple[float, str] | None = None
|
||||
|
||||
|
||||
def fetch_site_context(database_url: str, ttl: int = 120) -> str:
|
||||
"""نام برند، تماس و فهرست خدمات — با کش کوتاهمدت تا هر پیام یک کوئری سبک بزند."""
|
||||
global _site_context_cache
|
||||
import time as _time
|
||||
|
||||
now = _time.time()
|
||||
if _site_context_cache and now - _site_context_cache[0] < ttl:
|
||||
return _site_context_cache[1]
|
||||
try:
|
||||
dsn = _psycopg_dsn(database_url)
|
||||
brand = _fetch_rows(dsn, "SELECT name, phone, email, address FROM brand LIMIT 1")
|
||||
services = _fetch_rows(dsn, "SELECT title FROM services ORDER BY position")
|
||||
lines: list[str] = []
|
||||
if brand:
|
||||
b = brand[0]
|
||||
lines += [
|
||||
f"نام مجموعه: {_clean(b['name'])}",
|
||||
f"تلفن تماس: {_clean(b['phone'])}",
|
||||
f"ایمیل: {_clean(b['email'])}",
|
||||
f"آدرس: {_clean(b['address'])}",
|
||||
]
|
||||
if services:
|
||||
lines.append("خدمات سایت: " + "، ".join(_clean(s["title"]) for s in services))
|
||||
ctx = "\n".join(lines)
|
||||
_site_context_cache = (now, ctx)
|
||||
return ctx
|
||||
except Exception as e:
|
||||
log.warning("Site context fetch failed: %s", e)
|
||||
return _site_context_cache[1] if _site_context_cache else ""
|
||||
@@ -0,0 +1,130 @@
|
||||
# گزارش ارزیابی چتبات — 2026-10-01 21:05
|
||||
|
||||
- مجموع پرسشها: 21 — درست: 17 — خطا: 0
|
||||
- بازبینی دستی: 4 — خطای فنی: 0
|
||||
- میانگین زمان پاسخ: 9.1s
|
||||
|
||||
## [pass] پروژه میرزا طاهر ۵ کجا ساخته شده و چند متر زیربنا دارد؟
|
||||
*موضوع: projects — 8.2s — منابع: آرامش - میرزا طاهر 4 — /projects/آرامش---میرزا-طاهر-4، آرامش- میرزا طاهر 1 — /projects/آرامش--میرزا-طاهر-1، آرامش میرزا طاهر 2 — /projects/آرامش-میرزا-طاهر-2، آرامش - میرزا طاهر 5 — /projects/آرامش---میرزا-طاهر-5*
|
||||
|
||||
پروژه «آرامش - میرزا طاهر 5» در اصفهان، وحدت، شهریار (محلهی زهران) ساخته شده و متراژ زیربنای آن ۸۱۰۰ مترمربع است.
|
||||
جزئیات کامل در صفحه /projects/آرامش---میرزا-طاهر-5
|
||||
|
||||
## [pass] پروژه آرامش - بابک کی و کجا تحویل شده؟
|
||||
*موضوع: projects — 10.4s — منابع: معرفی صفحه اصلی — /، آخرین مقالات — /blog، آرامش - بابک — /projects/آرامش---بابک، پروژهها — /projects، تحویل و پشتیبانی — /investment*
|
||||
|
||||
پروژه «آرامش - بابک» طبق اطلاعات سایت در سال ۱۴۰۵ تکمیل شده و در اصفهان، شهید رضایی، بین باغ مسجد و ارشاد (محله برزان) قرار دارد.
|
||||
جزئیات کامل در صفحه /projects/آرامش---بابک در دسترس است.
|
||||
|
||||
## [pass] وضعیت پروژه میرزاطاهر ۶ چطور است؟
|
||||
*موضوع: projects — 8.7s — منابع: آرامش - میرزاطاهر 6 — /projects/آرامش---میرزاطاهر-6، آرامش - میرزا طاهر 5 — /projects/آرامش---میرزا-طاهر-5، کوثر- میرزاطاهر — /projects/کوثر--میرزاطاهر، نیکان میرزاطاهر — /projects/نیکان-میرزاطاهر، نگین- میرزاطاهر — /projects/نگین--میرزاطاهر*
|
||||
|
||||
پروژه «آرامش - میرزاطاهر ۶» در اصفهان، میرزاطاهر شرقی (محله زهران) قرار دارد و وضعیت آن **در حال ساخت** است؛ عرصه نیز **در حال اخذ مجوز** است.
|
||||
جزئیات کامل در صفحه /projects/آرامش---میرزاطاهر-6 در دسترس است.
|
||||
|
||||
## [pass] کدام پروژه شما در محله گورتان اصفهان است؟
|
||||
*موضوع: projects — 8.2s — منابع: آرامش - وحدت — /projects/آرامش---وحدت، سالهای توسعه و تجربه — /about، آرامش - آتشگاه — /projects/آرامش---آتشگاه*
|
||||
|
||||
پروژه «آرامش - وحدت» در اصفهان، آتشگاه، محلهی گورتان واقع شده و وضعیت آن تکمیلشده است. این پروژه کاربری مسکونی-تجاری دارد و شامل ۸ واحد مسکونی و ۱ واحد تجاری است.
|
||||
|
||||
جزئیات کامل در صفحه /projects/آرامش---وحدت موجود است.
|
||||
|
||||
## [pass] پروژه میرزا طاهر ۵ چند واحد مسکونی دارد؟
|
||||
*موضوع: projects — 9.0s — منابع: آرامش - میرزا طاهر 4 — /projects/آرامش---میرزا-طاهر-4، آرامش- میرزا طاهر 1 — /projects/آرامش--میرزا-طاهر-1، آرامش - میرزا طاهر 5 — /projects/آرامش---میرزا-طاهر-5، نگین- میرزاطاهر — /projects/نگین--میرزاطاهر، آرامش میرزا طاهر 2 — /projects/آرامش-میرزا-طاهر-2*
|
||||
|
||||
پروژه «آرامش - میرزا طاهر 5» دارای **۲۹ واحد مسکونی** است.
|
||||
جزئیات کامل در صفحه /projects/آرامش---میرزا-طاهر-5
|
||||
|
||||
## [pass] گروه ساختمانی آرامش چند سال سابقه دارد؟
|
||||
*موضوع: stats — 10.3s — منابع: آخرین مقالات — /blog، شرکت آرامش از چه سالی فعالیت میکند؟ — /faq، درباره ما — /about، تجربه بیش از دو دهه — /about، گروه ساختمانی آرامش — /about*
|
||||
|
||||
گروه ساختمانی آرامش بیش از ۲۳ سال سابقه فعالیت در حوزه ساختوساز دارد و فعالیت مستمر خود را از سال ۱۳۸۱ آغاز کرده است.
|
||||
|
||||
## [pass] تا امروز چند پروژه تحویل دادهاید؟
|
||||
*موضوع: stats — 8.7s — منابع: پروژهها — /projects، آمار و افتخارات — /، تعهدی فراتر از تحویل ساختمان — /about، تحویل و پشتیبانی — /investment*
|
||||
|
||||
طبق اطلاعات ثبتشده در سایت، گروه ساختمانی آرامش تاکنون **۶۴ پروژه تحویلداده** است.
|
||||
|
||||
## [pass] مجموع متراژ ساختوساز شما چقدر است؟
|
||||
*موضوع: stats — 9.2s — منابع: آمار و افتخارات — /، شروع مسیر ساختوساز — /about، سرمایهگذاری — /investment، درباره ما — /about، گروه ساختمانی آرامش — /about*
|
||||
|
||||
مجموع زیربنای ساختوساز گروه ساختمانی آرامش ۱۱۱ هزار مترمربع است.
|
||||
|
||||
## [pass] چند خانواده در پروژههای شما ساکن هستند؟
|
||||
*موضوع: stats — 7.2s — منابع: آمار و افتخارات — /*
|
||||
|
||||
بر اساس آمار ثبتشده، بیش از ۵۰۰ خانواده در پروژههای گروه ساختمانی آرامش ساکن هستند.
|
||||
|
||||
## [pass] شماره تماس شما چیست؟
|
||||
*موضوع: contact — 6.6s — منابع: اطلاعات تماس — /contact*
|
||||
|
||||
شماره تماس گروه ساختمانی آرامش: **۰۹۱۳۳۱۰۷۸۰۹**
|
||||
جزئیات بیشتر در صفحه «تماس با ما» موجود است.
|
||||
|
||||
## [pass] دفتر تهران کجاست؟
|
||||
*موضوع: offices — 7.6s — منابع: دفتر تهران — /contact*
|
||||
|
||||
دفتر تهران گروه ساختمانی آرامش در خیابان ولیعصر، برج آرامش، طبقه هجدهم واقع شده است.
|
||||
جزئیات بیشتر در صفحه /contact در دسترس است.
|
||||
|
||||
## [pass] آدرس ایمیل مجموعه چیست؟
|
||||
*موضوع: contact — 8.7s — منابع: اطلاعات تماس — /contact، دفتر نوشهر — /contact، دفتر اصفهان — /contact، تماس با ما — /contact*
|
||||
|
||||
ایمیل مجموعه: arameshsakhtemani@gmail.com
|
||||
|
||||
## [pass] دفاتر شما در چه شهرهایی است؟
|
||||
*موضوع: offices — 9.2s — منابع: ساختمان اداری — /services، ساختمان تجاری — /services*
|
||||
|
||||
دفاتر گروه ساختمانی آرامش در سه شهر زیر فعال هستند:
|
||||
|
||||
- **تهران:** خیابان ولیعصر، برج آرامش، طبقه هجدهم
|
||||
- **اصفهان:** خیابان چهارباغ بالا، مجتمع پارسه، طبقه ششم
|
||||
- **نوشهر:** بلوار دریا، دفتر پروژه دریاکنار
|
||||
|
||||
## [pass] گروه آرامش چه سالی تأسیس شده؟
|
||||
*موضوع: faqs — 18.5s — منابع: شرکت آرامش از چه سالی فعالیت میکند؟ — /faq، آخرین مقالات — /blog، ورود به صنعت ساختمان — /about*
|
||||
|
||||
بر اساس اطلاعات موجود، شرکت ساختمانی آرامش از سال ۱۳۸۱ فعالیت خود را آغاز کرده است. همچنین در صفحه «درباره ما» سابقه ورود مجموعه به صنعت ساختمان از سال ۱۳۷۷ با تأسیس شرکت پیمانکاری ذکر شده است. جزئیات بیشتر در صفحات /faq و /about در دسترس است.
|
||||
|
||||
## [manual] زمین دارم، ساخت را از کجا شروع کنم؟
|
||||
*موضوع: faqs — 7.9s — منابع: اگر زمین داشته باشیم، از کجا باید برای ساخت شروع کنیم؟ — /faq*
|
||||
|
||||
اولین قدم، بررسی زمین و شرایط پروژه است. موقعیت، ضوابط و تراکم، شرایط فنی و ظرفیت اقتصادی زمین بررسی میشود تا پیش از ورود به طراحی و اجرا، مسیر مناسب پروژه مشخص شود. جزئیات کامل در صفحه /faq موجود است.
|
||||
|
||||
## [manual] شرایط مشارکت در ساخت چگونه است؟
|
||||
*موضوع: investment — 8.5s — منابع: آیا امکان مشارکت در ساخت هم دارید؟ — /faq، مشارکت در ساخت — /investment، وبلاگ — /blog، تحویل و پشتیبانی — /investment*
|
||||
|
||||
شرایط مشارکت در ساخت به این صورت است که مالک زمین و گروه ساختمانی آرامش در سود پروژه شریک میشوند و اجرا، دریافت مجوزها و فروش بر عهده ماست. ابتدا ملک بهصورت کارشناسی بررسی میشود، سپس قرارداد شفاف با ضمانت اجرا تنظیم میگردد و در طول پروژه گزارش پیشرفت ارائه میشود. جزئیات کامل در صفحه /investment قابل مشاهده است.
|
||||
|
||||
## [pass] مدل صندوق سرمایهگذاری چطور کار میکند؟
|
||||
*موضوع: investment — 8.1s — منابع: صندوق سرمایهگذاری — /investment، مدلهای همکاری — /investment، سرمایهگذاری ساختمانی — /services، سرمایهگذاری — /investment*
|
||||
|
||||
صندوق سرمایهگذاری به این صورت کار میکند که سرمایهگذاران واحدهایی از پروژههای آرامش را خریداری میکنند و بازدهی آنها در پایان دوره محاسبه میشود. حداقل دوره سرمایهگذاری ۲۴ ماه است، گزارش ارزشگذاری بهصورت فصلی ارائه میشود و امکان انتقال واحد سرمایه نیز وجود دارد.
|
||||
|
||||
جزئیات کامل در صفحه /investment در دسترس است.
|
||||
|
||||
## [pass] پیشخرید واحد یعنی چه؟
|
||||
*موضوع: investment — 8.0s — منابع: پیشخرید واحد — /investment*
|
||||
|
||||
پیشخرید واحد یعنی خرید واحد مسکونی، اداری یا تجاری در مراحل مختلف ساخت. از جمله نکات آن میتوان به امکان شخصیسازی پلان، تضمین زمان تحویل و پرداخت توافقی اشاره کرد. جزئیات کامل در صفحه /investment.
|
||||
|
||||
## [manual] خدمات گروه آرامش چیست؟
|
||||
*موضوع: services — 7.7s — منابع: خدمات شرکت آرامش شامل چه مواردی است؟ — /faq، آخرین مقالات — /blog، آیا امکان مشارکت در ساخت هم دارید؟ — /faq، همراهی از صفر تا صد — /about*
|
||||
|
||||
خدمات گروه ساختمانی آرامش شامل طراحی معماری، ساخت ساختمانهای مسکونی، تجاری و اداری، طراحی و ویلاسازی، طراحی فضاهای عمومی و رفاهی، بازسازی، مدیریت پروژه و سرمایهگذاری ساختمانی است. ما خدمات کامل صفر تا صد را از طراحی تا تحویل کلید پوشش میدهیم. جزئیات بیشتر در صفحه /faq قابل مشاهده است.
|
||||
|
||||
## [manual] نظرات مشتریان قبلی درباره شما چیست؟
|
||||
*موضوع: testimonials — 11.2s — منابع: همراهی با تغییر نیازهای بازار مسکن — /about، نظرات مشتریان — /، سوالات متداول — /faq، سوالات متداول — /faq*
|
||||
|
||||
بر اساس نظرات ثبتشده در سایت، مشتریان قبلی رضایت خود را اینگونه اعلام کردهاند:
|
||||
|
||||
- مهندس سارا کیانی، سرمایهگذار پروژه پارسه: گزارشهای ماهانه آنقدر دقیق بود که نیازی به نگرانی درباره سرمایه نبود و پروژه دو ماه زودتر از موعد به بهرهبرداری رسید.
|
||||
- دکتر امیرحسین راد، ساکن برج الهیه: کیفیت اجرا در جزئیاتی مانند عایق صوتی پنجرهها و نور غیرمستقیم راهروها دیده میشود.
|
||||
- مریم دلاور، مدیر مجموعه ویلاهای دریاکنار: همکاری با تیم طراحی حرفهای بود و ایدهها به زبان معماری ترجمه شد.
|
||||
|
||||
جزئیات بیشتر در صفحه اصلی سایت (/) در بخش نظرات مشتریان آمده است.
|
||||
|
||||
## [fallback-expected] هزینه ساخت هر متر مربع چقدر است؟
|
||||
*موضوع: canary — 9.7s — منابع: آمار و افتخارات — /، اجرا و کنترل کیفیت — /investment، مدیریت پروژه — /services، شفافیت کامل — /about*
|
||||
|
||||
متأسفانه اطلاعات دقیقی در این باره در سایت ثبت نشده است. برای راهنمایی بیشتر میتوانید از صفحه «تماس با ما» با ما در ارتباط باشید.
|
||||
@@ -0,0 +1,191 @@
|
||||
"""گراف گفتگو (LangGraph) — پورت خط لوله v13 در سه گام:
|
||||
|
||||
۱) بازنویسی پرسش با تاریخچه (فقط وقتی تاریخچه هست — صرفهجویی در تأخیر)
|
||||
۲) بازیابی ترکیبی با چند نوعواژه (اختیاری)
|
||||
۳) تولید پاسخ فارسی با قواعد تکیه بر داده
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
import json as _json
|
||||
from typing import Annotated, List, Optional
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langgraph.checkpoint.memory import MemorySaver
|
||||
from langgraph.graph import END, StateGraph
|
||||
from langgraph.graph.message import add_messages
|
||||
|
||||
from . import content as content_mod
|
||||
from .config import settings
|
||||
from .retrieval import retrieve_final
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
FALLBACK_MESSAGE = (
|
||||
"متأسفانه اطلاعات دقیقی در این باره در سایت ثبت نشده است. "
|
||||
"برای راهنمایی بیشتر میتوانید از صفحه «تماس با ما» با ما در ارتباط باشید."
|
||||
)
|
||||
LLM_UNAVAILABLE = (
|
||||
"سرویس هوش مصنوعی هنوز پیکربندی نشده است. "
|
||||
"متغیرهای LLM_BASE_URL و LLM_MODEL را در تنظیمات سرویس چتبات تنظیم کنید."
|
||||
)
|
||||
|
||||
_llm = None
|
||||
|
||||
|
||||
def get_llm() -> ChatOpenAI | None:
|
||||
"""LLM تولید — اگر پیکربندی نشده باشد None برمیگرداند."""
|
||||
global _llm
|
||||
if _llm is None and settings.llm_base_url:
|
||||
_llm = ChatOpenAI(
|
||||
model=settings.llm_model,
|
||||
base_url=settings.llm_base_url,
|
||||
api_key=settings.llm_api_key or "not-needed",
|
||||
temperature=0,
|
||||
streaming=True,
|
||||
)
|
||||
return _llm
|
||||
|
||||
|
||||
class GraphState(TypedDict):
|
||||
messages: Annotated[List, add_messages]
|
||||
documents: List[str]
|
||||
contextualized_query: Optional[str]
|
||||
|
||||
|
||||
# --- گام ۱: بازنویسی پرسش با تاریخچه ---
|
||||
|
||||
def contextualize_query(question: str, history: list) -> str:
|
||||
"""ضمیرها و اشارههای پرسش را با تاریخچه گفتگو مشخص میکند («اون دومی» → موضوع واقعی)."""
|
||||
model = get_llm()
|
||||
if model is None or not history:
|
||||
return question
|
||||
try:
|
||||
history_text = "\n".join(
|
||||
f"{'کاربر' if isinstance(m, HumanMessage) else 'دستیار'}: {str(m.content)[:300]}"
|
||||
for m in history[-6:]
|
||||
)
|
||||
prompt = (
|
||||
"با توجه به تاریخچه گفتگو، پرسش کاربر را به یک پرسش مستقل و کامل فارسی بازنویسی کن.\n"
|
||||
"- ضمیرها و اشارهها (او، آن، همین، دومی، این یکی) را به موضوع واقعیِ ذکرشده در تاریخچه تبدیل کن.\n"
|
||||
"- اگر پرسش از قبل مستقل است، عیناً همان را برگردان.\n"
|
||||
"- فقط متن پرسش بازنویسیشده را برگردان؛ هیچ توضیحی ننویس.\n\n"
|
||||
f"تاریخچه گفتگو:\n{history_text}\n\n"
|
||||
f"پرسش کاربر: {question}\n\n"
|
||||
"پرسش مستقل:"
|
||||
)
|
||||
resp = model.invoke([HumanMessage(content=prompt)], config={"tags": ["utility"]})
|
||||
rewritten = (resp.content or "").strip() if isinstance(resp.content, str) else ""
|
||||
if not rewritten or len(rewritten) > len(question) * 4:
|
||||
return question
|
||||
if rewritten != question:
|
||||
log.info("Contextualized: '%s' → '%s'", question[:60], rewritten[:60])
|
||||
return rewritten
|
||||
except Exception as e:
|
||||
log.warning("Contextualization failed: %s", e)
|
||||
return question
|
||||
|
||||
|
||||
def expand_query(query: str) -> list[str]:
|
||||
"""گسترش پرسش به چند نوعواژه (اختیاری — پیشفرض خاموش برای پیکره کوچک)."""
|
||||
model = get_llm()
|
||||
if model is None:
|
||||
return [query]
|
||||
try:
|
||||
prompt = (
|
||||
"برای جستوجو در محتوای سایت یک گروه ساختمانی، ۳ نوعواژه جایگزین برای این پرسش بساز: "
|
||||
"بازنویسی معنایی، استخراج کلیدواژه، گسترش با مفاهیم مرتبط.\n"
|
||||
'فقط JSON برگردان: {"variants": ["۱", "۲", "۳"]}\n\n'
|
||||
f"پرسش: {query}"
|
||||
)
|
||||
resp = model.invoke([HumanMessage(content=prompt)], config={"tags": ["utility"]})
|
||||
text = resp.content if isinstance(resp.content, str) else ""
|
||||
match = re.search(r'\{.*"variants".*\}', text, re.DOTALL)
|
||||
if match:
|
||||
variants = [v for v in _json.loads(match.group()).get("variants", []) if v and v != query][:3]
|
||||
if variants:
|
||||
log.info("Query variants: %s", [query] + variants)
|
||||
return [query] + variants
|
||||
except Exception as e:
|
||||
log.warning("Query expansion failed: %s", e)
|
||||
return [query]
|
||||
|
||||
|
||||
# --- گام ۲: بازیابی ---
|
||||
|
||||
def retrieve_node(state: GraphState) -> dict:
|
||||
messages = state.get("messages", [])
|
||||
if not messages:
|
||||
return {"documents": []}
|
||||
question = messages[-1].content
|
||||
history = messages[:-1]
|
||||
|
||||
query = contextualize_query(question, history) if settings.contextualize_enabled else question
|
||||
variants = expand_query(query) if settings.query_expansion else [query]
|
||||
|
||||
docs = retrieve_final(query, variants)
|
||||
doc_texts = [f"{d['text']}\n(منبع: {d['title']} — {d['url']})" for d in docs]
|
||||
log.info("Retrieved %d documents for '%s'", len(doc_texts), question[:60])
|
||||
return {
|
||||
"documents": doc_texts,
|
||||
"contextualized_query": query if query != question else None,
|
||||
}
|
||||
|
||||
|
||||
# --- گام ۳: تولید پاسخ ---
|
||||
|
||||
def build_system_prompt(documents: list[str], contextualized_query: str | None) -> str:
|
||||
site_ctx = content_mod.fetch_site_context(settings.database_url, settings.site_context_ttl)
|
||||
docs_block = "\n\n———\n\n".join(documents) if documents else "(سند مرتبطی یافت نشد)"
|
||||
reminder = (
|
||||
f"\n--- یادآوری ---\nپرسش کاربر پس از بازنویسی این است: «{contextualized_query}»\n\n"
|
||||
if contextualized_query else ""
|
||||
)
|
||||
return (
|
||||
"تو دستیار گفتگوی هوشمند سایت «گروه ساختمانی آرامش» هستی و فقط به فارسی پاسخ میدهی.\n"
|
||||
"دانش تو اکیداً محدود به اطلاعات زیر است.\n\n"
|
||||
f"--- اطلاعات پایه سایت (همیشه معتبر) ---\n{site_ctx}\n\n"
|
||||
f"--- اسناد بازیابیشده مرتبط با پرسش ---\n{docs_block}\n"
|
||||
f"{reminder}"
|
||||
"--- قوانین پاسخ ---\n"
|
||||
"۱. فقط بر اساس اطلاعات بالا پاسخ بده؛ بههیچوجه از دانش بیرونی استفاده نکن و چیزی نساز.\n"
|
||||
"۲. پاسخ کوتاه، دقیق و مفید باشد (معمولاً ۲ تا ۵ جمله) و لحن حرفهای و محترمانه داشته باشد.\n"
|
||||
f"۳. اگر اطلاعات کافی در اسناد نیست، فقط همین جمله را بنویس: «{FALLBACK_MESSAGE}»\n"
|
||||
"۴. اگر سند مسیر صفحه مرتبط دارد، در پایان پاسخ آن را معرفی کن (مثلاً: جزئیات کامل در صفحه /blog/... ).\n"
|
||||
"۵. درباره قیمت، زمان دقیق یا هر تعهدی فقط چیزی را بگو که در دادهها آمده است."
|
||||
)
|
||||
|
||||
|
||||
def generate_node(state: GraphState) -> dict:
|
||||
messages = state.get("messages", [])
|
||||
question = messages[-1].content if messages else ""
|
||||
|
||||
model = get_llm()
|
||||
if model is None:
|
||||
return {"messages": [AIMessage(content=LLM_UNAVAILABLE)]}
|
||||
|
||||
documents = state.get("documents") or []
|
||||
system = build_system_prompt(documents, state.get("contextualized_query"))
|
||||
log.info("Generating answer with %d docs (system prompt %d chars)", len(documents), len(system))
|
||||
|
||||
history = messages[:-1]
|
||||
reply = model.invoke(
|
||||
[SystemMessage(content=system), *history, HumanMessage(content=question)],
|
||||
config={"tags": ["generate"]},
|
||||
)
|
||||
return {"messages": [reply]}
|
||||
|
||||
|
||||
# --- گراف ---
|
||||
|
||||
memory = MemorySaver()
|
||||
workflow = StateGraph(GraphState)
|
||||
workflow.add_node("retrieve", retrieve_node)
|
||||
workflow.add_node("generate", generate_node)
|
||||
workflow.set_entry_point("retrieve")
|
||||
workflow.add_edge("retrieve", "generate")
|
||||
workflow.add_edge("generate", END)
|
||||
graph = workflow.compile(checkpointer=memory)
|
||||
@@ -0,0 +1,70 @@
|
||||
"""تستهای خالص (بدون مدل/دیتابیس) برای ماژولهای چتبات — اجرا: python test_pure.py"""
|
||||
import sys
|
||||
import os
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
||||
|
||||
from chatbot.content import chunk_documents, tiptap_blocks, body_to_text
|
||||
from chatbot.vectorstore import chunk_content_hash, chatbot_dsn
|
||||
from chatbot.persian import normalize, tokenize
|
||||
|
||||
docs = [
|
||||
{"text": "پاراگراف کوتاه خدمت الف", "type": "service", "title": "الف", "url": "/services"},
|
||||
{"text": "سؤال اول؟", "type": "faq", "title": "س۱", "url": "/faq"},
|
||||
{"text": "سؤال دوم؟", "type": "faq", "title": "س۲", "url": "/faq"},
|
||||
{"text": "آ" * 2000, "type": "article", "title": "مقاله بلند", "url": "/blog/long"},
|
||||
]
|
||||
chunks = chunk_documents(docs)
|
||||
ids = [c["doc_id"] for c in chunks]
|
||||
assert len(ids) == len(set(ids)), f"duplicate ids: {ids}"
|
||||
|
||||
faq_ids = sorted(c["doc_id"] for c in chunks if c["type"] == "faq")
|
||||
assert faq_ids == ["faq:0:1", "faq:1:1"], faq_ids
|
||||
|
||||
art = [c for c in chunks if c["type"] == "article"]
|
||||
assert len(art) >= 2 and art[1]["doc_id"] == "article:0:2", [x["doc_id"] for x in art]
|
||||
assert "بخش 2 از" in art[1]["text"] and "بخش 1 از" in art[0]["text"]
|
||||
|
||||
c = chunks[0]
|
||||
assert c["content_hash"] == chunk_content_hash(c)
|
||||
c2 = dict(c, title="عنوان عوض شد")
|
||||
# hash فیلد کپیشده است — باید با محاسبه دوباره مقایسه شود، نه با فیلد قدیمی
|
||||
assert chunk_content_hash(c2) != c["content_hash"]
|
||||
|
||||
chunks2 = chunk_documents(docs)
|
||||
assert [x["doc_id"] for x in chunks2] == ids
|
||||
assert [x["content_hash"] for x in chunks2] == [x["content_hash"] for x in chunks]
|
||||
|
||||
settings_dsn = chatbot_dsn()
|
||||
assert settings_dsn.endswith("/aramesh_chatbot"), settings_dsn
|
||||
assert "+psycopg" not in settings_dsn
|
||||
|
||||
# نرمالسازی و توکنسازی فارسی
|
||||
assert normalize("كامل يك ۱۲۳") == "کامل یک 123"
|
||||
t = tokenize("کدام شرکت ساختمانی خوب در تهران؟")
|
||||
assert "شرکت" in t and "تهران" in t and "کدام" not in t, t
|
||||
assert "می\u200cسازیم" in tokenize("می\u200cسازیم") and "سازیم" in tokenize("می\u200cسازیم")
|
||||
|
||||
# استخراج متن TipTap و فرمت قدیمی
|
||||
tiptap_doc = {
|
||||
"type": "doc",
|
||||
"content": [
|
||||
{"type": "heading", "attrs": {"level": 2}, "content": [{"type": "text", "text": "معرفی پروژه"}]},
|
||||
{"type": "paragraph", "content": [
|
||||
{"type": "text", "text": "این برج در تهران "},
|
||||
{"type": "text", "marks": [{"type": "bold"}], "text": "ساخته شد"},
|
||||
{"type": "hardBreak"},
|
||||
{"type": "image", "attrs": {"alt": "نمای بیرونی"}},
|
||||
]},
|
||||
{"type": "bulletList", "content": [
|
||||
{"type": "listItem", "content": [{"type": "paragraph", "content": [{"type": "text", "text": "۲۴ طبقه"}]}]},
|
||||
]},
|
||||
{"type": "paragraph", "content": [{"type": "image", "attrs": {"alt": ""}}]},
|
||||
],
|
||||
}
|
||||
blocks = tiptap_blocks(tiptap_doc)
|
||||
assert blocks == ["معرفی پروژه", "این برج در تهران ساخته شد [تصویر: نمای بیرونی]", "۲۴ طبقه"], blocks
|
||||
assert body_to_text(["الف", "ب"]) == "الف\nب"
|
||||
assert body_to_text(None) == ""
|
||||
|
||||
print(f"ALL PURE TESTS OK — {len(chunks)} chunks from {len(docs)} docs")
|
||||
@@ -0,0 +1,217 @@
|
||||
"""ذخیرهساز برداری pgvector — جایگزین FAISS در مهاجرت به pgvector.
|
||||
|
||||
بردارها در یک دیتابیس جدا (aramesh_chatbot) روی همان نمونه Postgres سایت
|
||||
نگهداری میشوند تا دیتابیس سایت فقطخواندنی بماند. همگامسازی افزایشی است:
|
||||
فقط سطرهای جدید/تغییریافته امبد میشوند (کلید: doc_id پایدار + hash محتوا).
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
from .config import settings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _strip_driver(dsn: str) -> str:
|
||||
return dsn.replace("+psycopg", "").replace("+asyncpg", "")
|
||||
|
||||
|
||||
def chatbot_dsn() -> str:
|
||||
"""DSN دیتابیس اختصاصی چتبات — از DATABASE_URL با تعویض نام دیتابیس ساخته میشود."""
|
||||
parts = urlsplit(_strip_driver(settings.database_url))
|
||||
return urlunsplit(parts._replace(path=f"/{settings.chatbot_db_name}"))
|
||||
|
||||
|
||||
def _admin_dsn() -> str:
|
||||
"""DSN دیتابیس postgres برای ساخت دیتابیس چتبات (فقط یکبار)."""
|
||||
parts = urlsplit(_strip_driver(settings.database_url))
|
||||
return urlunsplit(parts._replace(path="/postgres"))
|
||||
|
||||
|
||||
def ensure_schema() -> None:
|
||||
"""ساخت دیتابیس و جدول بردارها — idempotent و در هر شروع اجرا میشود."""
|
||||
import psycopg
|
||||
from psycopg import errors as pg_errors
|
||||
|
||||
try:
|
||||
with psycopg.connect(_admin_dsn(), autocommit=True, connect_timeout=10) as conn:
|
||||
try:
|
||||
conn.execute(f'CREATE DATABASE "{settings.chatbot_db_name}"')
|
||||
log.info("Created chatbot database '%s'", settings.chatbot_db_name)
|
||||
except pg_errors.DuplicateDatabase:
|
||||
pass
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Cannot reach Postgres to ensure chatbot database: {e}") from e
|
||||
|
||||
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=10) as conn:
|
||||
conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
|
||||
conn.execute(
|
||||
f"""
|
||||
CREATE TABLE IF NOT EXISTS chatbot_chunks (
|
||||
doc_id TEXT PRIMARY KEY,
|
||||
content_hash TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
content JSONB NOT NULL,
|
||||
embedding vector({settings.embedding_dim}) NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS chatbot_chunks_embedding_hnsw
|
||||
ON chatbot_chunks USING hnsw (embedding vector_cosine_ops)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def sync_chunks(chunks: list[dict], force: bool = False) -> dict:
|
||||
"""همگامسازی افزایشی قطعات با جدول pgvector.
|
||||
|
||||
- سطرهایی که دیگر وجود ندارند حذف میشوند
|
||||
- سطرهای جدید یا تغییر یافته (hash یا مدل امبدینگ عوض شده) امبد و upsert میشوند
|
||||
- force=True همه سطرها را از نو امبد میکند
|
||||
خروجی: آمار عملیات برای لاگ.
|
||||
"""
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .embeddings import get_embeddings
|
||||
|
||||
model = settings.embedding_model
|
||||
wanted = {c["doc_id"]: c for c in chunks}
|
||||
|
||||
# row_factory لازم است: پایینتر row["model"]/row["doc_id"] خوانده میشود و
|
||||
# پیشفرض psycopg3 تاپل برمیگرداند (خطای tuple indices must be integers).
|
||||
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=10,
|
||||
row_factory=dict_row) as conn:
|
||||
existing: dict[str, str] = {}
|
||||
if not force:
|
||||
for row in conn.execute("SELECT doc_id, content_hash, model FROM chatbot_chunks").fetchall():
|
||||
if row["model"] == model:
|
||||
existing[row["doc_id"]] = row["content_hash"]
|
||||
else:
|
||||
conn.execute("DELETE FROM chatbot_chunks")
|
||||
|
||||
to_delete = [doc_id for doc_id in existing if doc_id not in wanted]
|
||||
if to_delete:
|
||||
conn.execute(
|
||||
"DELETE FROM chatbot_chunks WHERE doc_id = ANY(%s)",
|
||||
[to_delete],
|
||||
)
|
||||
|
||||
to_upsert = [
|
||||
c for c in chunks
|
||||
if existing.get(c["doc_id"]) != c["content_hash"]
|
||||
]
|
||||
inserted = updated = 0
|
||||
|
||||
if to_upsert:
|
||||
vectors = get_embeddings().embed_documents([c["text"] for c in to_upsert])
|
||||
for chunk, vec in zip(to_upsert, vectors):
|
||||
literal = "[" + ",".join(f"{x:.7f}" for x in vec) + "]"
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO chatbot_chunks (doc_id, content_hash, model, content, embedding)
|
||||
VALUES (%s, %s, %s, %s, %s::vector)
|
||||
ON CONFLICT (doc_id) DO UPDATE SET
|
||||
content_hash = EXCLUDED.content_hash,
|
||||
model = EXCLUDED.model,
|
||||
content = EXCLUDED.content,
|
||||
embedding = EXCLUDED.embedding
|
||||
""",
|
||||
(chunk["doc_id"], chunk["content_hash"], model, Jsonb(chunk), literal),
|
||||
)
|
||||
if chunk["doc_id"] in existing:
|
||||
updated += 1
|
||||
else:
|
||||
inserted += 1
|
||||
|
||||
stats = {"inserted": inserted, "updated": updated, "deleted": len(to_delete),
|
||||
"unchanged": len(wanted) - len(to_upsert)}
|
||||
log.info("Vector sync: %s", stats)
|
||||
return stats
|
||||
|
||||
|
||||
def fetch_all_chunks() -> list[dict]:
|
||||
"""همه قطعات ذخیرهشده (برای ساخت BM25 در حافظه)."""
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=10,
|
||||
row_factory=dict_row) as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT doc_id, content_hash, content FROM chatbot_chunks ORDER BY doc_id"
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"doc_id": r["doc_id"],
|
||||
"content_hash": r["content_hash"],
|
||||
**(r["content"] if isinstance(r["content"], dict) else json.loads(r["content"])),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def vector_count() -> int:
|
||||
"""تعداد بردارهای ذخیرهشده — برای healthz (خطا → ۰)."""
|
||||
try:
|
||||
import psycopg
|
||||
|
||||
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=5) as conn:
|
||||
return int(conn.execute("SELECT count(*) FROM chatbot_chunks").fetchone()[0])
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
def dense_search(query: str, top_k: int) -> list[tuple[dict, float]]:
|
||||
"""جستوجوی معنایی SQL با فاصله کسینوسی — خروجی: (سند، شباهت).
|
||||
|
||||
خطا (مثلاً دیتابیس هنوز آماده نیست) → فهرست خالی تا بازیابی فقط با BM25 ادامه یابد.
|
||||
"""
|
||||
try:
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row as _dict_row
|
||||
|
||||
from .embeddings import get_embeddings
|
||||
|
||||
vec = get_embeddings().embed_query(query)
|
||||
literal = "[" + ",".join(f"{x:.7f}" for x in vec) + "]"
|
||||
with psycopg.connect(chatbot_dsn(), row_factory=_dict_row, connect_timeout=10) as conn:
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT doc_id, content, 1 - (embedding <=> %s::vector) AS sim
|
||||
FROM chatbot_chunks
|
||||
ORDER BY embedding <=> %s::vector
|
||||
LIMIT %s
|
||||
""",
|
||||
(literal, literal, top_k),
|
||||
).fetchall()
|
||||
return [(_row_to_doc(r), float(r["sim"])) for r in rows]
|
||||
except Exception as e:
|
||||
log.warning("Dense search failed (%s) — falling back to keyword only", e)
|
||||
return []
|
||||
|
||||
|
||||
def _row_to_doc(row: Any) -> dict:
|
||||
content = row["content"] if isinstance(row["content"], dict) else json.loads(row["content"])
|
||||
return {
|
||||
"doc_id": row["doc_id"],
|
||||
"text": content.get("text", ""),
|
||||
"type": content.get("type", ""),
|
||||
"title": content.get("title", ""),
|
||||
"url": content.get("url", ""),
|
||||
}
|
||||
|
||||
|
||||
def chunk_content_hash(chunk: dict) -> str:
|
||||
"""هش محتوای قطعه — تغییر متن یا متادیتا یعنی سطر باید بهروز شود."""
|
||||
payload = json.dumps(
|
||||
{k: chunk[k] for k in ("text", "type", "title", "url")},
|
||||
ensure_ascii=False, sort_keys=True,
|
||||
)
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
|
||||
@@ -0,0 +1,71 @@
|
||||
# کپی کنید: cp .env.example .env — و همه مقادیر change-me را عوض کنید.
|
||||
# راه سادهتر: bash scripts/gen-env.sh — همهٔ رمزها را تصادفی و قوی میسازد.
|
||||
# docker compose بهطور خودکار این فایل را میخواند؛ بدون آن استک بالا نمیآید.
|
||||
|
||||
# --- رمزهای اصلی (اجباری) ---
|
||||
# تولید کلید تصادفی: python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
SECRET_KEY=change-me-to-a-long-random-string
|
||||
POSTGRES_PASSWORD=change-me-db-password
|
||||
MINIO_ROOT_USER=aramesh
|
||||
MINIO_ROOT_PASSWORD=change-me-minio-password
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=change-me-admin-password
|
||||
|
||||
# --- اختیاری ---
|
||||
# پورت ورود Traefik در توسعه (پیشفرض 5173)
|
||||
TRAEFIK_HTTP_PORT=5173
|
||||
# نشانی عمومی سایت برای sitemap و آدرس مطلق OG — در تولید مثل https://aramesh.example
|
||||
# در تولید این مقدار هم پایهٔ پروب بیروننگر مانیتورینگ است.
|
||||
SITE_URL=
|
||||
# آدرسهای مجاز CORS (لیست JSON) — پیشفرض فقط لوکالهاست
|
||||
# CORS_ORIGINS=["http://localhost:5173"]
|
||||
|
||||
# --- بیلد فرانتاند (در زمان npm run build روی هاست خوانده میشود — stack.sh پاس میدهد) ---
|
||||
# اگر API روی مبدأ دیگری است (مثل توسعه ویندوز با پورت 19001) تنظیم کنید؛ هممبدأ یعنی خالی
|
||||
VITE_API_URL=
|
||||
# اسکریپت ردیاب Umami — خالی یعنی آنالیتیکس خاموش؛ در تولید مثل:
|
||||
# VITE_UMAMI_SRC=https://analytics.aramesh.example/script.js
|
||||
VITE_UMAMI_SRC=
|
||||
# شناسهٔ وبسایت از داشبورد Umami (اولین بار: وبسایت را در analytics.localhost بسازید)
|
||||
VITE_UMAMI_WEBSITE_ID=
|
||||
|
||||
# --- چتبات (دستیار هوشمند) ---
|
||||
# LLM سازگار با OpenAI — اجباری برای پاسخگویی چتبات؛ خالی یعنی سرویس بالا میآید اما پاسخ نمیدهد
|
||||
LLM_BASE_URL=
|
||||
LLM_API_KEY=
|
||||
LLM_MODEL=openai/gpt-oss-120b
|
||||
# توکن محافظت از POST /chat/reindex — خالی یعنی فقط از شبکه داخلی
|
||||
CHAT_REINDEX_TOKEN=
|
||||
|
||||
# --- مانیتورینگ (docker-compose.monitoring.yml) ---
|
||||
GRAFANA_ADMIN_USER=admin
|
||||
GRAFANA_ADMIN_PASSWORD=change-me-grafana-password
|
||||
# هشدارها به بله — توکن بات (همان شکل تلگرام؛ از BotFather بله) و شناسه چت/گروه
|
||||
# شناسه چت: به بات یک پیام بدهید سپس:
|
||||
# curl "https://tapi.bale.ai/bot<توکن>/getUpdates"
|
||||
ALERT_BOT_TOKEN=
|
||||
ALERT_CHAT_ID=0
|
||||
|
||||
# --- عملیات ---
|
||||
# نگهداری پشتیبانهای شبانه (روز) — scripts/backup.sh
|
||||
RETENTION_DAYS=14
|
||||
# انتشار پشتیبان خارج از سرور (rclone remote مثل storage:aramesh-backups) — خالی یعنی خاموش
|
||||
OFFSITE_RCLONE_REMOTE=
|
||||
|
||||
# --- فقط برای docker-compose.prod.yml (حالت تولید با TLS) ---
|
||||
# DOMAIN=aramesh.example
|
||||
# ACME_EMAIL=admin@aramesh.example
|
||||
# دامنه دوم (در صورت وجود) — مسیرها و گواهی TLS برای هر دو صادر میشود
|
||||
# DOMAIN_ALIAS=aramesh.example.ir
|
||||
|
||||
# --- پیشنمایش خصوصی و انتشار (scripts/preview-mode.sh) ---
|
||||
# «on» یعنی سایت آنلاین است اما پشت گیت ورود و بدون ایندکس؛ «off» یعنی انتشار عمومی.
|
||||
# این مقادیر را دستی ویرایش نکنید — اسکریپت preview-mode.sh هماهنگشان میکند:
|
||||
# bash scripts/preview-mode.sh on|off|status → bash scripts/stack.sh deploy-prod
|
||||
# PREVIEW_MODE=on
|
||||
# هش htpasswd کاربر مشترک پیشنمایش — اولین «on» خودش میسازد
|
||||
# PREVIEW_AUTH_USERS=preview:$apr1$...
|
||||
# فهرست میانافزارهای فعال؛ «on» پرش میکند و «off» خالیش میکند
|
||||
# PREVIEW_MIDDLEWARES=preview-auth@docker,preview-noindex@docker
|
||||
# در انتشار، دامنه دوم را به اصلی ریدایرکت میکند تا محتوای تکراری ساخته نشود
|
||||
# ALIAS_REDIRECT_MIDDLEWARES=to-primary@docker
|
||||
@@ -0,0 +1,7 @@
|
||||
# اسکریپتهای شل باید در لینوکس هم LF باشند — CRLF در bash میشکند
|
||||
*.sh text eol=lf
|
||||
*.yml text
|
||||
*.yaml text
|
||||
*.json text
|
||||
Dockerfile text
|
||||
*.py text
|
||||
@@ -0,0 +1,47 @@
|
||||
name: CI
|
||||
|
||||
# گیت سرور self-hosted شما (Gitea Actions / Forgejo) همین سینتکس را اجرا میکند؛
|
||||
# روی GitHub هم بیتغییر کار میکند.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.13"
|
||||
|
||||
- name: Install backend deps
|
||||
run: pip install -r backend/requirements.txt -r backend/requirements-dev.txt
|
||||
|
||||
- name: Run backend tests
|
||||
working-directory: backend
|
||||
run: pytest -q
|
||||
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
|
||||
- name: Frontend typecheck/build
|
||||
working-directory: frontend
|
||||
run: |
|
||||
npm ci
|
||||
npm run build
|
||||
|
||||
images:
|
||||
runs-on: ubuntu-latest
|
||||
needs: tests
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Build images
|
||||
run: docker compose -f docker-compose.yml build backend frontend chatbot
|
||||
@@ -9,6 +9,15 @@ env/
|
||||
# Environment
|
||||
.env
|
||||
|
||||
# مانیتورینگ — کانفیگ رندرشدهٔ alertmanager (حاوی توکن بله است)
|
||||
monitoring/alertmanager/alertmanager.rendered.yml
|
||||
|
||||
# تنظیمات محلی هر ماشین
|
||||
docker-compose.override.yml
|
||||
|
||||
# پشتیبانگیری محلی
|
||||
backups/
|
||||
|
||||
# Node / Vite
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -19,7 +28,11 @@ dist/
|
||||
.vscode/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.zcode/
|
||||
|
||||
# Database
|
||||
*.sqlite3
|
||||
*.db
|
||||
|
||||
# تصاویر محلی — از پنل/کنسول MinIO مدیریت میشوند
|
||||
frontend/public/images/
|
||||
|
||||
@@ -2,73 +2,329 @@
|
||||
|
||||
مونوریپوی سایت گروه ساختمانی آرامش شامل:
|
||||
|
||||
- **`frontend/`** — سایت React + Vite + Tailwind (همه محتوا از API خوانده میشود)
|
||||
- **`backend/`** — بکاند FastAPI + SQLAlchemy 2 + PostgreSQL + JWT
|
||||
- **`frontend/`** — سایت React + Vite + Tailwind (تمام متنها و تصاویر از API خوانده میشود)
|
||||
- **`backend/`** — بکاند FastAPI + SQLAlchemy 2 + PostgreSQL (pgvector) + JWT + MinIO
|
||||
- **`chatbot/`** — دستیار هوشمند (FastAPI + LangGraph + RAG با pgvector، پاسخ استریمی)
|
||||
- **مانیتورینگ و آنالیتیکس** — Prometheus/Grafana/Loki و Umami بهصورت لایههای compose
|
||||
|
||||
## معماری
|
||||
|
||||
```
|
||||
Traefik (تنها نقطه ورود — 80/443 در تولید)
|
||||
├── / → Caddy (فایلهای استاتیک SPA)
|
||||
├── /api → FastAPI (بکاند) + متریک /metrics فقط داخلی
|
||||
├── /media → MinIO (باکت aramesh-media)
|
||||
├── /chat → چتبات (SSE استریم پاسخ)
|
||||
├── grafana.* → Grafana (مانیتورینگ — لایه monitoring)
|
||||
└── analytics.* → Umami (آنالیتیکس محصول)
|
||||
```
|
||||
|
||||
- **همه محتوای متنی سایت در PostgreSQL است** — هیچ متنی در کد فرانتاند هاردکد نشده؛
|
||||
با یک درخواست `GET /api/site` بارگذاری و از پنل مدیریت ویرایش میشود
|
||||
- **تصاویر آپلودی در MinIO** (Object Storage سازگار با S3) ذخیره میشوند و با مسیر نسبی
|
||||
`/media/...` برگردانده میشوند — بکاند ذخیرهسازی بدون تغییر محتوای دیتابیس قابل تعویض است
|
||||
- مسیریابی همهچیز روی **Traefik** است (با Docker labels) — nginx در پروژه وجود ندارد
|
||||
- شبکههای compose تفکیک شدهاند: `edge` (سرویسهای پشت Traefik) و `internal`
|
||||
(دیتابیس/ذخیرهسازی) — فرانتاند هیچ راه مستقیمی به دیتابیس ندارد
|
||||
- **لاگها**: json-file با سقف ۱۰MB×۳ برای هر سرویس؛ علاوه بر آن Promtail همه را به
|
||||
Loki میفرستد تا در Grafana جستوجو شوند
|
||||
|
||||
## ساختار
|
||||
|
||||
```
|
||||
├── frontend/ # سایت React
|
||||
│ ├── src/ # کد منبع (api.tsx = لایه اتصال به بکاند)
|
||||
│ ├── Dockerfile # بیلد Node + سرو با nginx
|
||||
│ └── nginx.conf # پروکسی /api به بکاند
|
||||
├── backend/ # بکاند FastAPI
|
||||
│ ├── app/ # کد منبع
|
||||
│ ├── requirements.txt
|
||||
│ ├── Dockerfile
|
||||
│ └── .env.example
|
||||
└── docker-compose.yml # اجرای کامل با یک دستور
|
||||
├── frontend/ # سایت React (بیلد روی هاست — ایمیج فقط سرو میکند)
|
||||
│ ├── src/ # کد منبع (api.tsx = لایه اتصال به بکاند)
|
||||
│ ├── Caddyfile # سرو استاتیک + کش immutable برای /assets/*
|
||||
│ └── Dockerfile # Caddy — بدون root
|
||||
├── backend/ # بکاند FastAPI
|
||||
│ ├── app/ # کد منبع (آپلود: app/api/admin.py — سئو: app/seo_pages.py)
|
||||
│ ├── migrations/ # مهاجرتهای نسخهدار Alembic
|
||||
│ ├── tests/ # تستهای API (pytest)
|
||||
│ ├── alembic.ini
|
||||
│ └── Dockerfile # بدون root — خاموشی تمیز با exec
|
||||
├── chatbot/ # دستیار هوشمند (RAG + pgvector)
|
||||
├── monitoring/ # پیکربندی Prometheus/Alertmanager/Loki/Promtail/Grafana
|
||||
├── scripts/
|
||||
│ ├── stack.sh # ابزار اصلی عملیات — deploy/logs/health/backup/restore/update
|
||||
│ ├── backup.sh # پشتیبان کامل (DB + تصاویر) با چکسام و گزینه انتشار بیرونی
|
||||
│ ├── restore.sh # بازگردانی پشتیبان دیتابیس
|
||||
│ ├── gen-env.sh # ساخت .env با رمزهای قوی تصادفی
|
||||
│ ├── audit.sh # ممیزی آسیبپذیری وابستگیها و ایمیجها
|
||||
│ ├── migrate-media.py # انتقال یکباره تصاویر CDN خارجی به MinIO
|
||||
│ └── ci.sh # تست + بیلد ایمیج (محلی یا هر CI)
|
||||
├── docker-compose.yml # استک اصلی (شامل چتبات و Umami)
|
||||
├── docker-compose.monitoring.yml # لایه مانیتورینگ
|
||||
├── docker-compose.prod.yml # لایه تولید: TLS، دامنه، سختسازی پورتها
|
||||
└── docker-compose.override.yml # تنظیمات محلی این ماشین (در گیت نیست)
|
||||
```
|
||||
|
||||
## اجرا با Docker (سادهترین راه)
|
||||
## اجرا با Docker
|
||||
|
||||
پیشنیاز: Docker Desktop. بیلد فرانتاند روی هاست انجام میشود (کانتینر فقط فایلهای
|
||||
`dist/` را سرو میکند) — `scripts/stack.sh` همین را به یک دستور تبدیل میکند:
|
||||
|
||||
```bash
|
||||
docker compose up --build
|
||||
cp .env.example .env # یا: bash scripts/gen-env.sh (رمزهای قوی تصادفی)
|
||||
cd frontend && npm install && cd ..
|
||||
bash scripts/stack.sh deploy # بیلد فرانت + بیلد و بالا آوردن استک + انتظار برای سلامت
|
||||
```
|
||||
|
||||
- سایت: http://localhost:5173
|
||||
- مستندات API: http://localhost:8000/docs
|
||||
- دیتابیس PostgreSQL در کانتینر جدا (دادهها در volume ذخیره میشوند)
|
||||
- بکاند هنگام شروع، خودش جداول و دادههای اولیه سایت را seed میکند
|
||||
- nginx درخواستهای `/api` را خودش به بکاند پروکسی میکند — نیازی به تنظیم CORS نیست
|
||||
- سایت: http://localhost:18081 (پورت از `TRAEFIK_HTTP_PORT` در `.env`) — ورود مدیریت: `/admin/login`
|
||||
- دستورهای عملیات: `bash scripts/stack.sh` — `logs`، `ps`، `health`، `backup`، `restore`، `update`، `seed-force`
|
||||
- مستندات API: http://localhost:19001/docs (با `docker-compose.override.yml` محلی)
|
||||
- کنسول MinIO: http://localhost:9001 — کاربر/رمز از متغیرهای `MINIO_ROOT_*` در `.env`
|
||||
- دیتابیس PostgreSQL (تصویر pgvector)، آبجکتاستور MinIO و کش مدلهای چتبات هر یک
|
||||
در کانتینر جدا با volume دائمی
|
||||
- بکاند هنگام شروع، جداول پایه را میسازد، **مهاجرتهای Alembic** را اعمال میکند و
|
||||
**فقط جدولهای خالی** را seed میکند — ارتقای نسخه دادههای فعلی را از بین نمیبرد
|
||||
- `minio-setup` باکت `aramesh-media` را میسازد و فقط **وقتی باکت خالی است** تصاویر
|
||||
`seed-media/` را میریزد — `db-init` هم دیتابیسهای `umami` و `aramesh_chatbot` را
|
||||
روی همان نمونهٔ Postgres میسازد
|
||||
|
||||
## اجرای محلی (توسعه)
|
||||
> نکته برای تازهواردها: هیچ فایل رمزدار در گیت نیست. فقط `.env.example` را کپی کنید؛
|
||||
> فایلهای `.env`/`env` در `.gitignore` هستند و هرگز commit نشوند.
|
||||
>
|
||||
> پایهٔ API فرانتاند در زمان بیلد از `VITE_API_URL` در `.env` خوانده میشود —
|
||||
> در توسعه ویندوزیِ این ماشین `VITE_API_URL=http://localhost:19001` بگذارید.
|
||||
|
||||
### بکاند
|
||||
## انتشار واقعی (TLS)
|
||||
|
||||
پیشنیاز: رکوردهای DNS (`example.com`، `analytics.example.com` و اگر مانیتورینگ فعال
|
||||
است `grafana.example.com`) به این سرور، سپس در `.env`: `DOMAIN`، `ACME_EMAIL` و
|
||||
`SITE_URL=https://example.com`:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python -m venv .venv
|
||||
.venv\Scripts\activate # ویندوز — در لینوکس: source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
|
||||
# فایل .env از روی .env.example بسازید و DATABASE_URL را تنظیم کنید
|
||||
python -m app.seed # ساخت جداول + محتوای اولیه
|
||||
uvicorn app.main:app --reload
|
||||
bash scripts/stack.sh deploy-prod
|
||||
```
|
||||
|
||||
### فرانتاند
|
||||
- Traefik گواهی Let's Encrypt میگیرد و تمدید میکند؛ همه درخواستهای HTTP به HTTPS هدایت میشوند
|
||||
- **پورتهای مدیریتی MinIO (۹۰۰۱ کنسول و ۱۹۰۰۰ API) در تولید فقط روی `127.0.0.1`
|
||||
بسته میشوند** — دسترسی از راه دور فقط با تونل SSH:
|
||||
`ssh -L 9001:127.0.0.1:9001 server`
|
||||
- همه روترهای websecure هدرهای امنیتی میگیرند (HSTS + nosniff)
|
||||
|
||||
### پیشنمایش خصوصی (کار روی سایت، قبل از انتشار عمومی)
|
||||
|
||||
سایت روی اینترنت بالا میآید و تیم با همان پنل مدیریت محتوا را ویرایش میکند
|
||||
(ویرایش درجای ایمیل/تلفن/متنها و نوشتن مقاله)، اما **نه عموم به آن دسترسی دارند و
|
||||
نه گوگل چیزی ایندکس میکند**. دو لایه محافظت:
|
||||
|
||||
1. **گیت ورود Traefik (Basic Auth)** — همه مسیرها (سایت، API، تصاویر و چت) پشت یک
|
||||
نام کاربری/رمز مشترکاند؛ بدون آن فقط ۴۰۱ برمیگردد
|
||||
2. **noindex** — هدر `X-Robots-Tag` روی همه پاسخها + `robots.txt` مسدودکننده +
|
||||
نقشه سایت خالی؛ حتی اگر گیت برداشته شود، گوگل چیزی ذخیره نمیکند
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run dev # http://localhost:5173
|
||||
bash scripts/preview-mode.sh on # فعالسازی (بار اول نام کاربری/رمز میسازد و چاپ میکند)
|
||||
bash scripts/stack.sh deploy-prod # اعمال
|
||||
bash scripts/preview-mode.sh status # وضعیت فعلی
|
||||
```
|
||||
|
||||
آدرس بکاند در `frontend/src/config.ts` از `VITE_API_URL` خوانده میشود؛
|
||||
اگر تنظیم نشود پیشفرض `http://localhost:8000` است.
|
||||
- دامنه اصلی (`DOMAIN`) و دامنه دوم (`DOMAIN_ALIAS`) هر دو سرو میشوند و هر دو گیت دارند
|
||||
- برای دادن دسترسی به کارفرما، همان نام کاربری/رمز مشترک را بدهید
|
||||
- رمز مشترک در `.env` (`PREVIEW_AUTH_USERS`) میماند — فقط یکبار چاپ میشود
|
||||
|
||||
### انتشار عمومی (برداشتن پیشنمایش)
|
||||
|
||||
```bash
|
||||
bash scripts/preview-mode.sh off # حذف گیت ورود + اجازه ایندکس
|
||||
bash scripts/stack.sh deploy-prod
|
||||
```
|
||||
|
||||
بعد از این مرحله:
|
||||
|
||||
1. دامنه دوم بهصورت ۳۰۱ دائمی به دامنه اصلی ریدایرکت میشود (جلوگیری از محتوای تکراری)
|
||||
2. در Search Console دامنه را تأیید و `https://DOMAIN/sitemap.xml` را ثبت کنید
|
||||
3. اگر پیشتر چیزی ایندکس شده بود، حذفش را از همان کنسول درخواست کنید
|
||||
|
||||
### چکلیست رفتن به تولید
|
||||
|
||||
1. `bash scripts/gen-env.sh` — رمزهای قوی جدید (رمزهای `.env` توسعه را کپی نکنید)
|
||||
2. DNS: رکوردهای دامنه و زیردامنهها + باز بودن پورتهای ۸۰/۴۴۳ در فایروال
|
||||
3. `DOMAIN`، `DOMAIN_ALIAS` (دامنه دوم)، `ACME_EMAIL`، `SITE_URL` را در `.env` تنظیم کنید
|
||||
4. `bash scripts/preview-mode.sh on` — اولین انتشار بهصورت پیشنمایش خصوصی میرود؛
|
||||
محتوا را روی سایت آنلاین نهایی کنید و بعد `preview-mode.sh off` + deploy مجدد
|
||||
5. `python scripts/migrate-media.py` — انتقال یکباره تصاویر CDN خارجی به MinIO
|
||||
6. پشتیبانگیری خودکار: `docker compose --profile ops up -d db-backup` (پشتیبان ساعتی)
|
||||
+ `scripts/backup.sh` شبانه با cron/Task Scheduler
|
||||
7. یک تمرین بازگردانی: `bash scripts/restore.sh backups/db-<زمان>.sql.gz` روی محیط آزمایشی
|
||||
8. مانیتورینگ (بخش پایین) و سپس چتبات/آنالیتیکس را با متغیرهای LLM و Umami فعال کنید
|
||||
|
||||
## مانیتورینگ (Prometheus + Grafana + Loki)
|
||||
|
||||
```bash
|
||||
bash scripts/stack.sh monitoring
|
||||
# در تولید (سه فایل با هم):
|
||||
docker compose -f docker-compose.yml -f docker-compose.monitoring.yml -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
- داشبورد: `grafana.localhost` (توسعه) یا `grafana.example.com` (تولید — برچسبهای
|
||||
روتر آن را در `docker-compose.override.yml` سرور بگذارید؛ نمونه در انتهای
|
||||
`docker-compose.prod.yml`) — کاربر/رمز از `GRAFANA_ADMIN_*` در `.env`
|
||||
- دو داشبورد آمادهٔ «زیرساخت» و «اپلیکیشن» بهصورت code-provisioned سوار میشوند
|
||||
- **هشدارها به بله**: در `.env` مقدار `ALERT_BOT_TOKEN` (بات بله — همان شکل API تلگرام،
|
||||
از BotFather بله) و `ALERT_CHAT_ID` را بگذارید (شناسه چت: به بات یک پیام بدهید سپس
|
||||
`curl "https://tapi.bale.ai/bot<توکن>/getUpdates"`) — قواعد آماده در
|
||||
`monitoring/prometheus/alerts.yml`:
|
||||
پایینبودن هر سرویس، شکست بررسی عمق سلامت، پرشدن دیسک، نرخ خطای 5xx، انقضای گواهی TLS،
|
||||
**کهنهشدن پشتیبان** (سنجهٔ `backup_success_time` از `scripts/backup.sh`) و...
|
||||
- **لاگها در Grafana**: Promtail لاگ همهٔ کانتینرهای استک را به Loki میفرستد —
|
||||
برای خطاهای بکاند از داشبورد «اپلیکیشن» پنل لاگ را ببینید
|
||||
- **سلامت واقعی**: `/api/health` اتصال DB و MinIO را واقعاً میآزماید (503 در خرابی)؛
|
||||
پروب blackbox هم همین را از بیرون و نشانی `SITE_URL` را عمومی چک میکند
|
||||
- مصرف منابع مجموع لایه حدود ۱ تا ۱.۵ گیگابایت RAM است؛ حذف هر سرویس بقیه را نمیشکند
|
||||
|
||||
## آنالیتیکس محصول (Umami)
|
||||
|
||||
استک شامل سرویس Umami است؛ داشبورد: `analytics.localhost` (توسعه) یا
|
||||
`analytics.example.com` (تولید). بدون کوکی — بدون نیاز به بنر رضایت.
|
||||
|
||||
راهاندازی (یکبار):
|
||||
|
||||
1. استک را بالا بیاورید و به `analytics.localhost` وارد شوید (پیشفرض `admin`/`umami`
|
||||
— بلافاصله رمز را عوض کنید)
|
||||
2. یک وبسایت با دامنهٔ سایت بسازید؛ «شناسه وبسایت» را در `.env` بگذارید:
|
||||
`VITE_UMAMI_WEBSITE_ID=...` و آدرس اسکریپت: `VITE_UMAMI_SRC=https://analytics.example.com/script.js`
|
||||
3. `bash scripts/stack.sh deploy` — اسکریپت ردیاب در `index.html` تزریق میشود
|
||||
|
||||
رخدادهای سفارشی که خودکار ارسال میشوند: ارسال فرم تماس (`contact-submit`)، عضویت
|
||||
خبرنامه (`newsletter-signup`)، کلیک تلفن (`phone-click`)، باز کردن چتبات
|
||||
(`chat-open`)، پرسش از چتبات (`chat-question`)، تغییر زبان (`lang-switch`) —
|
||||
سرچشمه: `frontend/src/analytics.ts`.
|
||||
|
||||
## چتبات (دستیار هوشمند)
|
||||
|
||||
- RAG روی محتوای همان دیتابیس سایت: امبدینگ MiniLM چندزبانه + BM25 + رنکر — بردارها
|
||||
در دیتابیس جدا `aramesh_chatbot` (pgvector) روی همان نمونهٔ Postgres
|
||||
- مسیرها: `GET /chat/healthz`، `GET /chat/suggestions`، `GET /chat/stream` (SSE) —
|
||||
رابط کاربری: ویجت شناور پایین صفحه (`ChatWidget.tsx`)
|
||||
- راهاندازی: `LLM_BASE_URL`/`LLM_API_KEY`/`LLM_MODEL` در `.env` (هر LLM سازگار با
|
||||
OpenAI) — بدون آن سرویس بالا میآید اما پاسخ نمیدهد
|
||||
- اولین اجرا مدلها را دانلود میکند (~۵۰۰MB در حجم `chatbot_hf`) — کند است، طبیعی است
|
||||
- ایندکس هر ۱۰ دقیقه خودش با تغییرهای محتوا همگام میشود؛ همگامسازی فوری با
|
||||
`POST /chat/reindex` و هدر `x-reindex-token` (از `CHAT_REINDEX_TOKEN`)
|
||||
|
||||
## امکانات بکاند
|
||||
|
||||
- **API عمومی**: برند، خدمات، پروژهها، مقالات، نظرات، سوالات متداول، تیم، تایملاین، آمار و...
|
||||
- **فرم تماس** `POST /api/contact` و **خبرنامه** `POST /api/newsletter`
|
||||
- **پنل مدیریت** با JWT: ورود `POST /api/auth/login` (پیشفرض: `admin` / `aramesh123`) و سپس CRUD کامل همه محتواها در `/api/admin/...`
|
||||
- همه محتوا در یک درخواست: `GET /api/site`
|
||||
- **API عمومی**: برند، منو، هیرو، خدمات، پروژهها، مقالات، نظرات، سوالات متداول، تیم،
|
||||
تایملاین، آمار، دفاتر، مدلهای سرمایهگذاری و... — همه در دیتابیس
|
||||
- **فرم تماس** `POST /api/contact` و **خبرنامه** `POST /api/newsletter` — هر دو با
|
||||
محدودسازی نرخ (تماس: ۵ در ۱۵ دقیقه، خبرنامه: ۳ در ساعت برای هر IP) + دامنهٔ پنهان
|
||||
(honeypot) ضدربات + میانافزار محدودسازی سیلاب روی Traefik
|
||||
- **پنل مدیریت** با JWT: ورود `POST /api/auth/login` (مقادیر از `ADMIN_*` در `.env` —
|
||||
هیچ رمز پیشفرضی در کد وجود ندارد) و سپس CRUD کامل همه محتواها در `/api/admin/...`
|
||||
- **تغییر رمز** `POST /api/auth/change-password` — از نوار مدیریت پایین سایت (دکمه «رمز») هم در دسترس است
|
||||
- **محدودسازی ورود**: بعد از ۵ ورود ناموفق در ۱۵ دقیقه از یک IP، درخواست با 429 رد میشود
|
||||
(IP واقعی کلاینت با `--proxy-headers` از پشت Traefik درست خوانده میشود)
|
||||
- **آپلود تصویر** `POST /api/admin/upload` (فقط توکن ادمین، حداکثر ۱۰MB) — فایل در MinIO
|
||||
ذخیره و URL نسبی `/media/...` برمیگردد؛ در همان لحظه تا ۲۰۰۰ پیکسل کوچک و دوباره
|
||||
فشرده میشود (Pillow) تا سرعت صفحه حفظ شود
|
||||
- **خروجی CSV** از نوار مدیریت: پیامهای تماس و مشترکان خبرنامه (با BOM برای Excel)
|
||||
- **ویرایش جزئی** `PATCH /api/admin/{resource}/{id}` — فقط فیلدهای ارسالشده عوض میشوند
|
||||
- **ترتیببندی** `POST /api/admin/{resource}/reorder` — با `{"ids": [...]}`
|
||||
- همه محتوا در یک درخواست: `GET /api/site` (مقالههای پیشنویس در آن نمیآیند)
|
||||
- **مهاجرتهای اسکیما**: Alembic (`backend/migrations/`) — هر تغییر اسکیمای جدید باید
|
||||
revision شود: `cd backend && alembic revision --autogenerate -m "..."` و پس از بازبینی
|
||||
commit؛ در استارت کانتینر خودکار `upgrade head` اجرا میشود
|
||||
- **تستها**: `cd backend && .venv/Scripts/activate && pytest tests` (۲۴ تست — شامل
|
||||
honeypot، محدودسازی نرخ و پاکسازی)
|
||||
|
||||
> در محیط واقعی حتماً `SECRET_KEY` و `ADMIN_PASSWORD` را تغییر دهید.
|
||||
> در محیط واقعی حتماً `SECRET_KEY`، `ADMIN_PASSWORD` و `MINIO_ROOT_PASSWORD` را قوی
|
||||
> بگیرید (`bash scripts/gen-env.sh`) و بعد از اولین ورود، رمز را از نوار مدیریت عوض کنید.
|
||||
|
||||
## ویرایش زنده سایت (دوقلوی دیجیتال)
|
||||
|
||||
ادمینها نیازی به داشبورد جدا ندارند — خود سایت ویرایشگر است:
|
||||
|
||||
1. به `/admin/login` بروید و وارد شوید
|
||||
2. نوار شناور پایین صفحه ظاهر میشود؛ **حالت ویرایش** را روشن کنید
|
||||
3. روی هر متن کلیک کنید و ویرایش کنید — **خروج از کادر، بلافاصله ذخیره میشود**
|
||||
(Enter ذخیره، Esc لغو)؛ وضعیت ذخیره در نوار پایین دیده میشود
|
||||
4. آیتمهای مجموعهها (خدمات، پروژهها، مقالات، نظرات، تیم و...) با هاور، دکمههای
|
||||
ویرایش / حذف / جابهجایی ترتیب نشان میدهند؛ دکمه «افزودن» هم انتهای هر لیست هست
|
||||
5. تصویرها از همان کشوها به MinIO آپلود میشوند
|
||||
|
||||
- در حالت ویرایش، لینکها کلیک نمیشوند تا ویرایش متن ممکن باشد
|
||||
- بازدیدکنندههای عادی هیچ اثری از این لایه نمیبینند (بدون توکن، همه درخواستهای
|
||||
مدیریتی `401` برمیگردند)
|
||||
- تمام تغییرها بلافاصله در PostgreSQL ثبت میشوند — با Ctrl+F5 هم میمانند
|
||||
|
||||
## وبلاگ — نوشتن با ویرایشگر WYSIWYG
|
||||
|
||||
مقالات با ویرایشگر غنی **TipTap** نوشته میشوند (همان تجربه Medium):
|
||||
|
||||
- در حالت ویرایش، روی هر مقاله در صفحه وبلاگ دکمه ویرایش را بزنید — کشوی نوشتن باز میشود
|
||||
- تیتر (H2/H3)، بولد/ایتالیک/زیرخط، لیست نقطهای و شمارهای، نقلقول، لینک و واگرد
|
||||
- **درج تصویر داخل متن**: دکمه تصویر، یا چسباندن/کشیدن تصویر داخل نوشته — فایل مستقیم
|
||||
در MinIO ذخیره و در متن قرار میگیرد
|
||||
- راستبهچپ کامل با فونت و تم سایت
|
||||
- ذخیره خودکار: هر مکث کوتاه در تایپ، تغییرها را ذخیره میکند؛ بستن کشو هم ذخیره میکند
|
||||
|
||||
**پیشنویس و انتشار**: مقاله تازه همیشه **پیشنویس** شروع میشود — در سایت عمومی دیده
|
||||
نمیشود و تا انتشار، تغییرهای خودکار آن چیزی را خراب نمیکند. با دکمه «انتشار در سایت»
|
||||
عمومی میشود؛ دوباره میتوان آن را به پیشنویس برگرداند. پیشنویسها فقط برای ادمین
|
||||
(در صفحه وبلاگ، با برچسب «پیشنویس») دیده میشوند و در `GET /api/site` هرگز نمیآیند.
|
||||
|
||||
**فرمت ذخیره**: بدنه مقاله یک سند ساختاریافته TipTap (JSON) در PostgreSQL است — نه HTML خام.
|
||||
صفحه مقاله آن را با رندر استاتیک TipTap به HTML تبدیل میکند، پس فقط تگهای شناختهشده
|
||||
(پاراگراف، تیتر، لیست، نقلقول، تصویر، لینک) تولید میشوند. مقالات قدیمی (لیست پاراگراف)
|
||||
در اولین اجرا بهصورت خودکار به این فرمت تبدیل میشوند. در زمان ذخیره، آدرسهای
|
||||
`href/src` سند در سمت سرور پاکسازی میشوند (`app/sanitize.py`) تا اسکیمهای خطرناک
|
||||
مثل `javascript:` هرگز ذخیره نشوند.
|
||||
|
||||
## سئو
|
||||
|
||||
- **بررسی سئو در صفحه نوشتن**: فهرست سبز/نارنجی/قرمز به سبک یوست ولی سازگار با فارسی —
|
||||
طول عنوان، کلمه کلیدی هدف (در عنوان/پاراگراف اول/تیترها)، طول چکیده، تعداد واژه،
|
||||
تیتربندی H2، متن جایگزین تصاویر، پیوندها و نشانی (slug) — کلمه کلیدی هدف در دیتابیس
|
||||
ذخیره میشود (فیلد `seo_keyphrase` مقاله)
|
||||
- **سئوی هر صفحه**: در حالت ویرایش، دکمه سئو روی هیرو هر صفحه (و کنار هیرو صفحه اصلی) —
|
||||
عنوان تب و توضیح متای هر صفحه از دیتابیس خوانده و اعمال میشود؛ اگر ردیف سئوی صفحهای
|
||||
هنوز ساخته نشده باشد، دکمه + همانجا آن را میسازد
|
||||
- صفحه مقاله و پروژه بهطور خودکار عنوان و توضیح متا را از محتوای خودشان میگیرند
|
||||
- **تگهای OG و توییتر و canonical** برای همه صفحات از `src/seo.ts` ست میشود و
|
||||
مقالهها اسکیمای JSON-LD نوع Article میگیرند
|
||||
- **robots.txt و sitemap.xml** از بکاند سرو میشوند و مقاله/پروژههای منتشرشده را
|
||||
شامل میشوند (پیشنویسها نمیآیند) — برای آدرس مطلق، `SITE_URL` را در `.env` بگذارید
|
||||
- **متا برای خزندههای بدون جاوااسکریپت** (تلگرام، واتساپ و...): بکاند صفحات
|
||||
`/blog`، `/blog/{slug}`، `/projects` و `/projects/{slug}` را با همان `index.html`
|
||||
فرانتاند سرو میکند و پیش از ارسال، title / description / OG / JSON-LD را از
|
||||
دیتابیس داخل آن تزریق میکند (`app/seo_pages.py`) — بازدیدکنندههای عادی همان SPA
|
||||
همیشگی را میبینند
|
||||
|
||||
## پشتیبانگیری و بازگردانی
|
||||
|
||||
همه محتوای سایت در PostgreSQL و تصاویر در MinIO است:
|
||||
|
||||
```bash
|
||||
bash scripts/stack.sh backup # پشتیبان کامل: DB + تصاویر MinIO
|
||||
docker compose --profile ops up -d db-backup # پشتیبان ساعتی خودکار DB (بدون cron میزبان)
|
||||
```
|
||||
|
||||
- خروجی: `backups/db-<زمان>.sql.gz` (فشرده + فایل `.sha256`) و `backups/images-<زمان>/`
|
||||
- اسکریپت پشتیبان، خروجی خالی/شکسته را خطا میگیرد، سنجهٔ تازگی برای هشدار Grafana
|
||||
مینویسد و اگر `OFFSITE_RCLONE_REMOTE` در `.env` تنظیم باشد، پشتیبان را به حافظهٔ
|
||||
دیگری هم کپی میکند (rclone)
|
||||
- **بازگردانی**: `bash scripts/stack.sh restore backups/db-<زمان>.sql.gz`
|
||||
(احتیاط: محتوای فعلی جایگزین میشود — قبل از انتشار واقعی یکبار تمرین کنید!)
|
||||
- زمانبندی پشتیبان کامل با cron یا Task Scheduler: نمونه دستور داخل خود اسکریپت هست
|
||||
|
||||
## تست و CI
|
||||
|
||||
- `bash scripts/ci.sh` — تستهای pytest + بیلد ایمیجها + ممیزی وابستگیها
|
||||
- `bash scripts/audit.sh` — pip-audit / npm audit / trivy (هر کدام نصب بود)
|
||||
- `.github/workflows/ci.yml` — همین مراحل؛ سینتکس GitHub Actions روی Gitea Actions/
|
||||
Forgejo هم اجرا میشود
|
||||
|
||||
## نکات امنیتی
|
||||
|
||||
- فایل `.env` هرگز commit نمیشود (در `.gitignore` است)
|
||||
- رمز عبور ادمین با bcrypt هش میشود
|
||||
- توکنهای JWT امضا دارند و مدت اعتبارشان قابل تنظیم است
|
||||
- مقادیر محرمانه در `.env` ریشه هستند (در `.gitignore`) و در compose با سینتکس
|
||||
`${VAR:?}` اجباری شدهاند — بدون `.env` استک بالا نمیآید؛ هیچ رمز پیشفرضی در کد نیست
|
||||
- رمز عبور ادمین با bcrypt هش میشود و از نوار مدیریت پایین سایت (دکمه «رمز») قابل تعویض است
|
||||
- توکنهای JWT ۸ ساعت اعتبار دارند (stateless — تغییر `SECRET_KEY` همه را خارج میکند)
|
||||
- همهٔ کانتینرها **بدون root** اجرا میشوند؛ کانتکست بیلد هر ایمیج با `.dockerignore`
|
||||
باریک است و لاگها سقف دارند
|
||||
- فرمهای عمومی ضدرباتاند (honeypot + محدودسازی نرخ در بکاند + سقف سیلاب در Traefik)
|
||||
- کنسول MinIO و API مستقیمش در تولید فقط از `127.0.0.1` در دسترساند (تونل SSH)
|
||||
- تصاویر باکت MinIO عمومی (فقط خواندن) هستند؛ آپلود فقط با توکن ادمین ممکن است
|
||||
- مقالههای پیشنویس در هیچ انتهای عمومی نمیآیند و در HTML تزریقشده سئو هم افشا نمیشوند
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# کانتکست بیلد باریک — .venv و کشهای تست محلی جایی در تصویر ندارند
|
||||
.venv/
|
||||
venv/
|
||||
tests/
|
||||
.pytest_cache/
|
||||
__pycache__/
|
||||
**/__pycache__/
|
||||
*.pyc
|
||||
README.md
|
||||
.env
|
||||
.env.*
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
@@ -15,3 +15,15 @@ CORS_ORIGINS=["http://localhost:5173","http://127.0.0.1:5173"]
|
||||
# مشخصات ادمین پیشفرض که هنگام seed ساخته میشود
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=aramesh123
|
||||
|
||||
# Object Storage (MinIO) برای آپلود تصاویر پنل مدیریت
|
||||
S3_ENDPOINT=http://localhost:9000
|
||||
S3_ACCESS_KEY=aramesh
|
||||
S3_SECRET_KEY=change-me-minio-secret
|
||||
S3_BUCKET=aramesh-media
|
||||
|
||||
# پیشوند عمومی مسیر تصاویر — پروکسی Reverse باید آن را به باکت برساند
|
||||
MEDIA_PUBLIC_BASE=/media
|
||||
|
||||
# حداکثر حجم آپلود تصویر (مگابایت)
|
||||
MEDIA_MAX_UPLOAD_MB=10
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# بکاند FastAPI — تصویر باریک و بدون root
|
||||
FROM python:3.13-slim
|
||||
|
||||
WORKDIR /app
|
||||
@@ -8,9 +9,23 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# FFmpeg — نرمالسازی رسانه به WebP برای ورودیهایی که Pillow نمیخواند
|
||||
# (ویدیو → WebP متحرک، فرمتهای تصویری خاص). مسیر Pillow به آن وابسته نیست.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ffmpeg \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY app ./app
|
||||
COPY alembic.ini ./
|
||||
COPY migrations ./migrations
|
||||
|
||||
# کاربر بدون دسترسی root — برنامه چیزی روی دیسک محلی نمینویسد
|
||||
RUN useradd --system --create-home appuser \
|
||||
&& chown -R appuser:appuser /app
|
||||
USER appuser
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
# ساخت جداول و seed (بدون حذف دادههای موجود) و سپس اجرای سرور
|
||||
CMD ["sh", "-c", "python -m app.seed && uvicorn app.main:app --host 0.0.0.0 --port 8000"]
|
||||
# ساخت جداول پایه، مهاجرتهای Alembic و seed (بدون حذف دادههای موجود) و سپس
|
||||
# اجرای سرور با exec — تا SIGTERM (docker stop) مستقیم به uvicorn برسد و خاموشی
|
||||
# تمیز انجام شود؛ --proxy-headers برای دیدن IP واقعی کلاینت پشت Traefik
|
||||
CMD ["sh", "-c", "python -m app.db_init && alembic upgrade head && python -m app.seed && exec uvicorn app.main:app --host 0.0.0.0 --port 8000 --proxy-headers --forwarded-allow-ips='*'"]
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
# بکاند گروه ساختمانی آرامش (Aramesh Building Group API)
|
||||
|
||||
بکاند سایت گروه ساختمانی آرامش — ساختهشده با **FastAPI** + **PostgreSQL** + **SQLAlchemy 2** + **JWT**.
|
||||
بکاند سایت گروه ساختمانی آرامش — ساختهشده با **FastAPI** + **PostgreSQL** + **SQLAlchemy 2** + **JWT** + **MinIO** (ذخیره تصاویر) + **Traefik** (مسیریابی).
|
||||
|
||||
## امکانات
|
||||
|
||||
- **API عمومی محتوا**: برند، خدمات، پروژهها، مقالات، نظرات مشتریان، سوالات متداول، تیم، تایملاین، آمار، چرا آرامش، و بخش قبل/بعد
|
||||
- **API عمومی محتوا**: برند، منو، هیرو، داستان، تیتر بخشها، هیرو صفحات، خدمات، پروژهها، مقالات، نظرات مشتریان، سوالات متداول، تیم، تایملاین، آمار، چرا آرامش، قبل/بعد، مدلهای سرمایهگذاری، مراحل کار، دفاتر، گالری، فرم تماس، خبرنامه و فوتر — **تمام متنهای سایت در دیتابیس است**
|
||||
- **فرم تماس**: ثبت پیام مشتریان از سایت (`POST /api/contact`)
|
||||
- **خبرنامه**: عضویت و مدیریت مشترکین (`POST /api/newsletter`)
|
||||
- **پنل مدیریت**: ورود با نام کاربری/رمز عبور و دریافت توکن JWT، سپس CRUD کامل همه محتواها، مدیریت پیامهای تماس و مشترکین
|
||||
- **Seed خودکار**: همه محتوای فعلی سایت با یک دستور در دیتابیس قرار میگیرد
|
||||
- **آپلود تصویر**: `POST /api/admin/upload` — فایل در MinIO ذخیره و URL نسبی `/media/...` برمیگردد
|
||||
- **Seed خودکار**: همه محتوای فعلی سایت با یک دستور در دیتابیس قرار میگیرد (فقط جدولهای خالی پر میشوند — ارتقا بدون از دست رفتن داده)
|
||||
- مستندات تعاملی Swagger در مسیر `/docs`
|
||||
|
||||
## راهاندازی
|
||||
@@ -85,6 +86,13 @@ Authorization: Bearer <access_token>
|
||||
|
||||
> نام کاربری و رمز عبور پیشفرض از تنظیمات `.env` خوانده میشود — حتماً در محیط تولید تغییرشان دهید.
|
||||
|
||||
تغییر رمز (با توکن):
|
||||
|
||||
```
|
||||
POST /api/auth/change-password
|
||||
{ "current_password": "...", "new_password": "..." }
|
||||
```
|
||||
|
||||
## فهرست انتهاپوینتها
|
||||
|
||||
### عمومی (بدون نیاز به توکن)
|
||||
@@ -96,8 +104,8 @@ Authorization: Bearer <access_token>
|
||||
| GET | `/api/services` | خدمات |
|
||||
| GET | `/api/projects` | همه پروژهها |
|
||||
| GET | `/api/projects/{slug}` | جزئیات یک پروژه |
|
||||
| GET | `/api/articles` | همه مقالات |
|
||||
| GET | `/api/articles/{slug}` | جزئیات یک مقاله |
|
||||
| GET | `/api/articles` | مقالههای منتشرشده (پیشنویس نمیآید) |
|
||||
| GET | `/api/articles/{slug}` | جزئیات یک مقاله منتشرشده |
|
||||
| GET | `/api/testimonials` | نظرات مشتریان |
|
||||
| GET | `/api/faqs` | سوالات متداول |
|
||||
| GET | `/api/team` | اعضای تیم |
|
||||
@@ -108,7 +116,11 @@ Authorization: Bearer <access_token>
|
||||
| GET | `/api/site` | **همه محتوا در یک درخواست** |
|
||||
| POST | `/api/contact` | ثبت پیام تماس |
|
||||
| POST | `/api/newsletter` | عضویت در خبرنامه |
|
||||
| POST | `/api/auth/login` | ورود ادمین و دریافت توکن |
|
||||
| POST | `/api/auth/login` | ورود ادمین و دریافت توکن — بعد از ۵ تلاش ناموفق در ۱۵ دقیقه، 429 |
|
||||
| GET | `/robots.txt` | قوانین خزندهها |
|
||||
| GET | `/sitemap.xml` | نقشه سایت — مقاله/پروژههای منتشرشده |
|
||||
| GET | `/blog/{slug}` | HTML صفحه مقاله با متای سئوی تزریقشده |
|
||||
| GET | `/projects/{slug}` | HTML صفحه پروژه با متای سئوی تزریقشده |
|
||||
|
||||
### مدیریت (نیاز به توکن Bearer)
|
||||
|
||||
@@ -118,12 +130,35 @@ Authorization: Bearer <access_token>
|
||||
| متد | مسیر | توضیح |
|
||||
|---|---|---|
|
||||
| GET/POST | `/api/admin/{resource}` | لیست / ساخت |
|
||||
| GET/PUT/DELETE | `/api/admin/{resource}/{id}` | دریافت / ویرایش / حذف |
|
||||
| GET/PUT/DELETE | `/api/admin/{resource}/{id}` | دریافت / ویرایش کامل / حذف |
|
||||
| PATCH | `/api/admin/{resource}/{id}` | **ویرایش جزئی** — فقط فیلدهای ارسالشده بهروزرسانی میشوند |
|
||||
| POST | `/api/admin/{resource}/reorder` | ذخیره ترتیب: `{"ids": [3, 1, 2, ...]}` |
|
||||
| GET | `/api/admin/messages` | پیامهای تماس (با `?unread_only=true` فقط خواندهنشدهها) |
|
||||
| PATCH | `/api/admin/messages/{id}` | تغییر وضعیت خواندهشدن |
|
||||
| DELETE | `/api/admin/messages/{id}` | حذف پیام |
|
||||
| GET | `/api/admin/subscribers` | مشترکین خبرنامه |
|
||||
| DELETE | `/api/admin/subscribers/{id}` | حذف مشترک |
|
||||
| POST | `/api/admin/upload` | آپلود تصویر (multipart، حداکثر ۱۰MB — jpg/png/webp/gif/avif) → `{"url": "/media/..."}` |
|
||||
|
||||
### بدنه مقاله — سند TipTap
|
||||
|
||||
`body` مقاله یک سند ساختاریافته TipTap (ProseMirror JSON) است: `{"type": "doc", "content": [...]}`.
|
||||
- فقط ساختار اعتبارسنجی میشود (`type: "doc"` + `content` لیست)؛ امنیت رندر بر عهده
|
||||
رندر استاتیک TipTap در فرانتاند است که فقط تگهای شناختهشده تولید میکند
|
||||
- ردیفهای قدیمی (لیست پاراگراف) با مهاجرت idempotent `migrate_article_bodies`
|
||||
در startup/seed خودکار به سند تبدیل میشوند
|
||||
- seed هم بدنههای لیستی را قبل از درج تبدیل میکند
|
||||
|
||||
| POST/PATCH | `/api/admin/seo-meta` | عنوان و توضیح متای صفحات — `page_key`: home / about / services / projects / investment / blog / faq / contact |
|
||||
|
||||
منابعی که `reorder` دارند (ستون `position`): `services`، `projects`، `articles`، `testimonials`، `faqs`، `team`، `timeline`، `stats`، `why-us`، `investment-models`، `process-steps`، `offices`، `gallery`، `nav`. ستون با مهاجرت سبک idempotent هنگام startup/seed به دیتابیسهای موجود اضافه میشود.
|
||||
|
||||
### تصاویر و MinIO
|
||||
|
||||
فایلهای آپلودشده در باکت `aramesh-media` روی MinIO ذخیره میشوند و با مسیر نسبی `/media/<سال>/<ماه>/<فایل>` برگردانده میشوند. Traefik مسیر `/media` را به MinIO میبرد، پس URLها مستقل از بکاند ذخیرهسازی هستند — بعداً برای مهاجرت به R2/S3 فقط تنظیمات را عوض کنید، نه محتوای دیتابیس را.
|
||||
|
||||
- کنسول MinIO: `http://localhost:9001` (کاربر/رمز از `MINIO_ROOT_USER` / `MINIO_ROOT_PASSWORD` در compose)
|
||||
- تصاویر عمومی و قابل نمایشاند؛ آپلود فقط با توکن ادمین انجام میشود.
|
||||
|
||||
## اتصال به فرانتاند
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
[alembic]
|
||||
script_location = migrations
|
||||
prepend_sys_path = .
|
||||
|
||||
# آدرس دیتابیس از DATABASE_URL (محیط) یا تنظیمات برنامه خوانده میشود — env.py
|
||||
sqlalchemy.url =
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -1,70 +1,226 @@
|
||||
"""انتهای پنل مدیریت — همه مسیرها نیازمند توکن JWT معتبر هستند."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
import csv
|
||||
import ipaddress
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import tempfile
|
||||
import urllib.request
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import boto3
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, Response, UploadFile, status
|
||||
from PIL import Image, ImageOps
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from .. import models, schemas
|
||||
from ..auth import create_access_token, get_current_admin, verify_password
|
||||
from ..auth import create_access_token, get_current_admin, get_user_from_token, hash_password, oauth2_scheme, verify_password
|
||||
from ..config import settings
|
||||
from ..database import get_db
|
||||
from ..rate_limit import clear as clear_rate_limit
|
||||
from ..rate_limit import ensure_allowed, record_failure
|
||||
from ..schemas import (
|
||||
ArticleIn,
|
||||
ArticleOut,
|
||||
ArticlePatch,
|
||||
BeforeAfterIn,
|
||||
BeforeAfterOut,
|
||||
BeforeAfterPatch,
|
||||
BrandIn,
|
||||
BrandOut,
|
||||
BrandPatch,
|
||||
ChangePasswordIn,
|
||||
ContactSectionIn,
|
||||
ContactSectionOut,
|
||||
ContactSectionPatch,
|
||||
ContactMessageOut,
|
||||
FaqIn,
|
||||
FaqOut,
|
||||
FaqPatch,
|
||||
FooterIn,
|
||||
FooterOut,
|
||||
FooterPatch,
|
||||
GalleryImageIn,
|
||||
GalleryImageOut,
|
||||
GalleryImagePatch,
|
||||
HeroIn,
|
||||
HeroOut,
|
||||
HeroPatch,
|
||||
InvestmentModelIn,
|
||||
InvestmentModelOut,
|
||||
InvestmentModelPatch,
|
||||
LoginIn,
|
||||
MessageReadIn,
|
||||
NavItemIn,
|
||||
NavItemOut,
|
||||
NavItemPatch,
|
||||
NewsletterSectionIn,
|
||||
NewsletterOut,
|
||||
NewsletterSectionPatch,
|
||||
OfficeIn,
|
||||
OfficeOut,
|
||||
OfficePatch,
|
||||
PageHeroIn,
|
||||
PageHeroOut,
|
||||
PageHeroPatch,
|
||||
ProcessStepIn,
|
||||
ProcessStepOut,
|
||||
ProcessStepPatch,
|
||||
ProjectIn,
|
||||
ProjectOut,
|
||||
ProjectPatch,
|
||||
ReorderIn,
|
||||
SeoMetaIn,
|
||||
SeoMetaOut,
|
||||
SeoMetaPatch,
|
||||
SectionHeadingIn,
|
||||
SectionHeadingOut,
|
||||
SectionHeadingPatch,
|
||||
ServiceIn,
|
||||
ServiceOut,
|
||||
ServicePatch,
|
||||
StatIn,
|
||||
StatOut,
|
||||
StatPatch,
|
||||
StatusLabelIn,
|
||||
StatusLabelOut,
|
||||
StatusLabelPatch,
|
||||
StoryIn,
|
||||
StoryOut,
|
||||
StoryPatch,
|
||||
SubscriberOut,
|
||||
TeamMemberIn,
|
||||
TeamMemberOut,
|
||||
TeamMemberPatch,
|
||||
TestimonialIn,
|
||||
TestimonialOut,
|
||||
TestimonialPatch,
|
||||
TimelineItemIn,
|
||||
TimelineItemOut,
|
||||
TimelineItemPatch,
|
||||
TokenOut,
|
||||
WhyUsItemIn,
|
||||
WhyUsItemOut,
|
||||
WhyUsItemPatch,
|
||||
)
|
||||
|
||||
# روتر عمومی برای ورود — بدون نیاز به توکن
|
||||
auth_router = APIRouter()
|
||||
|
||||
# روتر محافظتشده — همه مسیرهای آن فقط با توکن معتبر قابل دسترسی هستند
|
||||
router = APIRouter(dependencies=[Depends(get_current_admin)])
|
||||
async def admin_access_guard(
|
||||
request: Request,
|
||||
token: str = Depends(oauth2_scheme),
|
||||
db: Session = Depends(get_db),
|
||||
) -> models.AdminUser:
|
||||
"""نقشگارد — 'admin' همهکاره؛ 'creator' فقط مقالهنویسی: ساخت پیشنویس،
|
||||
خواندن/ویرایش پیشنویس خودش، و آپلود تصویر. بقیهٔ مسیرهای مدیریتی ۴۰۳."""
|
||||
user = get_user_from_token(token, db)
|
||||
if user.role == "admin":
|
||||
return user
|
||||
if user.role != "creator":
|
||||
raise HTTPException(status_code=403, detail="نقش ناشناخته")
|
||||
|
||||
path = request.url.path.rstrip("/")
|
||||
method = request.method
|
||||
|
||||
# آپلود تصویر مقالهها — مجاز
|
||||
if path in ("/api/admin/upload", "/api/admin/import-image") and method == "POST":
|
||||
return user
|
||||
# فهرست و ساخت مقاله — مجاز (ساخت همیشه پیشنویس است و نویسندهاش ثبت میشود)
|
||||
if path == "/api/admin/articles" and method in ("GET", "POST"):
|
||||
return user
|
||||
# خواندن/ویرایش پیشنویس خودِ نویسنده — مالکیت در هندلر هم دوباره چک میشود
|
||||
m = re.fullmatch(r"/api/admin/articles/(\d+)", path)
|
||||
if m and method in ("GET", "PUT", "PATCH"):
|
||||
article = db.get(models.Article, int(m.group(1)))
|
||||
if article is not None and article.author_id == user.id:
|
||||
return user
|
||||
# ۴۰۴ نه ۴۰۳ — مقالههای بقیه برای نویسنده اصلاً وجود ندارند
|
||||
raise HTTPException(status_code=404, detail="مقاله یافت نشد")
|
||||
raise HTTPException(status_code=403, detail="دسترسی نویسنده محدود است")
|
||||
|
||||
|
||||
router = APIRouter(
|
||||
dependencies=[
|
||||
Depends(get_current_admin),
|
||||
Depends(admin_access_guard),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
|
||||
@auth_router.post("/auth/login", response_model=TokenOut)
|
||||
def login(payload: LoginIn, db: Session = Depends(get_db)):
|
||||
def login(payload: LoginIn, request: Request, db: Session = Depends(get_db)):
|
||||
ensure_allowed(request)
|
||||
user = db.query(models.AdminUser).filter(models.AdminUser.username == payload.username).first()
|
||||
if user is None or not verify_password(payload.password, user.password_hash):
|
||||
record_failure(request)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="نام کاربری یا رمز عبور اشتباه است",
|
||||
)
|
||||
return TokenOut(access_token=create_access_token(user.username))
|
||||
clear_rate_limit(request)
|
||||
return TokenOut(access_token=create_access_token(user.username, user.role), role=user.role)
|
||||
|
||||
|
||||
def register_crud(path: str, model, out_schema, create_schema) -> None:
|
||||
"""ثبت پنج مسیر CRUD استاندارد (لیست، ساخت، دریافت، ویرایش، حذف) روی روتر مدیریت."""
|
||||
@auth_router.post("/auth/change-password")
|
||||
def change_password(
|
||||
payload: ChangePasswordIn,
|
||||
admin: models.AdminUser = Depends(get_current_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""تغییر رمز ادمین واردشده — رمز فعلی باید درست باشد."""
|
||||
if not verify_password(payload.current_password, admin.password_hash):
|
||||
raise HTTPException(status_code=400, detail="رمز عبور فعلی اشتباه است")
|
||||
admin.password_hash = hash_password(payload.new_password)
|
||||
db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
def register_crud(
|
||||
path: str, model, out_schema, create_schema, patch_schema=None,
|
||||
creator_scoped: bool = False,
|
||||
) -> None:
|
||||
"""ثبت مسیرهای استاندارد CRUD (لیست، ساخت، دریافت، ویرایش کامل، ویرایش جزئی،
|
||||
حذف و ترتیببندی) روی روتر مدیریت.
|
||||
|
||||
creator_scoped=True (فقط مقالهها): نقش creator فقط رکوردهای خودش را میبیند،
|
||||
ساختش همیشه پیشنویس است و ویرایشش هرگز منتشر نمیشود."""
|
||||
|
||||
@router.get(f"/{path}", response_model=list[out_schema])
|
||||
def list_items(db: Session = Depends(get_db)):
|
||||
return db.query(model).order_by(model.id).all()
|
||||
def list_items(db: Session = Depends(get_db), admin: models.AdminUser = Depends(get_current_admin)):
|
||||
query = db.query(model)
|
||||
if creator_scoped and admin.role == "creator":
|
||||
query = query.filter(model.author_id == admin.id)
|
||||
if hasattr(model, "position"):
|
||||
query = query.order_by(model.position, model.id)
|
||||
else:
|
||||
query = query.order_by(model.id)
|
||||
return query.all()
|
||||
|
||||
@router.post(f"/{path}", response_model=out_schema, status_code=201)
|
||||
def create_item(payload: create_schema, db: Session = Depends(get_db)):
|
||||
def create_item(payload: create_schema, db: Session = Depends(get_db), admin: models.AdminUser = Depends(get_current_admin)):
|
||||
item = model(**payload.model_dump())
|
||||
if creator_scoped:
|
||||
# نویسنده ثبت میشود؛ ساخت توسط creator همیشه پیشنویس است
|
||||
item.author_id = admin.id
|
||||
if admin.role == "creator":
|
||||
item.status = "draft"
|
||||
if hasattr(model, "position"):
|
||||
# آیتم جدید در انتهای لیست قرار میگیرد
|
||||
item.position = (db.query(func.max(model.position)).scalar() or 0) + 1
|
||||
db.add(item)
|
||||
try:
|
||||
db.commit()
|
||||
@@ -75,19 +231,26 @@ def register_crud(path: str, model, out_schema, create_schema) -> None:
|
||||
return item
|
||||
|
||||
@router.get(f"/{path}/{{item_id}}", response_model=out_schema)
|
||||
def get_item(item_id: int, db: Session = Depends(get_db)):
|
||||
def get_item(item_id: int, db: Session = Depends(get_db), admin: models.AdminUser = Depends(get_current_admin)):
|
||||
item = db.get(model, item_id)
|
||||
if item is None:
|
||||
raise HTTPException(status_code=404, detail="رکورد یافت نشد")
|
||||
if creator_scoped and admin.role == "creator" and item.author_id != admin.id:
|
||||
# مقالهٔ بقیه برای creator وجود ندارد
|
||||
raise HTTPException(status_code=404, detail="مقاله یافت نشد")
|
||||
return item
|
||||
|
||||
@router.put(f"/{path}/{{item_id}}", response_model=out_schema)
|
||||
def update_item(item_id: int, payload: create_schema, db: Session = Depends(get_db)):
|
||||
def update_item(item_id: int, payload: create_schema, db: Session = Depends(get_db), admin: models.AdminUser = Depends(get_current_admin)):
|
||||
item = db.get(model, item_id)
|
||||
if item is None:
|
||||
raise HTTPException(status_code=404, detail="رکورد یافت نشد")
|
||||
if creator_scoped and admin.role == "creator" and item.author_id != admin.id:
|
||||
raise HTTPException(status_code=404, detail="مقاله یافت نشد")
|
||||
for key, value in payload.model_dump().items():
|
||||
setattr(item, key, value)
|
||||
if creator_scoped and admin.role == "creator":
|
||||
item.status = "draft" # نویسنده حق انتشار ندارد
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
@@ -96,8 +259,48 @@ def register_crud(path: str, model, out_schema, create_schema) -> None:
|
||||
db.refresh(item)
|
||||
return item
|
||||
|
||||
if patch_schema is not None:
|
||||
|
||||
@router.patch(f"/{path}/{{item_id}}", response_model=out_schema)
|
||||
def patch_item(item_id: int, payload: patch_schema, db: Session = Depends(get_db), admin: models.AdminUser = Depends(get_current_admin)):
|
||||
"""ویرایش جزئی — فقط فیلدهای ارسالشده بهروزرسانی میشوند (برای ویرایش زنده)."""
|
||||
item = db.get(model, item_id)
|
||||
if item is None:
|
||||
raise HTTPException(status_code=404, detail="رکورد یافت نشد")
|
||||
if creator_scoped and admin.role == "creator" and item.author_id != admin.id:
|
||||
raise HTTPException(status_code=404, detail="مقاله یافت نشد")
|
||||
for key, value in payload.model_dump(exclude_unset=True).items():
|
||||
setattr(item, key, value)
|
||||
if creator_scoped and admin.role == "creator":
|
||||
item.status = "draft" # نویسنده حق انتشار ندارد
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(status_code=409, detail="رکوردی با این مقدار تکراری وجود دارد (مثلاً slug یا ایمیل)")
|
||||
db.refresh(item)
|
||||
return item
|
||||
|
||||
@router.post(f"/{path}/reorder", response_model=list[out_schema])
|
||||
def reorder_items(payload: ReorderIn, db: Session = Depends(get_db), admin: models.AdminUser = Depends(get_current_admin)):
|
||||
if creator_scoped and admin.role == "creator":
|
||||
raise HTTPException(status_code=403, detail="ترتیب مقالهها فقط توسط مدیر تغییر میکند")
|
||||
"""ذخیره ترتیب جدید آیتمها بر اساس لیست idهای ارسالی."""
|
||||
if not hasattr(model, "position"):
|
||||
raise HTTPException(status_code=400, detail="این منبع از ترتیببندی پشتیبانی نمیکند")
|
||||
items = db.query(model).filter(model.id.in_(payload.ids)).all()
|
||||
if len(items) != len(payload.ids):
|
||||
raise HTTPException(status_code=404, detail="برخی رکوردها یافت نشدند")
|
||||
by_id = {item.id: item for item in items}
|
||||
for pos, item_id in enumerate(payload.ids):
|
||||
by_id[item_id].position = pos
|
||||
db.commit()
|
||||
return db.query(model).order_by(model.position, model.id).all()
|
||||
|
||||
@router.delete(f"/{path}/{{item_id}}", status_code=204)
|
||||
def delete_item(item_id: int, db: Session = Depends(get_db)):
|
||||
def delete_item(item_id: int, db: Session = Depends(get_db), admin: models.AdminUser = Depends(get_current_admin)):
|
||||
if creator_scoped and admin.role == "creator":
|
||||
raise HTTPException(status_code=403, detail="حذف مقاله فقط توسط مدیر انجام میشود")
|
||||
item = db.get(model, item_id)
|
||||
if item is None:
|
||||
raise HTTPException(status_code=404, detail="رکورد یافت نشد")
|
||||
@@ -106,17 +309,300 @@ def register_crud(path: str, model, out_schema, create_schema) -> None:
|
||||
|
||||
|
||||
# CRUD محتوا
|
||||
register_crud("brand", models.Brand, BrandOut, BrandIn)
|
||||
register_crud("services", models.Service, ServiceOut, ServiceIn)
|
||||
register_crud("projects", models.Project, ProjectOut, ProjectIn)
|
||||
register_crud("articles", models.Article, ArticleOut, ArticleIn)
|
||||
register_crud("testimonials", models.Testimonial, TestimonialOut, TestimonialIn)
|
||||
register_crud("faqs", models.Faq, FaqOut, FaqIn)
|
||||
register_crud("team", models.TeamMember, TeamMemberOut, TeamMemberIn)
|
||||
register_crud("timeline", models.TimelineItem, TimelineItemOut, TimelineItemIn)
|
||||
register_crud("stats", models.Stat, StatOut, StatIn)
|
||||
register_crud("why-us", models.WhyUsItem, WhyUsItemOut, WhyUsItemIn)
|
||||
register_crud("before-after", models.BeforeAfter, BeforeAfterOut, BeforeAfterIn)
|
||||
register_crud("brand", models.Brand, BrandOut, BrandIn, BrandPatch)
|
||||
register_crud("nav", models.NavItem, NavItemOut, NavItemIn, NavItemPatch)
|
||||
register_crud("hero", models.Hero, HeroOut, HeroIn, HeroPatch)
|
||||
register_crud("story", models.StorySection, StoryOut, StoryIn, StoryPatch)
|
||||
register_crud("section-headings", models.SectionHeadingContent, SectionHeadingOut, SectionHeadingIn, SectionHeadingPatch)
|
||||
register_crud("page-heroes", models.PageHeroContent, PageHeroOut, PageHeroIn, PageHeroPatch)
|
||||
register_crud("services", models.Service, ServiceOut, ServiceIn, ServicePatch)
|
||||
register_crud("projects", models.Project, ProjectOut, ProjectIn, ProjectPatch)
|
||||
register_crud("articles", models.Article, ArticleOut, ArticleIn, ArticlePatch, creator_scoped=True)
|
||||
register_crud("testimonials", models.Testimonial, TestimonialOut, TestimonialIn, TestimonialPatch)
|
||||
register_crud("faqs", models.Faq, FaqOut, FaqIn, FaqPatch)
|
||||
register_crud("team", models.TeamMember, TeamMemberOut, TeamMemberIn, TeamMemberPatch)
|
||||
register_crud("timeline", models.TimelineItem, TimelineItemOut, TimelineItemIn, TimelineItemPatch)
|
||||
register_crud("stats", models.Stat, StatOut, StatIn, StatPatch)
|
||||
register_crud("why-us", models.WhyUsItem, WhyUsItemOut, WhyUsItemIn, WhyUsItemPatch)
|
||||
register_crud("before-after", models.BeforeAfter, BeforeAfterOut, BeforeAfterIn, BeforeAfterPatch)
|
||||
register_crud("investment-models", models.InvestmentModel, InvestmentModelOut, InvestmentModelIn, InvestmentModelPatch)
|
||||
register_crud("process-steps", models.ProcessStep, ProcessStepOut, ProcessStepIn, ProcessStepPatch)
|
||||
register_crud("offices", models.Office, OfficeOut, OfficeIn, OfficePatch)
|
||||
register_crud("gallery", models.GalleryImage, GalleryImageOut, GalleryImageIn, GalleryImagePatch)
|
||||
register_crud("status-labels", models.StatusLabel, StatusLabelOut, StatusLabelIn, StatusLabelPatch)
|
||||
register_crud("contact-section", models.ContactSectionContent, ContactSectionOut, ContactSectionIn, ContactSectionPatch)
|
||||
register_crud("newsletter", models.NewsletterSectionContent, NewsletterOut, NewsletterSectionIn, NewsletterSectionPatch)
|
||||
register_crud("footer", models.FooterContent, FooterOut, FooterIn, FooterPatch)
|
||||
register_crud("seo-meta", models.SeoMeta, SeoMetaOut, SeoMetaIn, SeoMetaPatch)
|
||||
|
||||
|
||||
# رسانه آپلودی به Object Storage (MinIO) — هر ورودی قابلرمزگشایی به WebP «تکفریمی» نرمال میشود:
|
||||
# هیچ آپلودی هرگز متحرک ذخیره نمیشود — منبع متحرک (gif/apng/webp متحرک/ویدیو) از فریم اول
|
||||
# پوستر میگیرد؛ انیمیشن در کارتها و اسلایدرها سوسو میزند و مطلوب نیست.
|
||||
# URL نسبی برمیگردد تا بکاند ذخیرهسازی قابل تعویض باشد.
|
||||
MAX_DIMENSION = 2000 # سقف ضلع تصویر — ابعاد بزرگ اصلیترین عامل کندی سایت است
|
||||
WEBP_QUALITY = 82
|
||||
WEBP_CONTENT_TYPE = "image/webp"
|
||||
|
||||
SUPPORTED_MEDIA_DETAIL = "فرمت پشتیبانی نمیشود — فقط تصویر یا ویدیویی که بتوان به WebP تبدیل کرد مجاز است"
|
||||
|
||||
|
||||
def _to_webp_mode(img: Image.Image) -> Image.Image:
|
||||
"""ذخیرهٔ WebP در Pillow فقط RGB/RGBA/L را میپذیرد — مدهای دیگر با حفظ شفافیت تبدیل میشوند."""
|
||||
if img.mode in ("RGB", "RGBA", "L"):
|
||||
return img
|
||||
has_alpha = img.mode in ("LA", "PA") or (img.mode == "P" and "transparency" in img.info)
|
||||
return img.convert("RGBA" if has_alpha else "RGB")
|
||||
|
||||
|
||||
def _webp_still(img: Image.Image) -> tuple[bytes, int, int]:
|
||||
"""فریم اول → WebP تکفریمی؛ چرخش EXIF اعمال، متادیتا حذف و سقف ضلع ۲۰۰۰ پیکسل رعایت میشود."""
|
||||
if getattr(img, "n_frames", 1) > 1:
|
||||
img.seek(0)
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if max(img.size) > MAX_DIMENSION:
|
||||
img.thumbnail((MAX_DIMENSION, MAX_DIMENSION), Image.LANCZOS)
|
||||
img = _to_webp_mode(img)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, "WEBP", quality=WEBP_QUALITY, method=4)
|
||||
return buf.getvalue(), *img.size
|
||||
|
||||
|
||||
def _ffprobe_video(path: str) -> dict | None:
|
||||
"""استریم ویدیوی اول با ffprobe — None یعنی ویدیویی در فایل نیست (رسانهٔ تصویری نیست)."""
|
||||
ffprobe = shutil.which("ffprobe")
|
||||
if ffprobe is None:
|
||||
return None
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[ffprobe, "-v", "error", "-print_format", "json", "-show_streams", path],
|
||||
capture_output=True, timeout=20,
|
||||
)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
return None
|
||||
if proc.returncode != 0:
|
||||
return None
|
||||
try:
|
||||
streams = json.loads(proc.stdout or "{}").get("streams") or []
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return next((s for s in streams if s.get("codec_type") == "video"), None)
|
||||
|
||||
|
||||
def _run_ffmpeg(args: list[str]) -> None:
|
||||
try:
|
||||
proc = subprocess.run(args, capture_output=True, timeout=60)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise HTTPException(status_code=415, detail="تبدیل رسانه بیش از حد طول کشید") from exc
|
||||
except OSError as exc:
|
||||
raise HTTPException(status_code=415, detail=SUPPORTED_MEDIA_DETAIL) from exc
|
||||
if proc.returncode != 0:
|
||||
raise HTTPException(status_code=415, detail=SUPPORTED_MEDIA_DETAIL)
|
||||
|
||||
|
||||
def _ffmpeg_webp(data: bytes) -> tuple[bytes, int | None, int | None]:
|
||||
"""مسیر FFmpeg — ورودیهایی که Pillow نمیخواند: ویدیو و فرمتهای تصویری خاص.
|
||||
خروجی همیشه تکفریم (پوستر) است — ویدیوی متحرک در صفحه لوپ میشود و سوسو میزند."""
|
||||
if shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None:
|
||||
raise HTTPException(status_code=415, detail=SUPPORTED_MEDIA_DETAIL)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = os.path.join(tmp, "src")
|
||||
dst = os.path.join(tmp, "out.webp")
|
||||
with open(src, "wb") as fh:
|
||||
fh.write(data)
|
||||
if _ffprobe_video(src) is None:
|
||||
raise HTTPException(status_code=415, detail=SUPPORTED_MEDIA_DETAIL)
|
||||
ff = shutil.which("ffmpeg") or "ffmpeg"
|
||||
_run_ffmpeg([ff, "-y", "-v", "error", "-i", src, "-frames:v", "1",
|
||||
"-vf", f"scale='min({MAX_DIMENSION},iw)':-2:flags=lanczos",
|
||||
"-c:v", "libwebp", "-q:v", str(WEBP_QUALITY), "-map_metadata", "-1", dst])
|
||||
with open(dst, "rb") as fh:
|
||||
out = fh.read()
|
||||
# ffprobe روی WebP عرض/ارتفاع صفر برمیگرداند — ابعاد از خود خروجی با Pillow
|
||||
try:
|
||||
width, height = Image.open(io.BytesIO(out)).size
|
||||
except Exception:
|
||||
width = height = None
|
||||
return out, width, height
|
||||
|
||||
|
||||
def _normalize_media(data: bytes) -> tuple[bytes, int | None, int | None]:
|
||||
"""هر ورودی قابلرمزگشایی → WebP تکفریمی. اول Pillow (دقیقترین برای EXIF/شفافیت)؛
|
||||
اگر رمزگشایی نشد، FFmpeg (پوستر ویدیو و فرمتهای خاص). هیچکدام نشد → ۴۱۵."""
|
||||
try:
|
||||
return _webp_still(Image.open(io.BytesIO(data)))
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
return _ffmpeg_webp(data)
|
||||
|
||||
|
||||
def _readable_key(name: str, ext: str) -> str:
|
||||
"""کلید ذخیرهسازی خوانا از نام دلخواه/نام فایل — «۱۴۰۳/elahieh-tower-a1b2c3.jpg».
|
||||
|
||||
نامگذاریها ایمن میشوند: نویسههای ناامن و جداکننده مسیر حذف، فاصلهها خط تیره،
|
||||
طول محدود؛ خالی بودن نام → شناسه تصادفی مثل قبل. پسوند ۶ نویسهای تضمین یکتایی است.
|
||||
"""
|
||||
slug = re.sub(r"[^\w-ۿ\- ]+", "", name, flags=re.UNICODE).strip()
|
||||
slug = re.sub(r"[\s_]+", "-", slug).strip("-")[:80]
|
||||
unique = uuid.uuid4().hex[:6]
|
||||
base = f"{slug}-{unique}" if slug else uuid.uuid4().hex
|
||||
return f"{datetime.now(timezone.utc):%Y/%m}/{base}.{ext}"
|
||||
|
||||
|
||||
def _store_image(data: bytes, name: str) -> str:
|
||||
"""ذخیرهٔ WebP در Object Storage با کلید خوانا — URL نسبی برمیگردد."""
|
||||
key = _readable_key(name, "webp")
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=settings.s3_endpoint,
|
||||
aws_access_key_id=settings.s3_access_key,
|
||||
aws_secret_access_key=settings.s3_secret_key,
|
||||
region_name="us-east-1",
|
||||
)
|
||||
try:
|
||||
s3.put_object(Bucket=settings.s3_bucket, Key=key, Body=data, ContentType=WEBP_CONTENT_TYPE)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=502, detail="ذخیره فایل در Object Storage ناموفق بود")
|
||||
return f"{settings.media_public_base}/{key}"
|
||||
|
||||
|
||||
@router.post("/upload")
|
||||
async def upload_media(
|
||||
file: UploadFile = File(...),
|
||||
name: str = Form(""),
|
||||
_admin: models.AdminUser = Depends(get_current_admin),
|
||||
):
|
||||
max_bytes = settings.media_max_upload_mb * 1024 * 1024
|
||||
data = await file.read()
|
||||
if len(data) == 0:
|
||||
raise HTTPException(status_code=400, detail="فایل خالی است")
|
||||
if len(data) > max_bytes:
|
||||
raise HTTPException(
|
||||
status_code=413,
|
||||
detail=f"حجم فایل بیش از {settings.media_max_upload_mb} مگابایت است",
|
||||
)
|
||||
|
||||
# هر ورودی قابلرمزگشایی (تصویر رایج/خاص، متحرک، ویدیو) → WebP نرمال — روی ترد،
|
||||
# تا رمزگذاری فایل حجیم رویدادلوپ و بقیهٔ درخواستها را قفل نکند
|
||||
data, width, height = await run_in_threadpool(_normalize_media, data)
|
||||
|
||||
# نام خوانا: نام ارسالی فرم، وگرنه نام اصلی فایل بدون پسوند
|
||||
display_name = (name or "").strip() or (file.filename or "").rsplit(".", 1)[0]
|
||||
url = _store_image(data, display_name)
|
||||
|
||||
return {
|
||||
"url": url,
|
||||
"key": url.removeprefix(f"{settings.media_public_base}/"),
|
||||
"size": len(data),
|
||||
"content_type": WEBP_CONTENT_TYPE,
|
||||
"width": width,
|
||||
"height": height,
|
||||
}
|
||||
|
||||
|
||||
# ---------- درونریزی تصویر از نشانی خارجی (چسباندن از Outline و مانند آن) ----------
|
||||
|
||||
|
||||
class ImportImageIn(BaseModel):
|
||||
url: str
|
||||
|
||||
|
||||
def _assert_public_http(url: str) -> None:
|
||||
"""فقط http/https به مقاصد عمومی — جلوگیری از SSRF به شبکه داخلی."""
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in ("http", "https") or not parsed.hostname:
|
||||
raise HTTPException(status_code=400, detail="نشانی تصویر معتبر نیست")
|
||||
try:
|
||||
infos = socket.getaddrinfo(parsed.hostname, None)
|
||||
except socket.gaierror:
|
||||
raise HTTPException(status_code=400, detail="میزبان تصویر پیدا نشد")
|
||||
for info in infos:
|
||||
ip = ipaddress.ip_address(info[4][0])
|
||||
if not ip.is_global:
|
||||
raise HTTPException(status_code=400, detail="نشانی تصویر به میزبان داخلی اشاره میکند")
|
||||
|
||||
|
||||
@router.post("/import-image")
|
||||
async def import_image(
|
||||
payload: ImportImageIn,
|
||||
_admin: models.AdminUser = Depends(get_current_admin),
|
||||
):
|
||||
"""دانلود تصویر از نشانی خارجی، بهینهسازی و ذخیره در Object Storage خودِ سایت —
|
||||
تصاویر چسباندهشده از Outline/مستندات خارجی به میزبانی سایت منتقل میشوند."""
|
||||
_assert_public_http(payload.url)
|
||||
|
||||
max_bytes = settings.media_max_upload_mb * 1024 * 1024
|
||||
request = urllib.request.Request(
|
||||
payload.url, headers={"User-Agent": "ArameshSite/1.0 (+image import)"}
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
data = response.read(max_bytes + 1)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=502, detail="دانلود تصویر از نشانی ناموفق بود")
|
||||
if len(data) == 0:
|
||||
raise HTTPException(status_code=400, detail="تصویر خالی است")
|
||||
if len(data) > max_bytes:
|
||||
raise HTTPException(
|
||||
status_code=413,
|
||||
detail=f"حجم تصویر بیش از {settings.media_max_upload_mb} مگابایت است",
|
||||
)
|
||||
|
||||
# هدر Content-Type دروغ میگوید — خود بدنه رمزگشایی و به WebP نرمال میشود (روی ترد)
|
||||
data, width, height = await run_in_threadpool(_normalize_media, data)
|
||||
|
||||
# نام خوانا از مسیر نشانی — بدون پارامترهای کوئری
|
||||
url_name = urlparse(payload.url).path.rsplit("/", 1)[-1].rsplit(".", 1)[0]
|
||||
media_url = _store_image(data, url_name)
|
||||
|
||||
return {
|
||||
"url": media_url,
|
||||
"key": media_url.removeprefix(f"{settings.media_public_base}/"),
|
||||
"size": len(data),
|
||||
"content_type": WEBP_CONTENT_TYPE,
|
||||
"width": width,
|
||||
"height": height,
|
||||
}
|
||||
|
||||
|
||||
# ---------- خروجی CSV (برای تیم فروش) ----------
|
||||
|
||||
def _csv_response(filename: str, header: list[str], rows: list[list]) -> Response:
|
||||
buf = io.StringIO()
|
||||
writer = csv.writer(buf)
|
||||
writer.writerow(header)
|
||||
writer.writerows(rows)
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%d")
|
||||
return Response(
|
||||
# BOM ابتدای فایل — تا Excel متن فارسی را درست باز کند
|
||||
content="\ufeff" + buf.getvalue(),
|
||||
media_type="text/csv; charset=utf-8",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}-{stamp}.csv"'},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/messages/export.csv")
|
||||
def export_messages(db: Session = Depends(get_db)):
|
||||
rows = [
|
||||
[m.id, m.name, m.phone, m.note, "yes" if m.is_read else "no", m.created_at.isoformat()]
|
||||
for m in db.query(models.ContactMessage).order_by(models.ContactMessage.created_at.desc()).all()
|
||||
]
|
||||
return _csv_response(
|
||||
"contact-messages", ["id", "name", "phone", "note", "is_read", "created_at"], rows
|
||||
)
|
||||
|
||||
|
||||
@router.get("/subscribers/export.csv")
|
||||
def export_subscribers(db: Session = Depends(get_db)):
|
||||
rows = [
|
||||
[s.id, s.email, "yes" if s.is_active else "no", s.created_at.isoformat()]
|
||||
for s in db.query(models.Subscriber).order_by(models.Subscriber.created_at.desc()).all()
|
||||
]
|
||||
return _csv_response(
|
||||
"newsletter-subscribers", ["id", "email", "is_active", "created_at"], rows
|
||||
)
|
||||
|
||||
|
||||
# پیامهای تماس
|
||||
|
||||
@@ -1,17 +1,48 @@
|
||||
"""انتهای فرمها — ثبت پیام تماس و عضویت در خبرنامه."""
|
||||
"""انتهای فرمها — ثبت پیام تماس و عضویت در خبرنامه.
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
هر فرم یک دامنهٔ پنهان (honeypot) دارد: رباتها همهٔ فیلدها را پُر میکنند؛
|
||||
در آن حالت پاسخ موفقِ قلابی برمیگردد و چیزی ذخیره نمیشود.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from .. import models
|
||||
from ..database import get_db
|
||||
from ..rate_limit import contact_limiter, newsletter_limiter
|
||||
from ..schemas import ContactIn, ContactMessageOut, NewsletterIn, SubscriberOut
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _fake_contact(payload: ContactIn) -> ContactMessageOut:
|
||||
"""پاسخ موفق بدون ذخیره — تا ربات متوجه تله نشود."""
|
||||
return ContactMessageOut(
|
||||
id=0,
|
||||
name=payload.name.strip(),
|
||||
phone=payload.phone.strip(),
|
||||
note="",
|
||||
is_read=True,
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
|
||||
def _fake_subscriber(payload: NewsletterIn) -> SubscriberOut:
|
||||
return SubscriberOut(
|
||||
id=0,
|
||||
email=str(payload.email).lower(),
|
||||
is_active=True,
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/contact", response_model=ContactMessageOut, status_code=201)
|
||||
def submit_contact(payload: ContactIn, db: Session = Depends(get_db)):
|
||||
def submit_contact(payload: ContactIn, request: Request, db: Session = Depends(get_db)):
|
||||
contact_limiter.hit(request)
|
||||
if payload.website:
|
||||
return _fake_contact(payload)
|
||||
message = models.ContactMessage(
|
||||
name=payload.name.strip(),
|
||||
phone=payload.phone.strip(),
|
||||
@@ -24,7 +55,11 @@ def submit_contact(payload: ContactIn, db: Session = Depends(get_db)):
|
||||
|
||||
|
||||
@router.post("/newsletter", response_model=SubscriberOut, status_code=201)
|
||||
def subscribe(payload: NewsletterIn, db: Session = Depends(get_db)):
|
||||
def subscribe(payload: NewsletterIn, request: Request, db: Session = Depends(get_db)):
|
||||
newsletter_limiter.hit(request)
|
||||
if payload.website:
|
||||
return _fake_subscriber(payload)
|
||||
|
||||
email = str(payload.email).lower()
|
||||
subscriber = db.query(models.Subscriber).filter(models.Subscriber.email == email).first()
|
||||
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
"""انتهای عمومی — خواندن محتوای سایت بدون نیاز به احراز هویت."""
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config as BotoConfig
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import settings
|
||||
from ..database import get_db
|
||||
from .. import models
|
||||
from ..schemas import (
|
||||
@@ -22,9 +27,44 @@ from ..schemas import (
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/live")
|
||||
def live():
|
||||
"""زندهبودن پروسه — بدون وابستگی؛ برای restart gate استفاده نمیشود."""
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health():
|
||||
return {"status": "ok", "app": "Aramesh Building Group API"}
|
||||
def health(db: Session = Depends(get_db)):
|
||||
"""بررسی عمق سلامت — اتصال DB و MinIO واقعاً آزموده میشود؛
|
||||
در صورت خرابی هر وابستگی، 503 با جزئیات برمیگردد."""
|
||||
checks: dict[str, str] = {}
|
||||
|
||||
try:
|
||||
db.execute(text("SELECT 1"))
|
||||
checks["database"] = "ok"
|
||||
except Exception:
|
||||
checks["database"] = "error"
|
||||
|
||||
try:
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=settings.s3_endpoint,
|
||||
aws_access_key_id=settings.s3_access_key,
|
||||
aws_secret_access_key=settings.s3_secret_key,
|
||||
region_name="us-east-1",
|
||||
config=BotoConfig(connect_timeout=2, read_timeout=2, retries={"max_attempts": 1}),
|
||||
)
|
||||
s3.head_bucket(Bucket=settings.s3_bucket)
|
||||
checks["storage"] = "ok"
|
||||
except Exception:
|
||||
checks["storage"] = "error"
|
||||
|
||||
if any(state != "ok" for state in checks.values()):
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={"status": "degraded", "checks": checks},
|
||||
)
|
||||
return {"status": "ok", "app": "Aramesh Building Group API", "checks": checks}
|
||||
|
||||
|
||||
@router.get("/brand", response_model=BrandOut)
|
||||
@@ -37,12 +77,12 @@ def get_brand(db: Session = Depends(get_db)):
|
||||
|
||||
@router.get("/services", response_model=list[ServiceOut])
|
||||
def get_services(db: Session = Depends(get_db)):
|
||||
return db.query(models.Service).all()
|
||||
return db.query(models.Service).order_by(models.Service.position, models.Service.id).all()
|
||||
|
||||
|
||||
@router.get("/projects", response_model=list[ProjectOut])
|
||||
def get_projects(db: Session = Depends(get_db)):
|
||||
return db.query(models.Project).order_by(models.Project.id).all()
|
||||
return db.query(models.Project).order_by(models.Project.position, models.Project.id).all()
|
||||
|
||||
|
||||
@router.get("/projects/{slug}", response_model=ProjectOut)
|
||||
@@ -55,12 +95,21 @@ def get_project(slug: str, db: Session = Depends(get_db)):
|
||||
|
||||
@router.get("/articles", response_model=list[ArticleOut])
|
||||
def get_articles(db: Session = Depends(get_db)):
|
||||
return db.query(models.Article).order_by(models.Article.id).all()
|
||||
return (
|
||||
db.query(models.Article)
|
||||
.filter(models.Article.status == "published")
|
||||
.order_by(models.Article.position, models.Article.id)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
@router.get("/articles/{slug}", response_model=ArticleOut)
|
||||
def get_article(slug: str, db: Session = Depends(get_db)):
|
||||
article = db.query(models.Article).filter(models.Article.slug == slug).first()
|
||||
article = (
|
||||
db.query(models.Article)
|
||||
.filter(models.Article.slug == slug, models.Article.status == "published")
|
||||
.first()
|
||||
)
|
||||
if article is None:
|
||||
raise HTTPException(status_code=404, detail="مقاله یافت نشد")
|
||||
return article
|
||||
@@ -68,32 +117,32 @@ def get_article(slug: str, db: Session = Depends(get_db)):
|
||||
|
||||
@router.get("/testimonials", response_model=list[TestimonialOut])
|
||||
def get_testimonials(db: Session = Depends(get_db)):
|
||||
return db.query(models.Testimonial).all()
|
||||
return db.query(models.Testimonial).order_by(models.Testimonial.position, models.Testimonial.id).all()
|
||||
|
||||
|
||||
@router.get("/faqs", response_model=list[FaqOut])
|
||||
def get_faqs(db: Session = Depends(get_db)):
|
||||
return db.query(models.Faq).all()
|
||||
return db.query(models.Faq).order_by(models.Faq.position, models.Faq.id).all()
|
||||
|
||||
|
||||
@router.get("/team", response_model=list[TeamMemberOut])
|
||||
def get_team(db: Session = Depends(get_db)):
|
||||
return db.query(models.TeamMember).all()
|
||||
return db.query(models.TeamMember).order_by(models.TeamMember.position, models.TeamMember.id).all()
|
||||
|
||||
|
||||
@router.get("/timeline", response_model=list[TimelineItemOut])
|
||||
def get_timeline(db: Session = Depends(get_db)):
|
||||
return db.query(models.TimelineItem).order_by(models.TimelineItem.id).all()
|
||||
return db.query(models.TimelineItem).order_by(models.TimelineItem.position, models.TimelineItem.id).all()
|
||||
|
||||
|
||||
@router.get("/stats", response_model=list[StatOut])
|
||||
def get_stats(db: Session = Depends(get_db)):
|
||||
return db.query(models.Stat).all()
|
||||
return db.query(models.Stat).order_by(models.Stat.position, models.Stat.id).all()
|
||||
|
||||
|
||||
@router.get("/why-us", response_model=list[WhyUsItemOut])
|
||||
def get_why_us(db: Session = Depends(get_db)):
|
||||
return db.query(models.WhyUsItem).all()
|
||||
return db.query(models.WhyUsItem).order_by(models.WhyUsItem.position, models.WhyUsItem.id).all()
|
||||
|
||||
|
||||
@router.get("/before-after", response_model=BeforeAfterOut)
|
||||
@@ -109,14 +158,32 @@ def get_site(db: Session = Depends(get_db)):
|
||||
"""همه محتوای سایت در یک درخواست — مناسب برای بارگذاری اولیه فرانتاند."""
|
||||
return {
|
||||
"brand": db.query(models.Brand).first(),
|
||||
"services": db.query(models.Service).all(),
|
||||
"projects": db.query(models.Project).order_by(models.Project.id).all(),
|
||||
"articles": db.query(models.Article).order_by(models.Article.id).all(),
|
||||
"testimonials": db.query(models.Testimonial).all(),
|
||||
"faqs": db.query(models.Faq).all(),
|
||||
"team": db.query(models.TeamMember).all(),
|
||||
"timeline": db.query(models.TimelineItem).order_by(models.TimelineItem.id).all(),
|
||||
"stats": db.query(models.Stat).all(),
|
||||
"why_us": db.query(models.WhyUsItem).all(),
|
||||
"nav": db.query(models.NavItem).order_by(models.NavItem.position, models.NavItem.id).all(),
|
||||
"hero": db.query(models.Hero).first(),
|
||||
"story": db.query(models.StorySection).first(),
|
||||
"section_headings": db.query(models.SectionHeadingContent).order_by(models.SectionHeadingContent.id).all(),
|
||||
"page_heroes": db.query(models.PageHeroContent).order_by(models.PageHeroContent.id).all(),
|
||||
"services": db.query(models.Service).order_by(models.Service.position, models.Service.id).all(),
|
||||
"projects": db.query(models.Project).order_by(models.Project.position, models.Project.id).all(),
|
||||
# فقط مقالههای منتشرشده — پیشنویسها از انتهای مدیریتی خوانده میشوند
|
||||
"articles": db.query(models.Article)
|
||||
.filter(models.Article.status == "published")
|
||||
.order_by(models.Article.position, models.Article.id)
|
||||
.all(),
|
||||
"testimonials": db.query(models.Testimonial).order_by(models.Testimonial.position, models.Testimonial.id).all(),
|
||||
"faqs": db.query(models.Faq).order_by(models.Faq.position, models.Faq.id).all(),
|
||||
"team": db.query(models.TeamMember).order_by(models.TeamMember.position, models.TeamMember.id).all(),
|
||||
"timeline": db.query(models.TimelineItem).order_by(models.TimelineItem.position, models.TimelineItem.id).all(),
|
||||
"stats": db.query(models.Stat).order_by(models.Stat.position, models.Stat.id).all(),
|
||||
"why_us": db.query(models.WhyUsItem).order_by(models.WhyUsItem.position, models.WhyUsItem.id).all(),
|
||||
"before_after": db.query(models.BeforeAfter).first(),
|
||||
"investment_models": db.query(models.InvestmentModel).order_by(models.InvestmentModel.position, models.InvestmentModel.id).all(),
|
||||
"process_steps": db.query(models.ProcessStep).order_by(models.ProcessStep.position, models.ProcessStep.id).all(),
|
||||
"offices": db.query(models.Office).order_by(models.Office.position, models.Office.id).all(),
|
||||
"gallery": db.query(models.GalleryImage).order_by(models.GalleryImage.position, models.GalleryImage.id).all(),
|
||||
"status_labels": db.query(models.StatusLabel).order_by(models.StatusLabel.id).all(),
|
||||
"contact_section": db.query(models.ContactSectionContent).first(),
|
||||
"newsletter": db.query(models.NewsletterSectionContent).first(),
|
||||
"footer": db.query(models.FooterContent).first(),
|
||||
"seo_meta": db.query(models.SeoMeta).order_by(models.SeoMeta.id).all(),
|
||||
}
|
||||
|
||||
@@ -21,17 +21,14 @@ def verify_password(password: str, hashed: str) -> bool:
|
||||
return bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8"))
|
||||
|
||||
|
||||
def create_access_token(username: str) -> str:
|
||||
def create_access_token(username: str, role: str = "admin") -> str:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
||||
payload = {"sub": username, "exp": expire}
|
||||
payload = {"sub": username, "role": role, "exp": expire}
|
||||
return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm)
|
||||
|
||||
|
||||
def get_current_admin(
|
||||
token: str = Depends(oauth2_scheme),
|
||||
db: Session = Depends(get_db),
|
||||
) -> AdminUser:
|
||||
"""وابستگی محافظتشده — فقط با توکن JWT معتبر دسترسی میدهد."""
|
||||
def get_user_from_token(token: str, db: Session) -> AdminUser:
|
||||
"""decode توکن و برگرداندن کاربر — هم برای get_current_admin و هم نقشگارد"""
|
||||
credentials_error = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="احراز هویت نامعتبر است",
|
||||
@@ -50,3 +47,11 @@ def get_current_admin(
|
||||
if user is None:
|
||||
raise credentials_error
|
||||
return user
|
||||
|
||||
|
||||
def get_current_admin(
|
||||
token: str = Depends(oauth2_scheme),
|
||||
db: Session = Depends(get_db),
|
||||
) -> AdminUser:
|
||||
"""وابستگی محافظتشده — فقط با توکن JWT معتبر دسترسی میدهد."""
|
||||
return get_user_from_token(token, db)
|
||||
|
||||
@@ -13,10 +13,30 @@ class Settings(BaseSettings):
|
||||
database_url: str = "postgresql+psycopg://postgres:postgres@localhost:5432/arameshplaza_api"
|
||||
secret_key: str = "dev-secret-change-me-in-production"
|
||||
algorithm: str = "HS256"
|
||||
access_token_expire_minutes: int = 1440
|
||||
# ۸ ساعت — توکن stateless است و امکان ابطال ندارد؛ عمر کوتاهتر ریسک نشت را کم میکند
|
||||
access_token_expire_minutes: int = 480
|
||||
cors_origins: list[str] = ["*"]
|
||||
admin_username: str = "admin"
|
||||
admin_password: str = "aramesh123"
|
||||
|
||||
# Object Storage (MinIO / هر S3 سازگار) برای آپلود تصاویر
|
||||
s3_endpoint: str = "http://localhost:9000"
|
||||
s3_access_key: str = "aramesh"
|
||||
s3_secret_key: str = "aramesh-minio-secret"
|
||||
s3_bucket: str = "aramesh-media"
|
||||
# پیشوند عمومی مسیر تصاویر — Traefik آن را به باکت پروکسی میکند
|
||||
media_public_base: str = "/media"
|
||||
# رندرهای معماری تا ~۳۰ مگابایت — لبه (Traefik api-bodylimit = ۴۰MB) باید همیشه بزرگتر باشد
|
||||
media_max_upload_mb: int = 35
|
||||
|
||||
# نشانی کامل سایت (مثل https://aramesh.example) — برای sitemap و آدرس مطلق OG
|
||||
site_url: str = ""
|
||||
# مسیر بیلد فرانتاند (شامل index.html) — برای سرو HTML با متای سئو در صفحات جزئیات
|
||||
frontend_dist: str = "../frontend/dist"
|
||||
# پیشنمایش خصوصی: سایت روی اینترنت است اما نه عمومی و نه ایندکسشدنی.
|
||||
# گیت اصلی ورود در Traefik است (Basic Auth)؛ این پرچم لایه دوم است:
|
||||
# هدر noindex روی همه پاسخها + robots.txt مسدودکننده.
|
||||
preview_mode: bool = False
|
||||
|
||||
|
||||
settings = Settings()
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
"""ساخت جداول پایه (baseline) — پیش از مهاجرتهای Alembic.
|
||||
|
||||
روی دیتابیس تازه، همهٔ جدولها از مدلهای فعلی ساخته میشوند؛ روی دیتابیس موجود
|
||||
بیاثر است (create_all جدولهای موجود را دست نمیزند). از اینجا به بعد تغییرات
|
||||
اسکیما فقط با revisionهای Alembic اعمال میشوند.
|
||||
"""
|
||||
|
||||
from . import models # noqa: F401 — ثبت مدلها
|
||||
from .database import Base, engine
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
@@ -1,11 +1,16 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
|
||||
from . import models # noqa: F401 — ثبت مدلها پیش از ساخت جداول
|
||||
from .api import admin, forms, public
|
||||
from .config import settings
|
||||
from .database import Base, engine
|
||||
from .seo_pages import router as seo_router
|
||||
|
||||
# ساخت جداول پایه — تغییرات بعدی اسکیما فقط با revisionهای Alembic اعمال میشوند
|
||||
# (مigrations/versions). اجرای اینجا برای اجرای مستقیم uvicorn در محیط توسعه است؛
|
||||
# در کانتینر، CMD همین کار را قبل از alembic upgrade head انجام میدهد.
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
app = FastAPI(
|
||||
@@ -26,11 +31,40 @@ app.add_middleware(
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
# پاسخهای JSON /api — فشردهسازی وقتی بدنه قابلتوجه است
|
||||
app.add_middleware(GZipMiddleware, minimum_size=1024)
|
||||
|
||||
|
||||
# پیشنمایش خصوصی — لایه دوم جلوگیری از ایندکس (لایه اول، گیت ورود Traefik است).
|
||||
# روی همه پاسخها هدر noindex مینشیند تا حتی در صورت حذف گیت، گوگل چیزی ذخیره نکند.
|
||||
# همیشه ثبت میشود و پرچم در زمان هر درخواست خوانده میشود (خاموشکردن انتشار = فقط تغییر .env).
|
||||
@app.middleware("http")
|
||||
async def _preview_noindex(request, call_next):
|
||||
response = await call_next(request)
|
||||
if settings.preview_mode:
|
||||
response.headers["X-Robots-Tag"] = "noindex, nofollow, noarchive"
|
||||
return response
|
||||
|
||||
# پاسخهای API هرگز کش مرورگر/CDN نشوند — دادهٔ پنل بعد از هر ذخیره فوراً fresh بماند
|
||||
@app.middleware("http")
|
||||
async def _api_no_store(request, call_next):
|
||||
response = await call_next(request)
|
||||
if request.url.path.startswith("/api"):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
app.include_router(public.router, prefix="/api", tags=["عمومی"])
|
||||
app.include_router(forms.router, prefix="/api", tags=["فرمها"])
|
||||
app.include_router(admin.auth_router, prefix="/api", tags=["احراز هویت"])
|
||||
app.include_router(admin.router, prefix="/api/admin", tags=["پنل مدیریت"])
|
||||
# robots.txt، sitemap.xml و HTML صفحات وبلاگ/پروژه با متای سئو — در ریشه دامنه
|
||||
app.include_router(seo_router, tags=["سئو"])
|
||||
|
||||
# متریکهای Prometheus — فقط Prometheus در شبکه داخلی اسکرپ میکند
|
||||
# (Traefik مسیر /metrics را نمیشناسد، پس از بیرون در دسترس نیست)
|
||||
from prometheus_fastapi_instrumentator import Instrumentator # noqa: E402
|
||||
|
||||
Instrumentator().instrument(app).expose(app, endpoint="/metrics", include_in_schema=False)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
"""مهاجرتهای سبک دیتابیس — DDL و تبدیل دادههای قدیمی؛ همه idempotent.
|
||||
|
||||
هم main.py (startup) و هم seed.py اینها را صدا میزنند تا هر مسیر اجرایی
|
||||
دیتابیس موجود را بدون از دست رفتن داده ارتقا دهد.
|
||||
"""
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from .database import SessionLocal, engine
|
||||
|
||||
# جدولهای مجموعهای که ستون position دارند
|
||||
POSITION_TABLES = [
|
||||
"services", "projects", "articles", "testimonials", "faqs", "team",
|
||||
"timeline", "stats", "why_us", "investment_models", "process_steps",
|
||||
"offices", "gallery_images", "nav_items",
|
||||
]
|
||||
|
||||
# ستونهای انگلیسی — (جدول، ستون، نوع). ستونهای JSON بدون default اند تا
|
||||
# سطرهای موجود NULL بگیرند (یعنی «ترجمه ثبت نشده») و فرانت به فارسی برگردد.
|
||||
EN_COLUMNS: list[tuple[str, str, str]] = [
|
||||
("brand", "name_en", "VARCHAR(128)"),
|
||||
("brand", "address_en", "TEXT"),
|
||||
("services", "title_en", "VARCHAR(256)"),
|
||||
("services", "desc_en", "TEXT"),
|
||||
("projects", "title_en", "VARCHAR(256)"),
|
||||
("projects", "location_en", "VARCHAR(128)"),
|
||||
("projects", "year_en", "VARCHAR(64)"),
|
||||
("projects", "area_en", "VARCHAR(64)"),
|
||||
("projects", "floors_en", "VARCHAR(64)"),
|
||||
("projects", "land_area", "VARCHAR(64)"),
|
||||
("projects", "pilot_floors", "VARCHAR(32)"),
|
||||
("projects", "units_residential", "VARCHAR(32)"),
|
||||
("projects", "units_commercial", "VARCHAR(32)"),
|
||||
("projects", "units_office", "VARCHAR(32)"),
|
||||
("projects", "client_en", "VARCHAR(128)"),
|
||||
("projects", "project_type", "VARCHAR(128)"),
|
||||
("projects", "project_type_en", "VARCHAR(128)"),
|
||||
("projects", "usage", "VARCHAR(128)"),
|
||||
("projects", "usage_en", "VARCHAR(128)"),
|
||||
("projects", "summary_en", "TEXT"),
|
||||
("projects", "body_en", "JSON"),
|
||||
("articles", "title_en", "VARCHAR(256)"),
|
||||
("articles", "date_en", "VARCHAR(64)"),
|
||||
("articles", "category_en", "VARCHAR(64)"),
|
||||
("articles", "read_en", "VARCHAR(32)"),
|
||||
("articles", "excerpt_en", "TEXT"),
|
||||
("articles", "body_en", "JSON"),
|
||||
("testimonials", "name_en", "VARCHAR(128)"),
|
||||
("testimonials", "role_en", "VARCHAR(128)"),
|
||||
("testimonials", "quote_en", "TEXT"),
|
||||
("faqs", "question_en", "TEXT"),
|
||||
("faqs", "answer_en", "TEXT"),
|
||||
("team", "name_en", "VARCHAR(128)"),
|
||||
("team", "role_en", "VARCHAR(128)"),
|
||||
("team", "bio_en", "TEXT"),
|
||||
("timeline", "year_en", "VARCHAR(32)"),
|
||||
("timeline", "title_en", "VARCHAR(256)"),
|
||||
("timeline", "desc_en", "TEXT"),
|
||||
("stats", "suffix_en", "VARCHAR(16)"),
|
||||
("stats", "label_en", "VARCHAR(128)"),
|
||||
("why_us", "title_en", "VARCHAR(256)"),
|
||||
("why_us", "desc_en", "TEXT"),
|
||||
("before_after", "title_en", "VARCHAR(256)"),
|
||||
("before_after", "lead_en", "TEXT"),
|
||||
("before_after", "before_label_en", "VARCHAR(128)"),
|
||||
("before_after", "after_label_en", "VARCHAR(128)"),
|
||||
("nav_items", "label_en", "VARCHAR(64)"),
|
||||
("hero", "kicker_en", "TEXT"),
|
||||
("hero", "title_en", "TEXT"),
|
||||
("hero", "title_highlight_en", "VARCHAR(128)"),
|
||||
("hero", "subtitle_en", "TEXT"),
|
||||
("hero", "badge_value_en", "VARCHAR(32)"),
|
||||
("hero", "badge_label_en", "TEXT"),
|
||||
("hero", "cta_primary_label_en", "VARCHAR(128)"),
|
||||
("hero", "cta_secondary_label_en", "VARCHAR(128)"),
|
||||
("hero", "scroll_label_en", "VARCHAR(64)"),
|
||||
("story", "title_en", "VARCHAR(256)"),
|
||||
("story", "paragraphs_en", "JSON"),
|
||||
("story", "quote_en", "TEXT"),
|
||||
("story", "quote_author_en", "TEXT"),
|
||||
("story", "stat1_value_en", "VARCHAR(32)"),
|
||||
("story", "stat1_label_en", "VARCHAR(128)"),
|
||||
("story", "stat2_value_en", "VARCHAR(32)"),
|
||||
("story", "stat2_label_en", "VARCHAR(128)"),
|
||||
("story", "link_label_en", "VARCHAR(128)"),
|
||||
("story", "bento_en", "JSON"),
|
||||
("section_headings", "label_en", "VARCHAR(64)"),
|
||||
("section_headings", "title_en", "VARCHAR(256)"),
|
||||
("section_headings", "lead_en", "TEXT"),
|
||||
("section_headings", "cta_label_en", "VARCHAR(128)"),
|
||||
("page_heroes", "title_en", "VARCHAR(256)"),
|
||||
("page_heroes", "lead_en", "TEXT"),
|
||||
("investment_models", "title_en", "VARCHAR(256)"),
|
||||
("investment_models", "desc_en", "TEXT"),
|
||||
("investment_models", "points_en", "JSON"),
|
||||
("process_steps", "step_en", "VARCHAR(16)"),
|
||||
("process_steps", "title_en", "VARCHAR(256)"),
|
||||
("process_steps", "desc_en", "TEXT"),
|
||||
("offices", "city_en", "VARCHAR(64)"),
|
||||
("offices", "address_en", "TEXT"),
|
||||
("offices", "hours_en", "VARCHAR(128)"),
|
||||
("gallery_images", "alt_en", "TEXT"),
|
||||
("status_labels", "label_en", "VARCHAR(64)"),
|
||||
("contact_section", "label_en", "VARCHAR(64)"),
|
||||
("contact_section", "title_en", "VARCHAR(256)"),
|
||||
("contact_section", "lead_en", "TEXT"),
|
||||
("contact_section", "address_label_en", "VARCHAR(64)"),
|
||||
("contact_section", "phone_label_en", "VARCHAR(64)"),
|
||||
("contact_section", "email_label_en", "VARCHAR(64)"),
|
||||
("contact_section", "name_label_en", "VARCHAR(64)"),
|
||||
("contact_section", "name_placeholder_en", "VARCHAR(128)"),
|
||||
("contact_section", "phone_field_label_en", "VARCHAR(64)"),
|
||||
("contact_section", "phone_placeholder_en", "VARCHAR(64)"),
|
||||
("contact_section", "note_label_en", "VARCHAR(64)"),
|
||||
("contact_section", "note_optional_label_en", "VARCHAR(64)"),
|
||||
("contact_section", "note_placeholder_en", "VARCHAR(256)"),
|
||||
("contact_section", "submit_label_en", "VARCHAR(128)"),
|
||||
("contact_section", "sending_label_en", "VARCHAR(64)"),
|
||||
("contact_section", "success_title_en", "VARCHAR(256)"),
|
||||
("contact_section", "success_text_en", "TEXT"),
|
||||
("contact_section", "success_button_label_en", "VARCHAR(128)"),
|
||||
("newsletter", "title_en", "VARCHAR(256)"),
|
||||
("newsletter", "lead_en", "TEXT"),
|
||||
("newsletter", "placeholder_en", "VARCHAR(128)"),
|
||||
("newsletter", "button_label_en", "VARCHAR(64)"),
|
||||
("newsletter", "sending_label_en", "VARCHAR(64)"),
|
||||
("newsletter", "success_text_en", "VARCHAR(256)"),
|
||||
("footer", "about_text_en", "TEXT"),
|
||||
("footer", "pages_heading_en", "VARCHAR(64)"),
|
||||
("footer", "services_heading_en", "VARCHAR(64)"),
|
||||
("footer", "contact_heading_en", "VARCHAR(64)"),
|
||||
("footer", "copyright_en", "VARCHAR(256)"),
|
||||
("footer", "tagline_en", "VARCHAR(256)"),
|
||||
("footer", "socials_en", "JSON"),
|
||||
("seo_meta", "title_en", "VARCHAR(256)"),
|
||||
("seo_meta", "description_en", "TEXT"),
|
||||
]
|
||||
|
||||
|
||||
def run_ddl_migrations() -> None:
|
||||
"""ستونهای جدید — برای PostgreSQL با ADD COLUMN IF NOT EXISTS."""
|
||||
if engine.dialect.name != "postgresql":
|
||||
return
|
||||
with engine.begin() as conn:
|
||||
for table in POSITION_TABLES:
|
||||
conn.execute(
|
||||
text(f"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS position INTEGER NOT NULL DEFAULT 0")
|
||||
)
|
||||
# مقالات موجود منتشر شدهاند؛ فقط مقالههای تازه میتوانند پیشنویس باشند
|
||||
conn.execute(
|
||||
text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS status VARCHAR(16) NOT NULL DEFAULT 'published'")
|
||||
)
|
||||
conn.execute(
|
||||
text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS seo_keyphrase VARCHAR(128) NOT NULL DEFAULT ''")
|
||||
)
|
||||
# نام نویسنده و توضیحات سئوی اختصاصی مقاله — فیلدهایی که پنل قبلاً نمایش میداد ولی در دیتابیس نبودند
|
||||
conn.execute(
|
||||
text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS author VARCHAR(128) NOT NULL DEFAULT ''")
|
||||
)
|
||||
conn.execute(
|
||||
text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS meta_description TEXT NOT NULL DEFAULT ''")
|
||||
)
|
||||
conn.execute(
|
||||
text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS meta_description_en TEXT NOT NULL DEFAULT ''")
|
||||
)
|
||||
# نقشها — 'admin' همهکاره، 'creator' فقط نویسندهٔ محتوا
|
||||
conn.execute(
|
||||
text("ALTER TABLE admin_users ADD COLUMN IF NOT EXISTS role VARCHAR(16) NOT NULL DEFAULT 'admin'")
|
||||
)
|
||||
# نویسندهٔ مقاله — نقش creator فقط مقالههای خودش را میبیند/ویرایش میکند
|
||||
conn.execute(
|
||||
text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS author_id INTEGER")
|
||||
)
|
||||
# متادیتای تصویر شاخص مقاله + پرسشوپاسخهای پایان مقاله (سئو)
|
||||
conn.execute(
|
||||
text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS image_alt VARCHAR(256) NOT NULL DEFAULT ''")
|
||||
)
|
||||
conn.execute(
|
||||
text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS image_title VARCHAR(256) NOT NULL DEFAULT ''")
|
||||
)
|
||||
conn.execute(text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS faqs JSON"))
|
||||
conn.execute(text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS faqs_en JSON"))
|
||||
# سطرهای موجود ستون تازه را NULL میگیرند — آرایه خالی یعنی «بدون پرسشوپاسخ»
|
||||
conn.execute(text("UPDATE articles SET faqs = '[]'::json WHERE faqs IS NULL"))
|
||||
# ستونهای انگلیسی — رشتهها با پیشفرض خالی، JSON بدون پیشفرض (NULL = بدون ترجمه)
|
||||
for table, column, col_type in EN_COLUMNS:
|
||||
if col_type == "JSON":
|
||||
conn.execute(text(f"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS {column} JSON"))
|
||||
else:
|
||||
conn.execute(
|
||||
text(f"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS {column} {col_type} NOT NULL DEFAULT ''")
|
||||
)
|
||||
|
||||
|
||||
def paragraphs_to_doc(paragraphs: list) -> dict:
|
||||
"""تبدیل لیست پاراگرافهای متنی (فرمت قدیمی بدنه مقاله) به سند TipTap."""
|
||||
content = []
|
||||
for para in paragraphs:
|
||||
if isinstance(para, str) and para.strip():
|
||||
content.append({
|
||||
"type": "paragraph",
|
||||
"content": [{"type": "text", "text": para}],
|
||||
})
|
||||
if not content:
|
||||
content = [{"type": "paragraph"}]
|
||||
return {"type": "doc", "content": content}
|
||||
|
||||
|
||||
def migrate_article_bodies() -> None:
|
||||
"""تبدیل بدنه مقالات از لیست پاراگراف به سند JSON — idempotent."""
|
||||
from . import models # lazy — جلوگیری از import حلقهای
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
changed = 0
|
||||
for article in db.query(models.Article).all():
|
||||
if isinstance(article.body, list):
|
||||
article.body = paragraphs_to_doc(article.body)
|
||||
changed += 1
|
||||
db.commit()
|
||||
if changed:
|
||||
print(f"مقالات تبدیلشده به فرمت سند: {changed}")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def _is_empty(value: object) -> bool:
|
||||
"""مقدار خالی انگلیسی — یعنی هنوز ترجمهای ثبت نشده و قابل پر کردن است."""
|
||||
if value is None or value == "" or value == [] or value == {}:
|
||||
return True
|
||||
if isinstance(value, dict) and value.get("content") == [{"type": "paragraph"}]:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _backfill_row(row, en_fields: dict) -> int:
|
||||
"""پر کردن فیلدهای خالی *_en یک سطر از دیکشنری ترجمه — تعداد فیلدهای پرشده."""
|
||||
filled = 0
|
||||
for key, value in en_fields.items():
|
||||
if not key.endswith("_en"):
|
||||
continue
|
||||
if not _is_empty(getattr(row, key, None)):
|
||||
continue
|
||||
setattr(row, key, value)
|
||||
filled += 1
|
||||
return filled
|
||||
|
||||
|
||||
def backfill_en_content() -> None:
|
||||
"""پر کردن ترجمههای انگلیسی سطرهای موجود از seed_data_en — idempotent.
|
||||
|
||||
تطبیق سطرها: جدولهای تکسطری مستقیم؛ بقیه با کلیدهای طبیعی/متنی فارسی
|
||||
(مثلاً slug پروژه، href منو، عنوان خدمت، متن پرسش) — اگر ادمین متن فارسی را
|
||||
ویرایش کرده باشد سطر تطبیق نمیخورد و ترجمهاش خالی میماند تا از پنل پر شود.
|
||||
هیچ مقدار انگلیسیِ ثبتشده بازنویسی نمیشود.
|
||||
"""
|
||||
from . import models, seed_data, seed_data_en # lazy — جلوگیری از import حلقهای
|
||||
|
||||
# (مدل، فهرست فارسی، فهرست انگلیسی، کلیدهای تطبیق — خالی برای تکسطریها)
|
||||
PLAN: list[tuple[object, list[dict], list[dict], tuple[str, ...]]] = [
|
||||
(models.Brand, [seed_data.BRAND], [seed_data_en.BRAND], ()),
|
||||
(models.Hero, [seed_data.HERO], [seed_data_en.HERO], ()),
|
||||
(models.StorySection, [seed_data.STORY], [seed_data_en.STORY], ()),
|
||||
(models.SectionHeadingContent, seed_data.SECTION_HEADINGS, seed_data_en.SECTION_HEADINGS, ("key", "title")),
|
||||
(models.PageHeroContent, seed_data.PAGE_HEROES, seed_data_en.PAGE_HEROES, ("key", "title")),
|
||||
(models.NavItem, seed_data.NAV_ITEMS, seed_data_en.NAV_ITEMS, ("href", "label")),
|
||||
(models.InvestmentModel, seed_data.INVESTMENT_MODELS, seed_data_en.INVESTMENT_MODELS, ("title",)),
|
||||
(models.ProcessStep, seed_data.PROCESS_STEPS, seed_data_en.PROCESS_STEPS, ("title",)),
|
||||
(models.Office, seed_data.OFFICES, seed_data_en.OFFICES, ("city",)),
|
||||
(models.GalleryImage, seed_data.GALLERY_IMAGES, seed_data_en.GALLERY_IMAGES, ("alt",)),
|
||||
(models.StatusLabel, seed_data.STATUS_LABELS, seed_data_en.STATUS_LABELS, ("key",)),
|
||||
(models.ContactSectionContent, [seed_data.CONTACT_SECTION], [seed_data_en.CONTACT_SECTION], ()),
|
||||
(models.NewsletterSectionContent, [seed_data.NEWSLETTER], [seed_data_en.NEWSLETTER], ()),
|
||||
(models.FooterContent, [seed_data.FOOTER], [seed_data_en.FOOTER], ()),
|
||||
(models.Service, seed_data.SERVICES, seed_data_en.SERVICES, ("title",)),
|
||||
(models.Stat, seed_data.STATS, seed_data_en.STATS, ("label",)),
|
||||
(models.Project, seed_data.PROJECTS, seed_data_en.PROJECTS, ("slug", "title")),
|
||||
(models.Article, seed_data.ARTICLES, seed_data_en.ARTICLES, ("slug", "title")),
|
||||
(models.Testimonial, seed_data.TESTIMONIALS, seed_data_en.TESTIMONIALS, ("name",)),
|
||||
(models.Faq, seed_data.FAQS, seed_data_en.FAQS, ("question",)),
|
||||
(models.TeamMember, seed_data.TEAM, seed_data_en.TEAM, ("name",)),
|
||||
(models.TimelineItem, seed_data.TIMELINE, seed_data_en.TIMELINE, ("title",)),
|
||||
(models.WhyUsItem, seed_data.WHY, seed_data_en.WHY, ("title",)),
|
||||
(models.BeforeAfter, [seed_data.BEFORE_AFTER], [seed_data_en.BEFORE_AFTER], ()),
|
||||
(models.SeoMeta, seed_data.SEO_META, seed_data_en.SEO_META, ("page_key",)),
|
||||
]
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
total_rows = 0
|
||||
total_fields = 0
|
||||
unmatched: list[str] = []
|
||||
for model, fa_rows, en_rows, match_keys in PLAN:
|
||||
rows = db.query(model).all()
|
||||
if not rows or not en_rows:
|
||||
continue
|
||||
table_name = getattr(model, "__tablename__", str(model))
|
||||
|
||||
if not match_keys:
|
||||
if len(rows) != 1 or len(en_rows) != 1:
|
||||
unmatched.append(table_name)
|
||||
continue
|
||||
pairs = [(rows[0], en_rows[0])]
|
||||
else:
|
||||
# برای هر کلید، نگاشت مقدار → سطر ترجمه (اولین کلید برنده است)
|
||||
en_lookups: list[dict[object, dict]] = []
|
||||
for key in match_keys:
|
||||
en_lookups.append({r[key]: r for r in en_rows if r.get(key) is not None})
|
||||
pairs = []
|
||||
matched_en_ids: set[int] = set()
|
||||
for row in rows:
|
||||
en_row = None
|
||||
for key, lookup in zip(match_keys, en_lookups):
|
||||
en_row = lookup.get(getattr(row, key, None))
|
||||
if en_row is not None:
|
||||
break
|
||||
if en_row is not None and id(en_row) not in matched_en_ids:
|
||||
matched_en_ids.add(id(en_row))
|
||||
pairs.append((row, en_row))
|
||||
|
||||
for row, en_row in pairs:
|
||||
# بدنه مقاله انگلیسی هم مثل فارسی از پاراگراف به سند تبدیل میشود
|
||||
en_fields = dict(en_row)
|
||||
if model is models.Article and isinstance(en_fields.get("body_en"), list):
|
||||
en_fields["body_en"] = paragraphs_to_doc(en_fields["body_en"])
|
||||
filled = _backfill_row(row, en_fields)
|
||||
total_fields += filled
|
||||
if filled:
|
||||
total_rows += 1
|
||||
|
||||
db.commit()
|
||||
if total_fields:
|
||||
print(f"ترجمه انگلیسی پر شد: {total_fields} فیلد در {total_rows} سطر.")
|
||||
if unmatched:
|
||||
print("سطرهایی که با seed تطبیق نکردند (از پنل مدیریت ترجمه کنید):")
|
||||
for name in unmatched:
|
||||
print(f" - {name}")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def run_all() -> None:
|
||||
run_ddl_migrations()
|
||||
migrate_article_bodies()
|
||||
backfill_en_content()
|
||||
@@ -1,4 +1,5 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import JSON, Boolean, DateTime, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
@@ -10,12 +11,18 @@ def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
# ستونهای *_en معادل انگلیسی فیلدهای متنیِ قابل نمایش هستند؛
|
||||
# مقدار خالی یعنی «ترجمهای ثبت نشده» و فرانتاند به نسخه فارسی برمیگردد.
|
||||
|
||||
|
||||
class AdminUser(Base):
|
||||
__tablename__ = "admin_users"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(255))
|
||||
# 'admin' همهکاره — 'creator' فقط نویسندهٔ محتوا (پیشنویس مقالههای خودش)
|
||||
role: Mapped[str] = mapped_column(String(16), default='admin')
|
||||
|
||||
|
||||
class Brand(Base):
|
||||
@@ -23,108 +30,194 @@ class Brand(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(128), default="")
|
||||
name_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
logo: Mapped[str] = mapped_column(Text, default="")
|
||||
logo_en: Mapped[str] = mapped_column(Text, default="")
|
||||
hero: Mapped[str] = mapped_column(Text, default="")
|
||||
contact_bg: Mapped[str] = mapped_column(Text, default="")
|
||||
phone: Mapped[str] = mapped_column(String(64), default="")
|
||||
phone_href: Mapped[str] = mapped_column(String(128), default="")
|
||||
email: Mapped[str] = mapped_column(String(128), default="")
|
||||
address: Mapped[str] = mapped_column(Text, default="")
|
||||
address_en: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class Service(Base):
|
||||
__tablename__ = "services"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(256))
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
desc: Mapped[str] = mapped_column(Text, default="")
|
||||
desc_en: Mapped[str] = mapped_column(Text, default="")
|
||||
icon: Mapped[str] = mapped_column(String(32), default="draft")
|
||||
|
||||
|
||||
class Project(Base):
|
||||
__tablename__ = "projects"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
slug: Mapped[str] = mapped_column(String(128), unique=True, index=True)
|
||||
title: Mapped[str] = mapped_column(String(256))
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
location: Mapped[str] = mapped_column(String(128), default="")
|
||||
location_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
year: Mapped[str] = mapped_column(String(64), default="")
|
||||
year_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
status: Mapped[str] = mapped_column(String(16), default="done") # done | progress
|
||||
image: Mapped[str] = mapped_column(Text, default="")
|
||||
gallery: Mapped[list] = mapped_column(JSON, default=list)
|
||||
area: Mapped[str] = mapped_column(String(64), default="")
|
||||
area_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
floors: Mapped[str] = mapped_column(String(64), default="")
|
||||
units: Mapped[str] = mapped_column(String(64), default="")
|
||||
floors_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
land_area: Mapped[str] = mapped_column(String(64), default="")
|
||||
pilot_floors: Mapped[str] = mapped_column(String(32), default="")
|
||||
units_residential: Mapped[str] = mapped_column(String(32), default="")
|
||||
units_commercial: Mapped[str] = mapped_column(String(32), default="")
|
||||
units_office: Mapped[str] = mapped_column(String(32), default="")
|
||||
client: Mapped[str] = mapped_column(String(128), default="")
|
||||
client_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
# مشخصات تکمیلی پروژه — به درخواست تیم: نوع پروژه و کاربری
|
||||
project_type: Mapped[str] = mapped_column(String(128), default="")
|
||||
project_type_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
usage: Mapped[str] = mapped_column(String(128), default="")
|
||||
usage_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
summary: Mapped[str] = mapped_column(Text, default="")
|
||||
summary_en: Mapped[str] = mapped_column(Text, default="")
|
||||
body: Mapped[list] = mapped_column(JSON, default=list)
|
||||
body_en: Mapped[list] = mapped_column(JSON, default=list)
|
||||
|
||||
|
||||
class Article(Base):
|
||||
__tablename__ = "articles"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
slug: Mapped[str] = mapped_column(String(128), unique=True, index=True)
|
||||
title: Mapped[str] = mapped_column(String(256))
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
date: Mapped[str] = mapped_column(String(64), default="")
|
||||
date_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
category: Mapped[str] = mapped_column(String(64), default="")
|
||||
category_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
image: Mapped[str] = mapped_column(Text, default="")
|
||||
# متن جایگزین و عنوان تصویر شاخص — سئو و دسترسپذیری
|
||||
image_alt: Mapped[str] = mapped_column(String(256), default="")
|
||||
image_title: Mapped[str] = mapped_column(String(256), default="")
|
||||
read: Mapped[str] = mapped_column(String(32), default="")
|
||||
read_en: Mapped[str] = mapped_column(String(32), default="")
|
||||
excerpt: Mapped[str] = mapped_column(Text, default="")
|
||||
body: Mapped[list] = mapped_column(JSON, default=list)
|
||||
excerpt_en: Mapped[str] = mapped_column(Text, default="")
|
||||
body: Mapped[list] = mapped_column(JSON, default=list) # سند TipTap (تاریخی: لیست پاراگراف)
|
||||
body_en: Mapped[dict] = mapped_column(JSON, default=dict) # سند TipTap انگلیسی
|
||||
# پرسش و پاسخهای پایان مقاله — [{question, answer}]؛ برای نتایج غنی سئو (FAQPage)
|
||||
faqs: Mapped[list] = mapped_column(JSON, default=list)
|
||||
faqs_en: Mapped[Optional[list]] = mapped_column(JSON) # NULL یعنی بدون ترجمه — برگشت به فارسی
|
||||
author_id: Mapped[int | None] = mapped_column(Integer, nullable=True) # نویسندهٔ creator — برای مقالههای ادمین NULL
|
||||
# نام نویسنده (رشتهٔ آزاد) — سربرگ مقاله و اسکیمای Article (نوع Person برای سیگنال E-E-A-T)
|
||||
author: Mapped[str] = mapped_column(String(128), default="")
|
||||
# draft | published — پیشنویس فقط برای ادمین دیده میشود
|
||||
status: Mapped[str] = mapped_column(String(16), default="published")
|
||||
# کلمه کلیدی هدف چکلیست سئو — راهنمای نوشتن، در سایت نمایش داده نمیشود
|
||||
seo_keyphrase: Mapped[str] = mapped_column(String(128), default="")
|
||||
# توضیحات سئوی اختصاصی مقاله — در تگ description و اسکیما، در اولویت بر چکیده
|
||||
meta_description: Mapped[str] = mapped_column(Text, default="")
|
||||
meta_description_en: Mapped[str] = mapped_column(Text, default="")
|
||||
# نشانی انگلیسی مقاله — مسیر /en/blog/...؛ خالی یعنی همان اسلاگ فارسی
|
||||
slug_en: Mapped[str] = mapped_column(String(128), default="", index=True)
|
||||
# کلمه کلیدی هدف نسخه انگلیسی — چکلیست سئو
|
||||
seo_keyphrase_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
# نام نویسنده نسخه انگلیسی
|
||||
author_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
# هشتگها/برچسبها — هر زبان جدا
|
||||
tags: Mapped[list] = mapped_column(JSON, default=list)
|
||||
tags_en: Mapped[list] = mapped_column(JSON, default=list)
|
||||
|
||||
|
||||
class Testimonial(Base):
|
||||
__tablename__ = "testimonials"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(128))
|
||||
name_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
role: Mapped[str] = mapped_column(String(128), default="")
|
||||
role_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
quote: Mapped[str] = mapped_column(Text, default="")
|
||||
quote_en: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class Faq(Base):
|
||||
__tablename__ = "faqs"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
question: Mapped[str] = mapped_column(Text)
|
||||
question_en: Mapped[str] = mapped_column(Text, default="")
|
||||
answer: Mapped[str] = mapped_column(Text, default="")
|
||||
answer_en: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class TeamMember(Base):
|
||||
__tablename__ = "team"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(128))
|
||||
name_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
role: Mapped[str] = mapped_column(String(128), default="")
|
||||
role_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
bio: Mapped[str] = mapped_column(Text, default="")
|
||||
bio_en: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class TimelineItem(Base):
|
||||
__tablename__ = "timeline"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
year: Mapped[str] = mapped_column(String(32))
|
||||
year_en: Mapped[str] = mapped_column(String(32), default="")
|
||||
title: Mapped[str] = mapped_column(String(256))
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
desc: Mapped[str] = mapped_column(Text, default="")
|
||||
desc_en: Mapped[str] = mapped_column(Text, default="")
|
||||
image: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class Stat(Base):
|
||||
__tablename__ = "stats"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
value: Mapped[int] = mapped_column(Integer)
|
||||
suffix: Mapped[str] = mapped_column(String(16), default="")
|
||||
suffix_en: Mapped[str] = mapped_column(String(16), default="")
|
||||
label: Mapped[str] = mapped_column(String(128))
|
||||
label_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
|
||||
|
||||
class WhyUsItem(Base):
|
||||
__tablename__ = "why_us"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(256))
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
desc: Mapped[str] = mapped_column(Text, default="")
|
||||
desc_en: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class BeforeAfter(Base):
|
||||
@@ -132,11 +225,279 @@ class BeforeAfter(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(256), default="")
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
lead: Mapped[str] = mapped_column(Text, default="")
|
||||
lead_en: Mapped[str] = mapped_column(Text, default="")
|
||||
before: Mapped[str] = mapped_column(Text, default="")
|
||||
after: Mapped[str] = mapped_column(Text, default="")
|
||||
before_label: Mapped[str] = mapped_column(String(128), default="")
|
||||
before_label_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
after_label: Mapped[str] = mapped_column(String(128), default="")
|
||||
after_label_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
|
||||
|
||||
class NavItem(Base):
|
||||
__tablename__ = "nav_items"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
label: Mapped[str] = mapped_column(String(64))
|
||||
label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
href: Mapped[str] = mapped_column(String(128))
|
||||
|
||||
|
||||
class Hero(Base):
|
||||
"""محتوای هیرو صفحه اصلی — رکورد یگانه."""
|
||||
|
||||
__tablename__ = "hero"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
kicker: Mapped[str] = mapped_column(Text, default="")
|
||||
kicker_en: Mapped[str] = mapped_column(Text, default="")
|
||||
title: Mapped[str] = mapped_column(Text, default="")
|
||||
title_en: Mapped[str] = mapped_column(Text, default="")
|
||||
title_highlight: Mapped[str] = mapped_column(String(128), default="")
|
||||
title_highlight_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
subtitle: Mapped[str] = mapped_column(Text, default="")
|
||||
subtitle_en: Mapped[str] = mapped_column(Text, default="")
|
||||
badge_value: Mapped[str] = mapped_column(String(32), default="")
|
||||
badge_value_en: Mapped[str] = mapped_column(String(32), default="")
|
||||
badge_label: Mapped[str] = mapped_column(Text, default="")
|
||||
badge_label_en: Mapped[str] = mapped_column(Text, default="")
|
||||
cta_primary_label: Mapped[str] = mapped_column(String(128), default="")
|
||||
cta_primary_label_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
cta_primary_href: Mapped[str] = mapped_column(String(128), default="")
|
||||
cta_secondary_label: Mapped[str] = mapped_column(String(128), default="")
|
||||
cta_secondary_label_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
cta_secondary_href: Mapped[str] = mapped_column(String(128), default="")
|
||||
scroll_label: Mapped[str] = mapped_column(String(64), default="")
|
||||
scroll_label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
|
||||
|
||||
class StorySection(Base):
|
||||
"""بخش «درباره ما» در خانه و صفحه درباره — رکورد یگانه."""
|
||||
|
||||
__tablename__ = "story"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(256), default="")
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
paragraphs: Mapped[list] = mapped_column(JSON, default=list)
|
||||
paragraphs_en: Mapped[list] = mapped_column(JSON, default=list)
|
||||
quote: Mapped[str] = mapped_column(Text, default="")
|
||||
quote_en: Mapped[str] = mapped_column(Text, default="")
|
||||
quote_author: Mapped[str] = mapped_column(Text, default="")
|
||||
quote_author_en: Mapped[str] = mapped_column(Text, default="")
|
||||
stat1_value: Mapped[str] = mapped_column(String(32), default="")
|
||||
stat1_value_en: Mapped[str] = mapped_column(String(32), default="")
|
||||
stat1_label: Mapped[str] = mapped_column(String(128), default="")
|
||||
stat1_label_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
stat2_value: Mapped[str] = mapped_column(String(32), default="")
|
||||
stat2_value_en: Mapped[str] = mapped_column(String(32), default="")
|
||||
stat2_label: Mapped[str] = mapped_column(String(128), default="")
|
||||
stat2_label_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
link_label: Mapped[str] = mapped_column(String(128), default="")
|
||||
link_label_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
link_href: Mapped[str] = mapped_column(String(128), default="")
|
||||
bento: Mapped[list] = mapped_column(JSON, default=list) # [{src, alt}]
|
||||
bento_en: Mapped[list] = mapped_column(JSON, default=list) # [{src, alt}] انگلیسی
|
||||
|
||||
|
||||
class SectionHeadingContent(Base):
|
||||
"""تیتر و توضیح بخشها — فرانتاند بر اساس key آن را پیدا میکند."""
|
||||
|
||||
__tablename__ = "section_headings"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
key: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
label: Mapped[str] = mapped_column(String(64), default="")
|
||||
label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
title: Mapped[str] = mapped_column(String(256), default="")
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
lead: Mapped[str] = mapped_column(Text, default="")
|
||||
lead_en: Mapped[str] = mapped_column(Text, default="")
|
||||
image: Mapped[str] = mapped_column(Text, default="")
|
||||
cta_label: Mapped[str] = mapped_column(String(128), default="")
|
||||
cta_label_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
cta_href: Mapped[str] = mapped_column(String(128), default="")
|
||||
|
||||
|
||||
class PageHeroContent(Base):
|
||||
"""هیرو بالای هر صفحه — key: about | services | projects | investment | blog | faq | contact."""
|
||||
|
||||
__tablename__ = "page_heroes"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
key: Mapped[str] = mapped_column(String(32), unique=True, index=True)
|
||||
title: Mapped[str] = mapped_column(String(256), default="")
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
lead: Mapped[str] = mapped_column(Text, default="")
|
||||
lead_en: Mapped[str] = mapped_column(Text, default="")
|
||||
image: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class InvestmentModel(Base):
|
||||
__tablename__ = "investment_models"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(256))
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
desc: Mapped[str] = mapped_column(Text, default="")
|
||||
desc_en: Mapped[str] = mapped_column(Text, default="")
|
||||
points: Mapped[list] = mapped_column(JSON, default=list)
|
||||
points_en: Mapped[list] = mapped_column(JSON, default=list)
|
||||
|
||||
|
||||
class ProcessStep(Base):
|
||||
__tablename__ = "process_steps"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
step: Mapped[str] = mapped_column(String(16), default="")
|
||||
step_en: Mapped[str] = mapped_column(String(16), default="")
|
||||
title: Mapped[str] = mapped_column(String(256))
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
desc: Mapped[str] = mapped_column(Text, default="")
|
||||
desc_en: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class Office(Base):
|
||||
__tablename__ = "offices"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
city: Mapped[str] = mapped_column(String(64))
|
||||
city_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
address: Mapped[str] = mapped_column(Text, default="")
|
||||
address_en: Mapped[str] = mapped_column(Text, default="")
|
||||
hours: Mapped[str] = mapped_column(String(128), default="")
|
||||
hours_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
|
||||
|
||||
class GalleryImage(Base):
|
||||
__tablename__ = "gallery_images"
|
||||
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
src: Mapped[str] = mapped_column(Text, default="")
|
||||
alt: Mapped[str] = mapped_column(Text, default="")
|
||||
alt_en: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class StatusLabel(Base):
|
||||
"""برچسب فارسی وضعیت پروژه — key: done | progress."""
|
||||
|
||||
__tablename__ = "status_labels"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
key: Mapped[str] = mapped_column(String(16), unique=True, index=True)
|
||||
label: Mapped[str] = mapped_column(String(64))
|
||||
label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
|
||||
|
||||
class ContactSectionContent(Base):
|
||||
"""بخش فرم تماس — رکورد یگانه."""
|
||||
|
||||
__tablename__ = "contact_section"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
label: Mapped[str] = mapped_column(String(64), default="")
|
||||
label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
title: Mapped[str] = mapped_column(String(256), default="")
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
lead: Mapped[str] = mapped_column(Text, default="")
|
||||
lead_en: Mapped[str] = mapped_column(Text, default="")
|
||||
address_label: Mapped[str] = mapped_column(String(64), default="")
|
||||
address_label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
phone_label: Mapped[str] = mapped_column(String(64), default="")
|
||||
phone_label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
email_label: Mapped[str] = mapped_column(String(64), default="")
|
||||
email_label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
name_label: Mapped[str] = mapped_column(String(64), default="")
|
||||
name_label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
name_placeholder: Mapped[str] = mapped_column(String(128), default="")
|
||||
name_placeholder_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
phone_field_label: Mapped[str] = mapped_column(String(64), default="")
|
||||
phone_field_label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
phone_placeholder: Mapped[str] = mapped_column(String(64), default="")
|
||||
phone_placeholder_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
note_label: Mapped[str] = mapped_column(String(64), default="")
|
||||
note_label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
note_optional_label: Mapped[str] = mapped_column(String(64), default="")
|
||||
note_optional_label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
note_placeholder: Mapped[str] = mapped_column(String(256), default="")
|
||||
note_placeholder_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
submit_label: Mapped[str] = mapped_column(String(128), default="")
|
||||
submit_label_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
sending_label: Mapped[str] = mapped_column(String(64), default="")
|
||||
sending_label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
success_title: Mapped[str] = mapped_column(String(256), default="")
|
||||
success_title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
success_text: Mapped[str] = mapped_column(Text, default="")
|
||||
success_text_en: Mapped[str] = mapped_column(Text, default="")
|
||||
success_button_label: Mapped[str] = mapped_column(String(128), default="")
|
||||
success_button_label_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
|
||||
|
||||
class NewsletterSectionContent(Base):
|
||||
"""بخش خبرنامه — رکورد یگانه."""
|
||||
|
||||
__tablename__ = "newsletter"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(256), default="")
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
lead: Mapped[str] = mapped_column(Text, default="")
|
||||
lead_en: Mapped[str] = mapped_column(Text, default="")
|
||||
placeholder: Mapped[str] = mapped_column(String(128), default="")
|
||||
placeholder_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
button_label: Mapped[str] = mapped_column(String(64), default="")
|
||||
button_label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
sending_label: Mapped[str] = mapped_column(String(64), default="")
|
||||
sending_label_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
success_text: Mapped[str] = mapped_column(String(256), default="")
|
||||
success_text_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
|
||||
|
||||
class FooterContent(Base):
|
||||
"""متنهای فوتر — رکورد یگانه."""
|
||||
|
||||
__tablename__ = "footer"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
about_text: Mapped[str] = mapped_column(Text, default="")
|
||||
about_text_en: Mapped[str] = mapped_column(Text, default="")
|
||||
pages_heading: Mapped[str] = mapped_column(String(64), default="")
|
||||
pages_heading_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
services_heading: Mapped[str] = mapped_column(String(64), default="")
|
||||
services_heading_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
contact_heading: Mapped[str] = mapped_column(String(64), default="")
|
||||
contact_heading_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
copyright: Mapped[str] = mapped_column(String(256), default="")
|
||||
copyright_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
tagline: Mapped[str] = mapped_column(String(256), default="")
|
||||
tagline_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
socials: Mapped[list] = mapped_column(JSON, default=list) # [{label, href, icon}]
|
||||
socials_en: Mapped[list] = mapped_column(JSON, default=list) # [{label, href, icon}] انگلیسی
|
||||
|
||||
|
||||
class SeoMeta(Base):
|
||||
"""عنوان و توضیح سئوی هر صفحه — page_key: home / about / services / ..."""
|
||||
|
||||
__tablename__ = "seo_meta"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
page_key: Mapped[str] = mapped_column(String(32), unique=True, index=True)
|
||||
title: Mapped[str] = mapped_column(String(256), default="")
|
||||
title_en: Mapped[str] = mapped_column(String(256), default="")
|
||||
description: Mapped[str] = mapped_column(Text, default="")
|
||||
description_en: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class ContactMessage(Base):
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""محدودسازی نرخ درخواست — پنجرهٔ لغزان درونحافظهای.
|
||||
|
||||
برای ورود ادمین (بر پایه تلاش ناموفق) و فرمهای عمومی (بر پایه هر ارسال)
|
||||
استفاده میشود. شمارندهها در حافظهٔ همین پروسهاند — با ریاستارت پاک میشوند؛
|
||||
به همین دلیل uvicorn تککارگر نگه داشته شده است.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
from fastapi import HTTPException, Request, status
|
||||
|
||||
|
||||
def client_ip(request: Request) -> str:
|
||||
"""IP واقعی کلاینت — پشت Traefik از X-Forwarded-For خوانده میشود
|
||||
(uvicorn با --proxy-headers هم client.host را درست میکند)."""
|
||||
forwarded = request.headers.get("x-forwarded-for")
|
||||
if forwarded:
|
||||
return forwarded.split(",")[0].strip()
|
||||
return request.client.host if request.client else "unknown"
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
"""پنجرهٔ لغزان بر پایه کلید (عملاً IP) — رویدادها پس از پنجره منقضی میشوند."""
|
||||
|
||||
def __init__(self, max_events: int, window_seconds: int, message: str):
|
||||
self.max_events = max_events
|
||||
self.window_seconds = window_seconds
|
||||
self.message = message
|
||||
self._events: dict[str, list[float]] = {}
|
||||
|
||||
def _recent(self, key: str, now: float) -> list[float]:
|
||||
recent = [t for t in self._events.get(key, []) if now - t < self.window_seconds]
|
||||
self._events[key] = recent
|
||||
return recent
|
||||
|
||||
def _reject(self, recent: list[float]) -> None:
|
||||
now = time.monotonic()
|
||||
retry_after = max(1, int(self.window_seconds - (now - recent[0])))
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail=self.message,
|
||||
headers={"Retry-After": str(retry_after)},
|
||||
)
|
||||
|
||||
def hit(self, request: Request) -> None:
|
||||
"""یک رویداد ثبت میکند؛ اگر سهمیه کلید پر باشد 429 برمیگرداند."""
|
||||
key = client_ip(request)
|
||||
now = time.monotonic()
|
||||
recent = self._recent(key, now)
|
||||
if len(recent) >= self.max_events:
|
||||
self._reject(recent)
|
||||
self._events.setdefault(key, []).append(now)
|
||||
|
||||
def clear(self, request: Request) -> None:
|
||||
self._events.pop(client_ip(request), None)
|
||||
|
||||
|
||||
# ورود ادمین: ۵ تلاش ناموفق در ۱۵ دقیقه — فقط شکستها شمرده میشوند
|
||||
_failed: dict[str, list[float]] = {}
|
||||
LOGIN_MAX_FAILED_ATTEMPTS = 5
|
||||
LOGIN_WINDOW_SECONDS = 15 * 60
|
||||
|
||||
|
||||
def ensure_allowed(request: Request) -> None:
|
||||
"""اگر این IP سهمیه تلاش ناموفقش پر شده باشد، درخواست با 429 رد میشود."""
|
||||
key = client_ip(request)
|
||||
now = time.monotonic()
|
||||
recent = [t for t in _failed.get(key, []) if now - t < LOGIN_WINDOW_SECONDS]
|
||||
_failed[key] = recent
|
||||
if len(recent) >= LOGIN_MAX_FAILED_ATTEMPTS:
|
||||
retry_after = max(1, int(LOGIN_WINDOW_SECONDS - (now - recent[0])))
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="تلاشهای ناموفق زیاد است — بعداً دوباره امتحان کنید",
|
||||
headers={"Retry-After": str(retry_after)},
|
||||
)
|
||||
|
||||
|
||||
def record_failure(request: Request) -> None:
|
||||
_failed.setdefault(client_ip(request), []).append(time.monotonic())
|
||||
|
||||
|
||||
def clear(request: Request) -> None:
|
||||
"""با ورود موفق، تاریخچه تلاشهای ناموفق IP پاک میشود."""
|
||||
_failed.pop(client_ip(request), None)
|
||||
|
||||
|
||||
# فرم تماس: ۵ ارسال در ۱۵ دقیقه برای هر IP
|
||||
contact_limiter = RateLimiter(
|
||||
max_events=5,
|
||||
window_seconds=15 * 60,
|
||||
message="تعداد پیامهای ارسالی زیاد است — کمی بعد دوباره امتحان کنید",
|
||||
)
|
||||
|
||||
# خبرنامه: ۳ عضویت در ساعت برای هر IP
|
||||
newsletter_limiter = RateLimiter(
|
||||
max_events=3,
|
||||
window_seconds=60 * 60,
|
||||
message="تعداد درخواستها زیاد است — کمی بعد دوباره امتحان کنید",
|
||||
)
|
||||
@@ -0,0 +1,135 @@
|
||||
"""پاکسازی ورودیهای غنی در زمان ذخیره.
|
||||
|
||||
بدنه مقالهها سند TipTap (ProseMirror) است و فرانتاند همان را با
|
||||
renderToHTMLString به HTML تبدیل و مستقیم تزریق میکند؛ متن گرهها در آن
|
||||
مسیر escape میشود، اما آدرسهای href/src عیناً وارد HTML میشوند — پس
|
||||
اسکیمهای خطرناک (javascript: و data: و ...) باید در سمت سرور حذف شوند.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
# اسکیمهای مجاز برای href/src — مسیرهای نسبی و لنگر هم بیاسکیماند و میگذرند
|
||||
SAFE_URL_SCHEMES = {"http", "https", "mailto", "tel"}
|
||||
URL_ATTRS = ("href", "src")
|
||||
|
||||
|
||||
def _clean_url(value: Any) -> str | None:
|
||||
"""آدرس امن را برمیگرداند؛ در غیر این صورت None (مشخصه حذف میشود)."""
|
||||
if not isinstance(value, str):
|
||||
return value if value is not None else None
|
||||
stripped = value.strip().replace("\n", "").replace("\r", "").replace("\t", "")
|
||||
if not stripped:
|
||||
return None
|
||||
parsed = urlparse(stripped)
|
||||
if parsed.scheme and parsed.scheme.lower() not in SAFE_URL_SCHEMES:
|
||||
return None
|
||||
return stripped
|
||||
|
||||
|
||||
def _is_junk_paragraph(node: Any) -> bool:
|
||||
"""پاراگراف خالی یا فقط نویسهٔ خنثی (nbsp/فاصله) — داخل نقلقول حذف میشود."""
|
||||
if not isinstance(node, dict) or node.get("type") != "paragraph":
|
||||
return False
|
||||
content = node.get("content") or []
|
||||
if not content:
|
||||
return True
|
||||
return all(
|
||||
isinstance(item, dict)
|
||||
and item.get("type") == "text"
|
||||
and not str(item.get("text", "")).replace("\xa0", " ").strip()
|
||||
for item in content
|
||||
)
|
||||
|
||||
|
||||
def _lift_lists_flat(node: Any) -> list[Any]:
|
||||
"""گره را به دنبالهای از گرههای نرمال تبدیل میکند — نقلقولهای داخل
|
||||
آیتم فهرست به سطح خود فهرست میآیند تا خط مسی همهٔ نقلقولها یکخط شود."""
|
||||
if not isinstance(node, dict):
|
||||
return [node]
|
||||
flat_content: list[Any] = []
|
||||
for child in node.get("content") or []:
|
||||
flat_content.extend(_lift_lists_flat(child))
|
||||
node["content"] = flat_content
|
||||
|
||||
if node.get("type") not in ("bulletList", "orderedList"):
|
||||
return [node]
|
||||
|
||||
rebuilt: list[Any] = []
|
||||
pending_items: list[Any] = []
|
||||
for li in node.get("content") or []:
|
||||
if not isinstance(li, dict) or li.get("type") != "listItem":
|
||||
pending_items.append(li)
|
||||
continue
|
||||
parts: list[list[Any]] = [[]]
|
||||
for child in li.get("content") or []:
|
||||
if isinstance(child, dict) and child.get("type") == "blockquote":
|
||||
parts.append(child)
|
||||
parts.append([])
|
||||
else:
|
||||
parts[-1].append(child)
|
||||
if len(parts) == 1:
|
||||
pending_items.append(li)
|
||||
continue
|
||||
if parts[0]:
|
||||
li["content"] = parts[0]
|
||||
pending_items.append(li)
|
||||
for part in parts[1:]:
|
||||
if isinstance(part, dict) and part.get("type") == "blockquote":
|
||||
if pending_items:
|
||||
rebuilt.append({**node, "content": pending_items})
|
||||
pending_items = []
|
||||
rebuilt.append(part)
|
||||
else:
|
||||
pending_items.extend(part)
|
||||
if pending_items:
|
||||
rebuilt.append({**node, "content": pending_items})
|
||||
return rebuilt
|
||||
|
||||
|
||||
def _lift_doc(doc: Any) -> Any:
|
||||
lifted = _lift_lists_flat(doc)
|
||||
if len(lifted) == 1 and isinstance(lifted[0], dict) and lifted[0].get("type") == "doc":
|
||||
return lifted[0]
|
||||
content: list[Any] = []
|
||||
for part in lifted:
|
||||
if isinstance(part, dict) and part.get("type") == "doc":
|
||||
content.extend(part.get("content") or [])
|
||||
else:
|
||||
content.append(part)
|
||||
return {"type": "doc", "content": content}
|
||||
|
||||
|
||||
def _walk(node: Any) -> Any:
|
||||
if isinstance(node, list):
|
||||
return [_walk(item) for item in node]
|
||||
if not isinstance(node, dict):
|
||||
return node
|
||||
cleaned: dict[str, Any] = {}
|
||||
for key, value in node.items():
|
||||
if key == "attrs" and isinstance(value, dict):
|
||||
attrs = dict(value)
|
||||
for attr in URL_ATTRS:
|
||||
if attr in attrs:
|
||||
cleaned_url = _clean_url(attrs[attr])
|
||||
if cleaned_url is None:
|
||||
attrs.pop(attr, None)
|
||||
else:
|
||||
attrs[attr] = cleaned_url
|
||||
cleaned[key] = attrs
|
||||
else:
|
||||
cleaned[key] = _walk(value)
|
||||
# داخل نقلقول: پاراگرافهای خالی/نویسهٔ خنثی حذف — وگرنه خط خالی اضافه رندر میشود
|
||||
if cleaned.get("type") == "blockquote" and isinstance(cleaned.get("content"), list):
|
||||
cleaned["content"] = [c for c in cleaned["content"] if not _is_junk_paragraph(c)]
|
||||
return cleaned
|
||||
|
||||
|
||||
def sanitize_doc(doc: Any) -> Any:
|
||||
"""سند TipTap را درجا پاک میکند (سایر ساختارها دستنخورده برمیگردند)."""
|
||||
if not isinstance(doc, dict):
|
||||
return doc
|
||||
walked = _walk(doc)
|
||||
return _lift_doc(walked)
|
||||
@@ -1,7 +1,9 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, EmailStr, Field
|
||||
from pydantic import BaseModel, ConfigDict, EmailStr, Field, create_model, field_validator
|
||||
|
||||
from .sanitize import sanitize_doc
|
||||
|
||||
# ---------- پایه ----------
|
||||
|
||||
@@ -10,25 +12,33 @@ class ORMModel(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
# فیلدهای *_en معادل انگلیسیاند؛ خالی بودنشان یعنی «بدون ترجمه».
|
||||
|
||||
|
||||
# ---------- خروجیها ----------
|
||||
|
||||
|
||||
class BrandOut(ORMModel):
|
||||
id: int
|
||||
name: str
|
||||
name_en: str = ""
|
||||
logo: str
|
||||
logo_en: str = ""
|
||||
hero: str
|
||||
contact_bg: str
|
||||
phone: str
|
||||
phone_href: str
|
||||
email: str
|
||||
address: str
|
||||
address_en: str = ""
|
||||
|
||||
|
||||
class ServiceOut(ORMModel):
|
||||
id: int
|
||||
title: str
|
||||
title_en: str = ""
|
||||
desc: str
|
||||
desc_en: str = ""
|
||||
icon: str
|
||||
|
||||
|
||||
@@ -36,56 +46,106 @@ class ProjectOut(ORMModel):
|
||||
id: int
|
||||
slug: str
|
||||
title: str
|
||||
title_en: str = ""
|
||||
location: str
|
||||
location_en: str = ""
|
||||
year: str
|
||||
year_en: str = ""
|
||||
status: str
|
||||
image: str
|
||||
gallery: list[str]
|
||||
area: str
|
||||
area_en: str = ""
|
||||
floors: str
|
||||
units: str
|
||||
floors_en: str = ""
|
||||
land_area: str = ""
|
||||
pilot_floors: str = ""
|
||||
units_residential: str = ""
|
||||
units_commercial: str = ""
|
||||
units_office: str = ""
|
||||
client: str
|
||||
client_en: str = ""
|
||||
project_type: str = ""
|
||||
project_type_en: str = ""
|
||||
usage: str = ""
|
||||
usage_en: str = ""
|
||||
summary: str
|
||||
summary_en: str = ""
|
||||
body: list[str]
|
||||
body_en: Optional[list[str]] = None
|
||||
|
||||
|
||||
class ArticleOut(ORMModel):
|
||||
id: int
|
||||
slug: str
|
||||
author_id: int | None = None
|
||||
title: str
|
||||
title_en: str = ""
|
||||
date: str
|
||||
date_en: str = ""
|
||||
category: str
|
||||
category_en: str = ""
|
||||
image: str
|
||||
image_alt: str = ""
|
||||
image_title: str = ""
|
||||
read: str
|
||||
read_en: str = ""
|
||||
excerpt: str
|
||||
body: list[str]
|
||||
excerpt_en: str = ""
|
||||
body: dict
|
||||
body_en: Optional[dict] = None
|
||||
# پرسشوپاسخهای پایان مقاله — [{question, answer}]؛ سطرهای قدیمی ممکن است NULL باشند
|
||||
faqs: Optional[list[dict]] = None
|
||||
faqs_en: Optional[list[dict]] = None
|
||||
status: str
|
||||
seo_keyphrase: str
|
||||
# نام نویسنده و توضیحات سئوی اختصاصی — سربرگ مقاله، تگ description و اسکیمای Article
|
||||
author: str = ""
|
||||
meta_description: str = ""
|
||||
meta_description_en: str = ""
|
||||
slug_en: str = ""
|
||||
seo_keyphrase_en: str = ""
|
||||
author_en: str = ""
|
||||
tags: list[str] = []
|
||||
tags_en: list[str] = []
|
||||
|
||||
|
||||
class TestimonialOut(ORMModel):
|
||||
id: int
|
||||
name: str
|
||||
name_en: str = ""
|
||||
role: str
|
||||
role_en: str = ""
|
||||
quote: str
|
||||
quote_en: str = ""
|
||||
|
||||
|
||||
class FaqOut(ORMModel):
|
||||
id: int
|
||||
question: str
|
||||
question_en: str = ""
|
||||
answer: str
|
||||
answer_en: str = ""
|
||||
|
||||
|
||||
class TeamMemberOut(ORMModel):
|
||||
id: int
|
||||
name: str
|
||||
name_en: str = ""
|
||||
role: str
|
||||
role_en: str = ""
|
||||
bio: str
|
||||
bio_en: str = ""
|
||||
|
||||
|
||||
class TimelineItemOut(ORMModel):
|
||||
id: int
|
||||
year: str
|
||||
year_en: str = ""
|
||||
title: str
|
||||
title_en: str = ""
|
||||
desc: str
|
||||
desc_en: str = ""
|
||||
image: str
|
||||
|
||||
|
||||
@@ -93,23 +153,239 @@ class StatOut(ORMModel):
|
||||
id: int
|
||||
value: int
|
||||
suffix: str
|
||||
suffix_en: str = ""
|
||||
label: str
|
||||
label_en: str = ""
|
||||
|
||||
|
||||
class WhyUsItemOut(ORMModel):
|
||||
id: int
|
||||
title: str
|
||||
title_en: str = ""
|
||||
desc: str
|
||||
desc_en: str = ""
|
||||
|
||||
|
||||
class BeforeAfterOut(ORMModel):
|
||||
id: int
|
||||
title: str
|
||||
title_en: str = ""
|
||||
lead: str
|
||||
lead_en: str = ""
|
||||
before: str
|
||||
after: str
|
||||
before_label: str
|
||||
before_label_en: str = ""
|
||||
after_label: str
|
||||
after_label_en: str = ""
|
||||
|
||||
|
||||
class NavItemOut(ORMModel):
|
||||
id: int
|
||||
label: str
|
||||
label_en: str = ""
|
||||
href: str
|
||||
|
||||
|
||||
class HeroOut(ORMModel):
|
||||
id: int
|
||||
kicker: str
|
||||
kicker_en: str = ""
|
||||
title: str
|
||||
title_en: str = ""
|
||||
title_highlight: str
|
||||
title_highlight_en: str = ""
|
||||
subtitle: str
|
||||
subtitle_en: str = ""
|
||||
badge_value: str
|
||||
badge_value_en: str = ""
|
||||
badge_label: str
|
||||
badge_label_en: str = ""
|
||||
cta_primary_label: str
|
||||
cta_primary_label_en: str = ""
|
||||
cta_primary_href: str
|
||||
cta_secondary_label: str
|
||||
cta_secondary_label_en: str = ""
|
||||
cta_secondary_href: str
|
||||
scroll_label: str
|
||||
scroll_label_en: str = ""
|
||||
|
||||
|
||||
class StoryOut(ORMModel):
|
||||
id: int
|
||||
title: str
|
||||
title_en: str = ""
|
||||
paragraphs: list[str]
|
||||
paragraphs_en: Optional[list[str]] = None
|
||||
quote: str
|
||||
quote_en: str = ""
|
||||
quote_author: str
|
||||
quote_author_en: str = ""
|
||||
stat1_value: str
|
||||
stat1_value_en: str = ""
|
||||
stat1_label: str
|
||||
stat1_label_en: str = ""
|
||||
stat2_value: str
|
||||
stat2_value_en: str = ""
|
||||
stat2_label: str
|
||||
stat2_label_en: str = ""
|
||||
link_label: str
|
||||
link_label_en: str = ""
|
||||
link_href: str
|
||||
bento: list[dict]
|
||||
bento_en: Optional[list[dict]] = None
|
||||
|
||||
|
||||
class SectionHeadingOut(ORMModel):
|
||||
id: int
|
||||
key: str
|
||||
label: str
|
||||
label_en: str = ""
|
||||
title: str
|
||||
title_en: str = ""
|
||||
lead: str
|
||||
lead_en: str = ""
|
||||
image: str
|
||||
cta_label: str
|
||||
cta_label_en: str = ""
|
||||
cta_href: str
|
||||
|
||||
|
||||
class PageHeroOut(ORMModel):
|
||||
id: int
|
||||
key: str
|
||||
title: str
|
||||
title_en: str = ""
|
||||
lead: str
|
||||
lead_en: str = ""
|
||||
image: str
|
||||
|
||||
|
||||
class InvestmentModelOut(ORMModel):
|
||||
id: int
|
||||
title: str
|
||||
title_en: str = ""
|
||||
desc: str
|
||||
desc_en: str = ""
|
||||
points: list[str]
|
||||
points_en: Optional[list[str]] = None
|
||||
|
||||
|
||||
class ProcessStepOut(ORMModel):
|
||||
id: int
|
||||
step: str
|
||||
step_en: str = ""
|
||||
title: str
|
||||
title_en: str = ""
|
||||
desc: str
|
||||
desc_en: str = ""
|
||||
|
||||
|
||||
class OfficeOut(ORMModel):
|
||||
id: int
|
||||
city: str
|
||||
city_en: str = ""
|
||||
address: str
|
||||
address_en: str = ""
|
||||
hours: str
|
||||
hours_en: str = ""
|
||||
|
||||
|
||||
class GalleryImageOut(ORMModel):
|
||||
id: int
|
||||
src: str
|
||||
alt: str
|
||||
alt_en: str = ""
|
||||
|
||||
|
||||
class StatusLabelOut(ORMModel):
|
||||
id: int
|
||||
key: str
|
||||
label: str
|
||||
label_en: str = ""
|
||||
|
||||
|
||||
class ContactSectionOut(ORMModel):
|
||||
id: int
|
||||
label: str
|
||||
label_en: str = ""
|
||||
title: str
|
||||
title_en: str = ""
|
||||
lead: str
|
||||
lead_en: str = ""
|
||||
address_label: str
|
||||
address_label_en: str = ""
|
||||
phone_label: str
|
||||
phone_label_en: str = ""
|
||||
email_label: str
|
||||
email_label_en: str = ""
|
||||
name_label: str
|
||||
name_label_en: str = ""
|
||||
name_placeholder: str
|
||||
name_placeholder_en: str = ""
|
||||
phone_field_label: str
|
||||
phone_field_label_en: str = ""
|
||||
phone_placeholder: str
|
||||
phone_placeholder_en: str = ""
|
||||
note_label: str
|
||||
note_label_en: str = ""
|
||||
note_optional_label: str
|
||||
note_optional_label_en: str = ""
|
||||
note_placeholder: str
|
||||
note_placeholder_en: str = ""
|
||||
submit_label: str
|
||||
submit_label_en: str = ""
|
||||
sending_label: str
|
||||
sending_label_en: str = ""
|
||||
success_title: str
|
||||
success_title_en: str = ""
|
||||
success_text: str
|
||||
success_text_en: str = ""
|
||||
success_button_label: str
|
||||
success_button_label_en: str = ""
|
||||
|
||||
|
||||
class NewsletterOut(ORMModel):
|
||||
id: int
|
||||
title: str
|
||||
title_en: str = ""
|
||||
lead: str
|
||||
lead_en: str = ""
|
||||
placeholder: str
|
||||
placeholder_en: str = ""
|
||||
button_label: str
|
||||
button_label_en: str = ""
|
||||
sending_label: str
|
||||
sending_label_en: str = ""
|
||||
success_text: str
|
||||
success_text_en: str = ""
|
||||
|
||||
|
||||
class FooterOut(ORMModel):
|
||||
id: int
|
||||
about_text: str
|
||||
about_text_en: str = ""
|
||||
pages_heading: str
|
||||
pages_heading_en: str = ""
|
||||
services_heading: str
|
||||
services_heading_en: str = ""
|
||||
contact_heading: str
|
||||
contact_heading_en: str = ""
|
||||
copyright: str
|
||||
copyright_en: str = ""
|
||||
tagline: str
|
||||
tagline_en: str = ""
|
||||
socials: list[dict]
|
||||
socials_en: Optional[list[dict]] = None
|
||||
|
||||
|
||||
class SeoMetaOut(ORMModel):
|
||||
id: int
|
||||
page_key: str
|
||||
title: str
|
||||
title_en: str = ""
|
||||
description: str
|
||||
description_en: str = ""
|
||||
|
||||
|
||||
class ContactMessageOut(ORMModel):
|
||||
@@ -135,10 +411,14 @@ class ContactIn(BaseModel):
|
||||
name: str = Field(min_length=3, max_length=128)
|
||||
phone: str = Field(pattern=r"^[\d۰-۹+\-\s]{8,15}$")
|
||||
note: str = Field(default="", max_length=2000)
|
||||
# honeypot — فیلد پنهان فرم؛ کاربر واقعی هرگز آن را پر نمیکند
|
||||
website: str = Field(default="", max_length=128)
|
||||
|
||||
|
||||
class NewsletterIn(BaseModel):
|
||||
email: EmailStr
|
||||
# honeypot — فیلد پنهان فرم؛ کاربر واقعی هرگز آن را پر نمیکند
|
||||
website: str = Field(default="", max_length=128)
|
||||
|
||||
|
||||
# ---------- ورودیهای پنل مدیریت ----------
|
||||
@@ -152,95 +432,449 @@ class LoginIn(BaseModel):
|
||||
class TokenOut(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
role: str = "admin"
|
||||
|
||||
|
||||
class ChangePasswordIn(BaseModel):
|
||||
current_password: str
|
||||
new_password: str = Field(min_length=8, max_length=128)
|
||||
|
||||
|
||||
class BrandIn(BaseModel):
|
||||
name: str = ""
|
||||
name_en: str = ""
|
||||
logo: str = ""
|
||||
logo_en: str = ""
|
||||
hero: str = ""
|
||||
contact_bg: str = ""
|
||||
phone: str = ""
|
||||
phone_href: str = ""
|
||||
email: str = ""
|
||||
address: str = ""
|
||||
address_en: str = ""
|
||||
|
||||
|
||||
class ServiceIn(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=256)
|
||||
title_en: str = ""
|
||||
desc: str = ""
|
||||
desc_en: str = ""
|
||||
icon: str = "draft"
|
||||
|
||||
|
||||
class ProjectIn(BaseModel):
|
||||
slug: str = Field(min_length=1, max_length=128)
|
||||
title: str = Field(min_length=1, max_length=256)
|
||||
title_en: str = ""
|
||||
location: str = ""
|
||||
location_en: str = ""
|
||||
year: str = ""
|
||||
year_en: str = ""
|
||||
status: Literal["done", "progress"] = "done"
|
||||
land_area: str = ""
|
||||
pilot_floors: str = ""
|
||||
units_residential: str = ""
|
||||
units_commercial: str = ""
|
||||
units_office: str = ""
|
||||
project_type: str = ""
|
||||
project_type_en: str = ""
|
||||
usage: str = ""
|
||||
usage_en: str = ""
|
||||
image: str = ""
|
||||
gallery: list[str] = []
|
||||
area: str = ""
|
||||
area_en: str = ""
|
||||
floors: str = ""
|
||||
units: str = ""
|
||||
floors_en: str = ""
|
||||
client: str = ""
|
||||
client_en: str = ""
|
||||
summary: str = ""
|
||||
summary_en: str = ""
|
||||
body: list[str] = []
|
||||
body_en: list[str] = []
|
||||
|
||||
|
||||
EMPTY_DOC = {"type": "doc", "content": [{"type": "paragraph"}]}
|
||||
|
||||
|
||||
def validate_doc_body(value: object) -> dict:
|
||||
"""بدنه مقاله باید یک سند TipTap (ProseMirror) معتبر از نظر ساختار باشد و
|
||||
آدرسهای href/src آن به اسکیمهای امن محدود شوند."""
|
||||
if not value:
|
||||
return dict(EMPTY_DOC)
|
||||
if not isinstance(value, dict) or value.get("type") != "doc" or not isinstance(value.get("content"), list):
|
||||
raise ValueError("body must be a TipTap doc: {type: 'doc', content: [...]}")
|
||||
return sanitize_doc(value)
|
||||
|
||||
|
||||
class ArticleIn(BaseModel):
|
||||
slug: str = Field(min_length=1, max_length=128)
|
||||
title: str = Field(min_length=1, max_length=256)
|
||||
title_en: str = ""
|
||||
date: str = ""
|
||||
date_en: str = ""
|
||||
category: str = ""
|
||||
category_en: str = ""
|
||||
image: str = ""
|
||||
image_alt: str = ""
|
||||
image_title: str = ""
|
||||
read: str = ""
|
||||
read_en: str = ""
|
||||
excerpt: str = ""
|
||||
body: list[str] = []
|
||||
excerpt_en: str = ""
|
||||
body: dict = Field(default_factory=lambda: dict(EMPTY_DOC))
|
||||
body_en: dict = Field(default_factory=lambda: dict(EMPTY_DOC))
|
||||
faqs: list[dict] = []
|
||||
faqs_en: list[dict] = []
|
||||
status: Literal["draft", "published"] = "draft"
|
||||
seo_keyphrase: str = Field(default="", max_length=128)
|
||||
seo_keyphrase_en: str = Field(default="", max_length=128)
|
||||
slug_en: str = Field(default="", max_length=128)
|
||||
author: str = Field(default="", max_length=128)
|
||||
author_en: str = Field(default="", max_length=128)
|
||||
tags: list[str] = []
|
||||
tags_en: list[str] = []
|
||||
meta_description: str = ""
|
||||
meta_description_en: str = ""
|
||||
_validate_body = field_validator("body")(validate_doc_body)
|
||||
_validate_body_en = field_validator("body_en")(validate_doc_body)
|
||||
|
||||
|
||||
class TestimonialIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=128)
|
||||
name_en: str = ""
|
||||
role: str = ""
|
||||
role_en: str = ""
|
||||
quote: str = ""
|
||||
quote_en: str = ""
|
||||
|
||||
|
||||
class FaqIn(BaseModel):
|
||||
question: str = Field(min_length=1)
|
||||
question_en: str = ""
|
||||
answer: str = ""
|
||||
answer_en: str = ""
|
||||
|
||||
|
||||
class TeamMemberIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=128)
|
||||
name_en: str = ""
|
||||
role: str = ""
|
||||
role_en: str = ""
|
||||
bio: str = ""
|
||||
bio_en: str = ""
|
||||
|
||||
|
||||
class TimelineItemIn(BaseModel):
|
||||
year: str = Field(min_length=1, max_length=32)
|
||||
year_en: str = ""
|
||||
title: str = Field(min_length=1, max_length=256)
|
||||
title_en: str = ""
|
||||
desc: str = ""
|
||||
desc_en: str = ""
|
||||
image: str = ""
|
||||
|
||||
|
||||
class StatIn(BaseModel):
|
||||
value: int
|
||||
suffix: str = ""
|
||||
suffix_en: str = ""
|
||||
label: str = Field(min_length=1, max_length=128)
|
||||
label_en: str = ""
|
||||
|
||||
|
||||
class WhyUsItemIn(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=256)
|
||||
title_en: str = ""
|
||||
desc: str = ""
|
||||
desc_en: str = ""
|
||||
|
||||
|
||||
class BeforeAfterIn(BaseModel):
|
||||
title: str = ""
|
||||
title_en: str = ""
|
||||
lead: str = ""
|
||||
lead_en: str = ""
|
||||
before: str = ""
|
||||
after: str = ""
|
||||
before_label: str = ""
|
||||
before_label_en: str = ""
|
||||
after_label: str = ""
|
||||
after_label_en: str = ""
|
||||
|
||||
|
||||
class NavItemIn(BaseModel):
|
||||
label: str = Field(min_length=1, max_length=64)
|
||||
label_en: str = ""
|
||||
href: str = Field(min_length=1, max_length=128)
|
||||
|
||||
|
||||
class HeroIn(BaseModel):
|
||||
kicker: str = ""
|
||||
kicker_en: str = ""
|
||||
title: str = ""
|
||||
title_en: str = ""
|
||||
title_highlight: str = ""
|
||||
title_highlight_en: str = ""
|
||||
subtitle: str = ""
|
||||
subtitle_en: str = ""
|
||||
badge_value: str = ""
|
||||
badge_value_en: str = ""
|
||||
badge_label: str = ""
|
||||
badge_label_en: str = ""
|
||||
cta_primary_label: str = ""
|
||||
cta_primary_label_en: str = ""
|
||||
cta_primary_href: str = ""
|
||||
cta_secondary_label: str = ""
|
||||
cta_secondary_label_en: str = ""
|
||||
cta_secondary_href: str = ""
|
||||
scroll_label: str = ""
|
||||
scroll_label_en: str = ""
|
||||
|
||||
|
||||
class StoryIn(BaseModel):
|
||||
title: str = ""
|
||||
title_en: str = ""
|
||||
paragraphs: list[str] = []
|
||||
paragraphs_en: list[str] = []
|
||||
quote: str = ""
|
||||
quote_en: str = ""
|
||||
quote_author: str = ""
|
||||
quote_author_en: str = ""
|
||||
stat1_value: str = ""
|
||||
stat1_value_en: str = ""
|
||||
stat1_label: str = ""
|
||||
stat1_label_en: str = ""
|
||||
stat2_value: str = ""
|
||||
stat2_value_en: str = ""
|
||||
stat2_label: str = ""
|
||||
stat2_label_en: str = ""
|
||||
link_label: str = ""
|
||||
link_label_en: str = ""
|
||||
link_href: str = ""
|
||||
bento: list[dict] = []
|
||||
bento_en: list[dict] = []
|
||||
|
||||
|
||||
class SectionHeadingIn(BaseModel):
|
||||
key: str = Field(min_length=1, max_length=64)
|
||||
label: str = ""
|
||||
label_en: str = ""
|
||||
title: str = ""
|
||||
title_en: str = ""
|
||||
lead: str = ""
|
||||
lead_en: str = ""
|
||||
image: str = ""
|
||||
cta_label: str = ""
|
||||
cta_label_en: str = ""
|
||||
cta_href: str = ""
|
||||
|
||||
|
||||
class PageHeroIn(BaseModel):
|
||||
key: str = Field(min_length=1, max_length=32)
|
||||
title: str = ""
|
||||
title_en: str = ""
|
||||
lead: str = ""
|
||||
lead_en: str = ""
|
||||
image: str = ""
|
||||
|
||||
|
||||
class InvestmentModelIn(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=256)
|
||||
title_en: str = ""
|
||||
desc: str = ""
|
||||
desc_en: str = ""
|
||||
points: list[str] = []
|
||||
points_en: list[str] = []
|
||||
|
||||
|
||||
class ProcessStepIn(BaseModel):
|
||||
step: str = ""
|
||||
step_en: str = ""
|
||||
title: str = Field(min_length=1, max_length=256)
|
||||
title_en: str = ""
|
||||
desc: str = ""
|
||||
desc_en: str = ""
|
||||
|
||||
|
||||
class OfficeIn(BaseModel):
|
||||
city: str = Field(min_length=1, max_length=64)
|
||||
city_en: str = ""
|
||||
address: str = ""
|
||||
address_en: str = ""
|
||||
hours: str = ""
|
||||
hours_en: str = ""
|
||||
|
||||
|
||||
class GalleryImageIn(BaseModel):
|
||||
src: str = ""
|
||||
alt: str = ""
|
||||
alt_en: str = ""
|
||||
|
||||
|
||||
class StatusLabelIn(BaseModel):
|
||||
key: str = Field(min_length=1, max_length=16)
|
||||
label: str = Field(min_length=1, max_length=64)
|
||||
label_en: str = ""
|
||||
|
||||
|
||||
class ContactSectionIn(BaseModel):
|
||||
label: str = ""
|
||||
label_en: str = ""
|
||||
title: str = ""
|
||||
title_en: str = ""
|
||||
lead: str = ""
|
||||
lead_en: str = ""
|
||||
address_label: str = ""
|
||||
address_label_en: str = ""
|
||||
phone_label: str = ""
|
||||
phone_label_en: str = ""
|
||||
email_label: str = ""
|
||||
email_label_en: str = ""
|
||||
name_label: str = ""
|
||||
name_label_en: str = ""
|
||||
name_placeholder: str = ""
|
||||
name_placeholder_en: str = ""
|
||||
phone_field_label: str = ""
|
||||
phone_field_label_en: str = ""
|
||||
phone_placeholder: str = ""
|
||||
phone_placeholder_en: str = ""
|
||||
note_label: str = ""
|
||||
note_label_en: str = ""
|
||||
note_optional_label: str = ""
|
||||
note_optional_label_en: str = ""
|
||||
note_placeholder: str = ""
|
||||
note_placeholder_en: str = ""
|
||||
submit_label: str = ""
|
||||
submit_label_en: str = ""
|
||||
sending_label: str = ""
|
||||
sending_label_en: str = ""
|
||||
success_title: str = ""
|
||||
success_title_en: str = ""
|
||||
success_text: str = ""
|
||||
success_text_en: str = ""
|
||||
success_button_label: str = ""
|
||||
success_button_label_en: str = ""
|
||||
|
||||
|
||||
class NewsletterSectionIn(BaseModel):
|
||||
title: str = ""
|
||||
title_en: str = ""
|
||||
lead: str = ""
|
||||
lead_en: str = ""
|
||||
placeholder: str = ""
|
||||
placeholder_en: str = ""
|
||||
button_label: str = ""
|
||||
button_label_en: str = ""
|
||||
sending_label: str = ""
|
||||
sending_label_en: str = ""
|
||||
success_text: str = ""
|
||||
success_text_en: str = ""
|
||||
|
||||
|
||||
class FooterIn(BaseModel):
|
||||
about_text: str = ""
|
||||
about_text_en: str = ""
|
||||
pages_heading: str = ""
|
||||
pages_heading_en: str = ""
|
||||
services_heading: str = ""
|
||||
services_heading_en: str = ""
|
||||
contact_heading: str = ""
|
||||
contact_heading_en: str = ""
|
||||
copyright: str = ""
|
||||
copyright_en: str = ""
|
||||
tagline: str = ""
|
||||
tagline_en: str = ""
|
||||
socials: list[dict] = []
|
||||
socials_en: list[dict] = []
|
||||
|
||||
|
||||
class SeoMetaIn(BaseModel):
|
||||
page_key: str = Field(min_length=1, max_length=32)
|
||||
title: str = ""
|
||||
title_en: str = ""
|
||||
description: str = ""
|
||||
description_en: str = ""
|
||||
|
||||
|
||||
class SeoMetaPatch(BaseModel):
|
||||
page_key: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
title_en: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
description_en: Optional[str] = None
|
||||
|
||||
|
||||
class MessageReadIn(BaseModel):
|
||||
is_read: bool = True
|
||||
|
||||
|
||||
# ---------- اسکیماهای PATCH (ویرایش جزئی — همه فیلدها اختیاری) ----------
|
||||
|
||||
|
||||
def _make_patch(name: str, model_cls: type[BaseModel]) -> type[BaseModel]:
|
||||
"""از اسکیمای ورودی، اسکیمای PATCH میسازد؛ فیلدهای ارسالنشده دستنخورده میمانند."""
|
||||
fields = {fname: (Optional[f.annotation], None) for fname, f in model_cls.model_fields.items()}
|
||||
return create_model(name, **fields)
|
||||
|
||||
|
||||
BrandPatch = _make_patch("BrandPatch", BrandIn)
|
||||
ServicePatch = _make_patch("ServicePatch", ServiceIn)
|
||||
ProjectPatch = _make_patch("ProjectPatch", ProjectIn)
|
||||
class ArticlePatch(BaseModel):
|
||||
slug: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
title_en: Optional[str] = None
|
||||
date: Optional[str] = None
|
||||
date_en: Optional[str] = None
|
||||
category: Optional[str] = None
|
||||
category_en: Optional[str] = None
|
||||
image: Optional[str] = None
|
||||
image_alt: Optional[str] = None
|
||||
image_title: Optional[str] = None
|
||||
read: Optional[str] = None
|
||||
read_en: Optional[str] = None
|
||||
excerpt: Optional[str] = None
|
||||
excerpt_en: Optional[str] = None
|
||||
body: Optional[dict] = None
|
||||
body_en: Optional[dict] = None
|
||||
faqs: Optional[list[dict]] = None
|
||||
faqs_en: Optional[list[dict]] = None
|
||||
status: Optional[Literal["draft", "published"]] = None
|
||||
seo_keyphrase: Optional[str] = None
|
||||
seo_keyphrase_en: Optional[str] = None
|
||||
slug_en: Optional[str] = None
|
||||
author: Optional[str] = None
|
||||
author_en: Optional[str] = None
|
||||
tags: Optional[list[str]] = None
|
||||
tags_en: Optional[list[str]] = None
|
||||
meta_description: Optional[str] = None
|
||||
meta_description_en: Optional[str] = None
|
||||
_validate_body = field_validator("body")(validate_doc_body)
|
||||
_validate_body_en = field_validator("body_en")(validate_doc_body)
|
||||
TestimonialPatch = _make_patch("TestimonialPatch", TestimonialIn)
|
||||
FaqPatch = _make_patch("FaqPatch", FaqIn)
|
||||
TeamMemberPatch = _make_patch("TeamMemberPatch", TeamMemberIn)
|
||||
TimelineItemPatch = _make_patch("TimelineItemPatch", TimelineItemIn)
|
||||
StatPatch = _make_patch("StatPatch", StatIn)
|
||||
WhyUsItemPatch = _make_patch("WhyUsItemPatch", WhyUsItemIn)
|
||||
BeforeAfterPatch = _make_patch("BeforeAfterPatch", BeforeAfterIn)
|
||||
NavItemPatch = _make_patch("NavItemPatch", NavItemIn)
|
||||
HeroPatch = _make_patch("HeroPatch", HeroIn)
|
||||
StoryPatch = _make_patch("StoryPatch", StoryIn)
|
||||
SectionHeadingPatch = _make_patch("SectionHeadingPatch", SectionHeadingIn)
|
||||
PageHeroPatch = _make_patch("PageHeroPatch", PageHeroIn)
|
||||
InvestmentModelPatch = _make_patch("InvestmentModelPatch", InvestmentModelIn)
|
||||
ProcessStepPatch = _make_patch("ProcessStepPatch", ProcessStepIn)
|
||||
OfficePatch = _make_patch("OfficePatch", OfficeIn)
|
||||
GalleryImagePatch = _make_patch("GalleryImagePatch", GalleryImageIn)
|
||||
StatusLabelPatch = _make_patch("StatusLabelPatch", StatusLabelIn)
|
||||
ContactSectionPatch = _make_patch("ContactSectionPatch", ContactSectionIn)
|
||||
NewsletterSectionPatch = _make_patch("NewsletterSectionPatch", NewsletterSectionIn)
|
||||
FooterPatch = _make_patch("FooterPatch", FooterIn)
|
||||
|
||||
|
||||
class ReorderIn(BaseModel):
|
||||
"""ترتیب جدید آیتمهای یک مجموعه بر اساس id."""
|
||||
|
||||
ids: list[int]
|
||||
|
||||
@@ -1,16 +1,79 @@
|
||||
"""اسکریپت seed دیتابیس.
|
||||
|
||||
اجرا:
|
||||
python -m app.seed # فقط اگر دیتابیس خالی باشد
|
||||
python -m app.seed # فقط جدولهای خالی پر میشوند
|
||||
python -m app.seed --force # حذف کامل دادهها و ساخت مجدد
|
||||
|
||||
پر کردن هر جدول مستقل است: روی یک دیتابیس موجود، فقط جدولهای جدید یا خالی
|
||||
seed میشوند و دادههای قبلی دستنخورده میمانند.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from typing import Any
|
||||
|
||||
from . import models, seed_data
|
||||
from . import models, seed_data, seed_data_en
|
||||
from .auth import hash_password
|
||||
from .config import settings
|
||||
from .database import Base, SessionLocal, engine
|
||||
from .migrations import paragraphs_to_doc, run_all as run_migrations
|
||||
|
||||
# (مدل، دادههای اولیه، برچسب گزارش)
|
||||
CONTENT: list[tuple[Any, list[dict], str]] = [
|
||||
(models.Brand, [seed_data.BRAND], "برند"),
|
||||
(models.Hero, [seed_data.HERO], "هیرو صفحه اصلی"),
|
||||
(models.StorySection, [seed_data.STORY], "داستان ما"),
|
||||
(models.SectionHeadingContent, seed_data.SECTION_HEADINGS, "تیتر بخشها"),
|
||||
(models.PageHeroContent, seed_data.PAGE_HEROES, "هیرو صفحات"),
|
||||
(models.NavItem, seed_data.NAV_ITEMS, "منوی ناوبری"),
|
||||
(models.InvestmentModel, seed_data.INVESTMENT_MODELS, "مدلهای سرمایهگذاری"),
|
||||
(models.ProcessStep, seed_data.PROCESS_STEPS, "مراحل فرآیند کار"),
|
||||
(models.Office, seed_data.OFFICES, "دفاتر"),
|
||||
(models.GalleryImage, seed_data.GALLERY_IMAGES, "گالری تصاویر"),
|
||||
(models.StatusLabel, seed_data.STATUS_LABELS, "برچسب وضعیت پروژه"),
|
||||
(models.ContactSectionContent, [seed_data.CONTACT_SECTION], "بخش تماس"),
|
||||
(models.NewsletterSectionContent, [seed_data.NEWSLETTER], "خبرنامه"),
|
||||
(models.FooterContent, [seed_data.FOOTER], "فوتر"),
|
||||
(models.Service, seed_data.SERVICES, "خدمات"),
|
||||
(models.Stat, seed_data.STATS, "آمار"),
|
||||
(models.Project, seed_data.PROJECTS, "پروژهها"),
|
||||
(models.Article, seed_data.ARTICLES, "مقالات"),
|
||||
(models.Testimonial, seed_data.TESTIMONIALS, "نظرات"),
|
||||
(models.Faq, seed_data.FAQS, "سوالات متداول"),
|
||||
(models.TeamMember, seed_data.TEAM, "تیم"),
|
||||
(models.TimelineItem, seed_data.TIMELINE, "تایملاین"),
|
||||
(models.WhyUsItem, seed_data.WHY, "چرا آرامش"),
|
||||
(models.BeforeAfter, [seed_data.BEFORE_AFTER], "قبل/بعد"),
|
||||
(models.SeoMeta, seed_data.SEO_META, "سئوی صفحات"),
|
||||
]
|
||||
|
||||
# ترجمه انگلیسی همان جدولها — همترتیب با CONTENT تا با zip ادغام شود
|
||||
EN_CONTENT: list[list[dict]] = [
|
||||
[seed_data_en.BRAND],
|
||||
[seed_data_en.HERO],
|
||||
[seed_data_en.STORY],
|
||||
seed_data_en.SECTION_HEADINGS,
|
||||
seed_data_en.PAGE_HEROES,
|
||||
seed_data_en.NAV_ITEMS,
|
||||
seed_data_en.INVESTMENT_MODELS,
|
||||
seed_data_en.PROCESS_STEPS,
|
||||
seed_data_en.OFFICES,
|
||||
seed_data_en.GALLERY_IMAGES,
|
||||
seed_data_en.STATUS_LABELS,
|
||||
[seed_data_en.CONTACT_SECTION],
|
||||
[seed_data_en.NEWSLETTER],
|
||||
[seed_data_en.FOOTER],
|
||||
seed_data_en.SERVICES,
|
||||
seed_data_en.STATS,
|
||||
seed_data_en.PROJECTS,
|
||||
seed_data_en.ARTICLES,
|
||||
seed_data_en.TESTIMONIALS,
|
||||
seed_data_en.FAQS,
|
||||
seed_data_en.TEAM,
|
||||
seed_data_en.TIMELINE,
|
||||
seed_data_en.WHY,
|
||||
[seed_data_en.BEFORE_AFTER],
|
||||
seed_data_en.SEO_META,
|
||||
]
|
||||
|
||||
|
||||
def seed(force: bool = False) -> None:
|
||||
@@ -21,32 +84,22 @@ def seed(force: bool = False) -> None:
|
||||
print("جداول قبلی حذف شدند.")
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
run_migrations()
|
||||
|
||||
if not force and db.query(models.Service).count() > 0:
|
||||
print("دیتابیس قبلاً seed شده است. برای بازنشانی کامل: python -m app.seed --force")
|
||||
return
|
||||
|
||||
db.add(models.Brand(**seed_data.BRAND))
|
||||
|
||||
for item in seed_data.SERVICES:
|
||||
db.add(models.Service(**item))
|
||||
for item in seed_data.STATS:
|
||||
db.add(models.Stat(**item))
|
||||
for item in seed_data.PROJECTS:
|
||||
db.add(models.Project(**item))
|
||||
for item in seed_data.ARTICLES:
|
||||
db.add(models.Article(**item))
|
||||
for item in seed_data.TESTIMONIALS:
|
||||
db.add(models.Testimonial(**item))
|
||||
for item in seed_data.FAQS:
|
||||
db.add(models.Faq(**item))
|
||||
for item in seed_data.TEAM:
|
||||
db.add(models.TeamMember(**item))
|
||||
for item in seed_data.TIMELINE:
|
||||
db.add(models.TimelineItem(**item))
|
||||
for item in seed_data.WHY:
|
||||
db.add(models.WhyUsItem(**item))
|
||||
db.add(models.BeforeAfter(**seed_data.BEFORE_AFTER))
|
||||
for (model, rows, label), en_rows in zip(CONTENT, EN_CONTENT):
|
||||
if db.query(model).count() > 0:
|
||||
continue
|
||||
for idx, row in enumerate(rows):
|
||||
# فایل فارسی مرجع است؛ فقط فیلدهای *_en از فایل انگلیسی اضافه میشود
|
||||
payload = {**dict(en_rows[idx]), **dict(row)} if idx < len(en_rows) else dict(row)
|
||||
if hasattr(model, "position") and "position" not in payload:
|
||||
payload["position"] = idx
|
||||
# بدنه مقاله (فارسی و انگلیسی) در seed بهصورت لیست پاراگراف است — به سند تبدیل میشود
|
||||
if model is models.Article:
|
||||
for body_key in ("body", "body_en"):
|
||||
if isinstance(payload.get(body_key), list):
|
||||
payload[body_key] = paragraphs_to_doc(payload[body_key])
|
||||
db.add(model(**payload))
|
||||
|
||||
if db.query(models.AdminUser).count() == 0:
|
||||
db.add(
|
||||
@@ -59,19 +112,8 @@ def seed(force: bool = False) -> None:
|
||||
|
||||
db.commit()
|
||||
|
||||
counts = {
|
||||
"خدمات": db.query(models.Service).count(),
|
||||
"پروژهها": db.query(models.Project).count(),
|
||||
"مقالات": db.query(models.Article).count(),
|
||||
"نظرات": db.query(models.Testimonial).count(),
|
||||
"سوالات متداول": db.query(models.Faq).count(),
|
||||
"تیم": db.query(models.TeamMember).count(),
|
||||
"تایملاین": db.query(models.TimelineItem).count(),
|
||||
"آمار": db.query(models.Stat).count(),
|
||||
"چرا آرامش": db.query(models.WhyUsItem).count(),
|
||||
}
|
||||
for label, count in counts.items():
|
||||
print(f" {label}: {count} رکورد")
|
||||
for model, _, label in CONTENT:
|
||||
print(f" {label}: {db.query(model).count()} رکورد")
|
||||
print("✔ seed با موفقیت انجام شد.")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -289,3 +289,170 @@ FAQS = [
|
||||
{"question": "خدمات پس از تحویل شامل چه مواردی میشود؟", "answer": "پنج سال پشتیبانی فنی تأسیسات مکانیکی و برقی، بازدید دورهای سالانه و تضمین اجرای نما و عایقکاری."},
|
||||
{"question": "پروژهها در چه شهرهایی اجرا میشوند؟", "answer": "در حال حاضر تهران، اصفهان و سواحل شمالی کشور مناطق اصلی فعالیت ما هستند و پروژهای نیز در جزیره کیش در دست ساخت است."},
|
||||
]
|
||||
|
||||
# ---------- محتوای قبلاً هاردکدشده در فرانتاند (الان در دیتابیس) ----------
|
||||
|
||||
NAV_ITEMS = [
|
||||
{"label": "صفحه اصلی", "href": "/"},
|
||||
{"label": "درباره ما", "href": "/about"},
|
||||
{"label": "خدمات", "href": "/services"},
|
||||
{"label": "پروژهها", "href": "/projects"},
|
||||
{"label": "سرمایهگذاری", "href": "/investment"},
|
||||
{"label": "وبلاگ", "href": "/blog"},
|
||||
{"label": "سوالات متداول", "href": "/faq"},
|
||||
{"label": "تماس با ما", "href": "/contact"},
|
||||
]
|
||||
|
||||
HERO = {
|
||||
"kicker": "از سال ۱۳۸۳ — تهران، اصفهان، سواحل شمال",
|
||||
"title": "ساختمانی که آرامش را معماری میکند",
|
||||
"title_highlight": "معماری",
|
||||
"subtitle": "طراحی، ساخت و سرمایهگذاری در پروژههای مسکونی و تجاری لوکس؛ با استانداردی که در جزئیات دیده میشود و در سالها دوام میآورد.",
|
||||
"badge_value": "۴۷",
|
||||
"badge_label": "پروژه تحویلشده در بیستویک سال فعالیت حرفهای",
|
||||
"cta_primary_label": "مشاهده پروژهها",
|
||||
"cta_primary_href": "/projects",
|
||||
"cta_secondary_label": "مشاوره سرمایهگذاری",
|
||||
"cta_secondary_href": "/contact",
|
||||
"scroll_label": "اسکرول کنید",
|
||||
}
|
||||
|
||||
STORY = {
|
||||
"title": "درباره ی ما",
|
||||
"paragraphs": [
|
||||
"گروه ساختمانی آرامش با یک دفتر کوچک معماری آغاز شد و امروز یکی از مجموعههای شناختهشده ساختوساز لوکس در ایران است. در تمام این سالها یک اصل تغییر نکرده است: ساختمان باید برای زندگی ساخته شود، نه برای فروش سریع.",
|
||||
"هر پروژه با مطالعه زمین، نور، اقلیم و الگوی زندگی ساکنان آغاز میشود؛ سپس تیم طراحی، سازه و اجرا در یک فرآیند واحد آن را تا تحویل کلید پیش میبرند.",
|
||||
],
|
||||
"quote": "«ساختمان برای ما فقط آجر و بتن نیست؛ بلکه تعهدی است به کیفیت زندگی ساکنان. ما فضاهایی میسازیم که در گذر زمان ارزش و هویت خود را حفظ کنند.»",
|
||||
"quote_author": "کامران آرامش — مدیرعامل شرکت ساختمانی آرامش",
|
||||
"stat1_value": "۹۴٪",
|
||||
"stat1_label": "تحویل بهموقع پروژهها",
|
||||
"stat2_value": "۵ سال",
|
||||
"stat2_label": "پشتیبانی پس از تحویل",
|
||||
"link_label": "داستان کامل ما",
|
||||
"link_href": "/about",
|
||||
"bento": [
|
||||
{"src": IMAGES[0], "alt": "نمای برج مسکونی آرامش در تهران"},
|
||||
{"src": IMAGES[1], "alt": "آتریوم مرکزی مجتمع تجاری پارسه"},
|
||||
{"src": IMAGES[2], "alt": "ویلاهای ساختهشده در سواحل شمال"},
|
||||
{"src": IMAGES[3], "alt": "نمای شبانه برج دوقلوی نیاوران"},
|
||||
],
|
||||
}
|
||||
|
||||
SECTION_HEADINGS = [
|
||||
{"key": "services", "title": "خدمات", "lead": "از نخستین خط روی کاغذ تا تحویل کلید، مدیریت سرمایه و طراحی محوطه؛ همه مراحل در یک مجموعه و زیر یک نظام کنترل کیفیت."},
|
||||
{"key": "featured_projects", "title": "پروژههای شاخص", "lead": "کارهایی که بیشترین چیز را درباره استاندارد ما میگویند؛ چه آنهایی که تحویل شدهاند و چه آنهایی که همین امروز در حال ساختاند.", "cta_label": "همه پروژهها", "cta_href": "/projects"},
|
||||
{"key": "gallery", "title": "گالری تصاویر", "lead": "قابهایی از کارگاهها و پروژههای تحویلشده گروه ساختمانی آرامش."},
|
||||
{"key": "timeline", "title": "مسیر ما", "lead": "از یک دفتر چهارنفره تا ۴۷ پروژه. خط زمان پروژههای ما را ببینید."},
|
||||
{"key": "why_us", "title": "چرا گروه ساختمانی آرامش", "lead": "شش دلیلی که کارفرمایان و سرمایهگذاران بار دوم هم به ما برمیگردند.", "image": IMAGES[3]},
|
||||
{"key": "testimonials", "title": "نظرات مشتریان"},
|
||||
{"key": "team", "title": "تیم ما", "lead": "کسانی که تصمیمهای اصلی هر پروژه را میگیرند و پاسخگوی آن هستند."},
|
||||
{"key": "articles", "label": "وبلاگ", "title": "آخرین مقالات", "lead": "یادداشتهای تیم معماری، اجرا و سرمایهگذاری گروه ساختمانی آرامش درباره آنچه در کارگاه و بازار میگذرد.", "cta_label": "همه مقالات", "cta_href": "/blog"},
|
||||
{"key": "faq", "title": "سوالات متداول", "lead": "پاسخ کوتاه به پرتکرارترین پرسشهای سرمایهگذاران و خریداران."},
|
||||
{"key": "investment_models", "title": "مدلهای همکاری", "lead": "بسته به میزان سرمایه، افق زمانی و سطح ریسکی که میپذیرید، یکی از این سه مسیر مناسب شماست."},
|
||||
{"key": "process", "title": "فرآیند کار ما", "lead": "چهار مرحله شفاف، از نخستین جلسه تا تحویل کلید."},
|
||||
]
|
||||
|
||||
PAGE_HEROES = [
|
||||
{"key": "about", "title": "درباره ما", "lead": "گروه ساختمانی آرامش مجموعهای از معماران، مهندسان سازه و مدیران پروژه است که از سال ۱۳۸۳ در حوزه ساختوساز لوکس فعالیت میکند.", "image": IMAGES[3]},
|
||||
{"key": "services", "title": "خدمات", "lead": "هشت حوزه تخصصی که چرخه کامل یک پروژه ساختمانی را از ایده تا بهرهبرداری پوشش میدهند.", "image": IMAGES[1]},
|
||||
{"key": "projects", "title": "پروژهها", "lead": "مجموعهای از برجهای مسکونی، مراکز تجاری و ویلاهای اختصاصی؛ از پروژههای تحویلشده تا کارگاههای فعال امروز.", "image": IMAGES[0]},
|
||||
{"key": "investment", "title": "سرمایهگذاری", "lead": "سه مسیر روشن برای ورود به بازار ساختوساز لوکس، با ساختار مالی شفاف و گزارشدهی منظم.", "image": IMAGES[4]},
|
||||
{"key": "blog", "title": "وبلاگ", "lead": "یادداشتهای تیم معماری، اجرا و سرمایهگذاری گروه ساختمانی آرامش درباره آنچه در کارگاه و بازار میگذرد.", "image": IMAGES[2]},
|
||||
{"key": "faq", "title": "سوالات متداول", "lead": "پیش از تماس، شاید پاسخ پرسش شما همینجا باشد. اگر نبود، خوشحال میشویم مستقیم صحبت کنیم.", "image": IMAGES[1]},
|
||||
{"key": "contact", "title": "تماس با ما", "lead": "برای مشاوره ساخت، سرمایهگذاری یا بازدید از پروژهها، تیم ما در سه شهر آماده پاسخگویی است.", "image": IMAGES[1]},
|
||||
]
|
||||
|
||||
INVESTMENT_MODELS = [
|
||||
{
|
||||
"title": "مشارکت در ساخت",
|
||||
"desc": "مالک زمین و گروه ساختمانی آرامش در سود پروژه شریک میشوند؛ اجرا، مجوزها و فروش بر عهده ماست.",
|
||||
"points": ["ارزیابی رایگان زمین", "قرارداد شفاف با ضمانت اجرا", "گزارش ماهانه پیشرفت"],
|
||||
},
|
||||
{
|
||||
"title": "صندوق پروژهمحور",
|
||||
"desc": "سرمایهگذاری روی یک پروژه مشخص با واحدهای قابل خرید و بازدهی محاسبهشده در پایان دوره.",
|
||||
"points": ["حداقل دوره ۲۴ ماه", "گزارش ارزشگذاری فصلی", "امکان انتقال واحد سرمایه"],
|
||||
},
|
||||
{
|
||||
"title": "پیشخرید واحد",
|
||||
"desc": "خرید واحد مسکونی یا تجاری در مراحل ابتدایی ساخت با قیمت پیش از تکمیل و پرداخت مرحلهای.",
|
||||
"points": ["پرداخت مرحلهای متناسب با پیشرفت", "امکان شخصیسازی پلان", "تضمین زمان تحویل"],
|
||||
},
|
||||
]
|
||||
|
||||
PROCESS_STEPS = [
|
||||
{"step": "۰۱", "title": "مطالعه و امکانسنجی", "desc": "بررسی زمین، ضوابط شهری و تحلیل بازدهی اقتصادی پروژه."},
|
||||
{"step": "۰۲", "title": "طراحی و فاز اجرایی", "desc": "کانسپت معماری، طراحی سازه و تأسیسات و تهیه نقشههای اجرایی."},
|
||||
{"step": "۰۳", "title": "اجرا و کنترل کیفیت", "desc": "ساخت با نظارت مستمر، گزارش ماهانه پیشرفت و کنترل هزینه."},
|
||||
{"step": "۰۴", "title": "تحویل و پشتیبانی", "desc": "تحویل کلید، آموزش بهرهبرداری و پنج سال پشتیبانی فنی."},
|
||||
]
|
||||
|
||||
OFFICES = [
|
||||
{"city": "تهران", "address": "خیابان ولیعصر، برج آرامش، طبقه هجدهم", "hours": "شنبه تا چهارشنبه، ۹ تا ۱۸"},
|
||||
{"city": "اصفهان", "address": "خیابان چهارباغ بالا، مجتمع پارسه، طبقه ششم", "hours": "شنبه تا چهارشنبه، ۹ تا ۱۷"},
|
||||
{"city": "نوشهر", "address": "بلوار دریا، دفتر پروژه دریاکنار", "hours": "شنبه تا پنجشنبه، ۱۰ تا ۱۶"},
|
||||
]
|
||||
|
||||
GALLERY_IMAGES = [
|
||||
{"src": IMAGES[0], "alt": "تصویری از پروژههای گروه ساختمانی آرامش، شماره ۱"},
|
||||
{"src": IMAGES[1], "alt": "تصویری از پروژههای گروه ساختمانی آرامش، شماره ۲"},
|
||||
{"src": IMAGES[2], "alt": "تصویری از پروژههای گروه ساختمانی آرامش، شماره ۳"},
|
||||
{"src": IMAGES[3], "alt": "تصویری از پروژههای گروه ساختمانی آرامش، شماره ۴"},
|
||||
{"src": IMAGES[4], "alt": "تصویری از پروژههای گروه ساختمانی آرامش، شماره ۵"},
|
||||
{"src": IMAGES[1], "alt": "تصویری از پروژههای گروه ساختمانی آرامش، شماره ۶"},
|
||||
]
|
||||
|
||||
STATUS_LABELS = [
|
||||
{"key": "done", "label": "انجام شده"},
|
||||
{"key": "progress", "label": "در حال انجام"},
|
||||
]
|
||||
|
||||
CONTACT_SECTION = {
|
||||
"label": "تماس با ما",
|
||||
"title": "پروژهتان را با ما در میان بگذارید",
|
||||
"lead": "شمارهتان را بگذارید؛ کارشناس ما در کمتر از یک روز کاری برای یک جلسه مشاوره رایگان تماس میگیرد.",
|
||||
"address_label": "دفتر مرکزی",
|
||||
"phone_label": "تلفن",
|
||||
"email_label": "ایمیل",
|
||||
"name_label": "نام",
|
||||
"name_placeholder": "نام و نام خانوادگی",
|
||||
"phone_field_label": "شماره تلفن",
|
||||
"phone_placeholder": "09xx xxx xxxx",
|
||||
"note_label": "توضیحات",
|
||||
"note_optional_label": "(اختیاری)",
|
||||
"note_placeholder": "درباره پروژه یا درخواست خود بنویسید…",
|
||||
"submit_label": "ارسال درخواست مشاوره",
|
||||
"sending_label": "در حال ارسال…",
|
||||
"success_title": "درخواست شما ثبت شد",
|
||||
"success_text": "از اعتماد شما سپاسگزاریم. کارشناسان ما بهزودی با شما تماس میگیرند.",
|
||||
"success_button_label": "ثبت درخواست جدید",
|
||||
}
|
||||
|
||||
NEWSLETTER = {
|
||||
"title": "خبرنامه گروه ساختمانی آرامش",
|
||||
"lead": "هر ماه یک ایمیل: پروژههای جدید، فرصتهای سرمایهگذاری و یادداشتهای تیم معماری.",
|
||||
"placeholder": "نشانی ایمیل شما",
|
||||
"button_label": "عضویت",
|
||||
"sending_label": "در حال ارسال…",
|
||||
"success_text": "عضویت شما ثبت شد.",
|
||||
}
|
||||
|
||||
FOOTER = {
|
||||
"about_text": "گروه ساختمانی آرامش از سال ۱۳۸۳ ساختمانهایی میسازد که قرار است چند نسل در آنها زندگی کنند؛ معماری آرام، اجرای دقیق و سرمایهگذاری شفاف.",
|
||||
"pages_heading": "صفحات",
|
||||
"services_heading": "خدمات",
|
||||
"contact_heading": "ارتباط با ما",
|
||||
"copyright": "© ۱۴۰۳ گروه ساختمانی آرامش — تمامی حقوق محفوظ است.",
|
||||
"tagline": "طراحی و ساخت با دقتِ معماری",
|
||||
"socials": [
|
||||
{"label": "اینستاگرام", "href": "#", "icon": "instagram"},
|
||||
{"label": "لینکدین", "href": "#", "icon": "linkedin"},
|
||||
{"label": "تلگرام", "href": "#", "icon": "telegram"},
|
||||
],
|
||||
}
|
||||
|
||||
SEO_META = [
|
||||
{"page_key": key, "title": "", "description": ""}
|
||||
for key in ["home", "about", "services", "projects", "investment", "blog", "faq", "contact"]
|
||||
]
|
||||
|
||||
@@ -0,0 +1,580 @@
|
||||
"""ترجمه انگلیسی دادههای اولیه سایت — ساختار یکبهیک با seed_data.py.
|
||||
|
||||
هر فهرست همطول و همترتیب با معادل فارسی خود است تا seed.py بتواند با zip
|
||||
ادغام کند و backfill مهاجرت بتواند سطرهای موجود را پر کند. فقط فیلدهای
|
||||
`*_en` ملاک ادغاماند؛ کلیدهای همنام با فارسی (مثل title یا body) صرفاً
|
||||
برای خواندن راحتتر مترجم آمدهاند و در ادغام نادیده گرفته میشوند.
|
||||
فیلدهای تطبیق (slug، key، page_key، src) عیناً مقدار فارسیاند.
|
||||
"""
|
||||
|
||||
from .seed_data import IMAGES
|
||||
|
||||
BRAND = {
|
||||
"name": "گروه ساختمانی آرامش",
|
||||
"name_en": "Aramesh Construction Group",
|
||||
"address": "تهران، خیابان ولیعصر، برج آرامش، طبقه هجدهم",
|
||||
"address_en": "Valiasr St., Aramesh Tower, 18th Floor, Tehran, Iran",
|
||||
}
|
||||
|
||||
SERVICES = [
|
||||
{"title": "طراحی معماری", "title_en": "Architectural Design", "desc": "خلق فرمهای معاصر با نگاه ایرانی؛ از کانسپت اولیه تا نقشههای اجرایی و جزئیات نما.", "desc_en": "Contemporary forms with an Iranian eye — from the first concept to construction drawings and facade details.", "icon": "draft"},
|
||||
{"title": "ساخت برجهای مسکونی", "title_en": "Residential Towers", "desc": "اجرای برجهای بلندمرتبه با استانداردهای سازهای بینالمللی و کیفیت تحویل بینقص.", "desc_en": "High-rise execution built on international structural standards and a flawless handover quality.", "icon": "tower"},
|
||||
{"title": "مجتمعهای تجاری", "title_en": "Commercial Complexes", "desc": "طراحی و ساخت مراکز تجاری با مطالعه دقیق جریان مخاطب و بازدهی بلندمدت سرمایه.", "desc_en": "Retail destinations designed and built around precise visitor-flow studies and long-term returns.", "icon": "mall"},
|
||||
{"title": "ویلاسازی", "title_en": "Private Villas", "desc": "ویلاهای اختصاصی همنشین با طبیعت؛ محرمانگی، نور طبیعی و مصالح ماندگار.", "desc_en": "Bespoke villas in harmony with nature — privacy, natural light and enduring materials.", "icon": "villa"},
|
||||
{"title": "بازسازی", "title_en": "Renovation", "desc": "بازآفرینی ساختمانهای موجود با ارتقای سازه، نما و تجربه زندگی در فضا.", "desc_en": "Reimagining existing buildings with upgraded structure, facades and living experience.", "icon": "renew"},
|
||||
{"title": "مدیریت پروژه", "title_en": "Project Management", "desc": "کنترل همزمان زمان، هزینه و کیفیت با گزارشدهی شفاف در تمام مراحل ساخت.", "desc_en": "Controlling time, cost and quality in parallel with transparent reporting at every stage.", "icon": "manage"},
|
||||
{"title": "سرمایهگذاری ساختمانی", "title_en": "Real Estate Investment", "desc": "ساختارهای مشارکت شفاف، ارزیابی ریسک و طراحی سبد ملکی متناسب با سرمایه شما.", "desc_en": "Transparent partnership structures, risk assessment and property portfolios tailored to your capital.", "icon": "invest"},
|
||||
{"title": "محوطهسازی و لنداسکیپ", "title_en": "Landscape Design", "desc": "طراحی حیاط، بام سبز و مسیرهای دسترسی؛ ادامه معماری در فضای باز پروژه.", "desc_en": "Courtyards, green roofs and pathways — architecture carried on into the open air.", "icon": "landscape"},
|
||||
]
|
||||
|
||||
STATS = [
|
||||
{"value": 21, "suffix": "+", "suffix_en": "+", "label": "سال تجربه ساخت", "label_en": "Years of building experience"},
|
||||
{"value": 47, "suffix": "", "suffix_en": "", "label": "پروژه تحویلشده", "label_en": "Projects delivered"},
|
||||
{"value": 860, "suffix": "هزار", "suffix_en": "K", "label": "مترمربع زیربنا", "label_en": "Square meters built"},
|
||||
{"value": 1200, "suffix": "+", "suffix_en": "+", "label": "خانواده ساکن", "label_en": "Resident families"},
|
||||
]
|
||||
|
||||
PROJECTS = [
|
||||
{
|
||||
"slug": "aramesh-elahieh",
|
||||
"title": "برج آرامش الهیه",
|
||||
"title_en": "Aramesh Elahieh Tower",
|
||||
"location": "تهران، الهیه",
|
||||
"location_en": "Elahieh, Tehran",
|
||||
"year": "۱۴۰۲",
|
||||
"year_en": "2023",
|
||||
"area": "۲۴٬۰۰۰ متر مربع",
|
||||
"area_en": "24,000 m²",
|
||||
"floors": "۱۸ طبقه",
|
||||
"floors_en": "18 floors",
|
||||
"units": "۵۶ واحد",
|
||||
"units_en": "56 units",
|
||||
"client": "سرمایهگذاری خصوصی",
|
||||
"client_en": "Private investor",
|
||||
"summary": "یک برج مسکونی لوکس با نمای سنگ تراورتن و پوسته دوپوستهای که مصرف انرژی را تا ۳۵ درصد کاهش داده است.",
|
||||
"summary_en": "A luxury residential tower with travertine cladding and a double-skin facade that cuts energy use by up to 35%.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"Aramesh Elahieh Tower was designed on a site with a natural northward slope — an opportunity that placed the lobby, pool and shared spaces on three different levels and gave every unit an unobstructed view of the city.",
|
||||
"The outer shell combines light travertine stone with floor-to-ceiling triple-glazed windows. Copper-toned vertical louvers break the direct summer sun while letting winter light pour in.",
|
||||
"Construction was completed in thirty-two months, and every unit was sold before handover.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"slug": "parseh-mall",
|
||||
"title": "مجتمع تجاری پارسه",
|
||||
"title_en": "Parseh Shopping Mall",
|
||||
"location": "اصفهان، مرکز شهر",
|
||||
"location_en": "City center, Isfahan",
|
||||
"year": "۱۴۰۱",
|
||||
"year_en": "2022",
|
||||
"area": "۳۸٬۵۰۰ متر مربع",
|
||||
"area_en": "38,500 m²",
|
||||
"floors": "۷ طبقه",
|
||||
"floors_en": "7 floors",
|
||||
"units": "۱۴۰ واحد تجاری",
|
||||
"units_en": "140 retail units",
|
||||
"client": "گروه سرمایهگذاری پارسه",
|
||||
"client_en": "Parseh Investment Group",
|
||||
"summary": "مرکز تجاری با آتریوم مرکزی و نورگیر سقفی که جریان مخاطب را بهصورت طبیعی در همه ترازها توزیع میکند.",
|
||||
"summary_en": "A retail center with a central atrium and roof light-wells that naturally distribute visitor flow across every level.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"A visitor-behavior study before design showed that the shortest vertical path was the key to the complex's commercial success — so the central atrium with diagonal escalators sits at the heart of the plan.",
|
||||
"Low-E glazing on the roof light-well carries daylight down to level B2 and measurably cuts artificial lighting consumption.",
|
||||
"The complex opened two months ahead of the contractual schedule.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"slug": "daryakenar-villas",
|
||||
"title": "ویلاهای دریاکنار",
|
||||
"title_en": "Daryakenar Villas",
|
||||
"location": "مازندران، نوشهر",
|
||||
"location_en": "Nowshahr, Mazandaran",
|
||||
"year": "۱۴۰۰",
|
||||
"year_en": "2021",
|
||||
"area": "۹٬۲۰۰ متر مربع",
|
||||
"area_en": "9,200 m²",
|
||||
"floors": "۲ طبقه",
|
||||
"floors_en": "2 floors",
|
||||
"units": "۱۲ ویلا",
|
||||
"units_en": "12 villas",
|
||||
"client": "مجموعه خصوصی دریاکنار",
|
||||
"client_en": "Daryakenar Private Estate",
|
||||
"summary": "دوازده ویلای اختصاصی با چیدمان شانهای که برای هر واحد، دید مستقیم به دریا و محرمانگی کامل فراهم میکند.",
|
||||
"summary_en": "Twelve bespoke villas in a comb layout that gives each unit a direct sea view and complete privacy.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"The comb layout of the villas is the result of dozens of view-angle studies: no villa overlooks another, and all of them open onto the sea.",
|
||||
"The materials answer the humid northern climate: thermowood, exposed concrete and salt-resistant coatings on the facade metals.",
|
||||
"The landscape was designed with native plants to keep annual irrigation demand to a minimum.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"slug": "niavaran-twins",
|
||||
"title": "برج دوقلوی نیاوران",
|
||||
"title_en": "Niavaran Twin Towers",
|
||||
"location": "تهران، نیاوران",
|
||||
"location_en": "Niavaran, Tehran",
|
||||
"year": "۱۳۹۹",
|
||||
"year_en": "2020",
|
||||
"area": "۳۱٬۷۰۰ متر مربع",
|
||||
"area_en": "31,700 m²",
|
||||
"floors": "۲۰ طبقه",
|
||||
"floors_en": "20 floors",
|
||||
"units": "۸۰ واحد",
|
||||
"units_en": "80 units",
|
||||
"client": "مشارکت با مالکان زمین",
|
||||
"client_en": "Partnership with landowners",
|
||||
"summary": "دو برج همسان با پادست مشترک که فضاهای رفاهی و پارکینگها را در یک تراز واحد ادغام میکند.",
|
||||
"summary_en": "Two identical towers on a shared podium that merges amenities and parking into a single level.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"The two towers rest on a shared podium — a decision that let the amenities, event hall and parking be shared between the buildings and reduced the footprint on the garden.",
|
||||
"The structure uses shear walls with post-tensioned slabs so the interior spans stay free and the floor plans remain customizable.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"slug": "kish-garden-tower",
|
||||
"title": "باغبرج کیش",
|
||||
"title_en": "Kish Garden Tower",
|
||||
"location": "کیش، مروارید",
|
||||
"location_en": "Marvàrid, Kish Island",
|
||||
"year": "۱۴۰۵ (پیشبینی)",
|
||||
"year_en": "2026 (expected)",
|
||||
"area": "۱۸٬۴۰۰ متر مربع",
|
||||
"area_en": "18,400 m²",
|
||||
"floors": "۱۴ طبقه",
|
||||
"floors_en": "14 floors",
|
||||
"units": "۶۲ واحد اقامتی",
|
||||
"units_en": "62 hospitality units",
|
||||
"client": "صندوق پروژهمحور آرامش",
|
||||
"client_en": "Aramesh Project Fund",
|
||||
"summary": "باغبرجی اقامتی با تراسهای سبز پیوسته که در حال ساخت است؛ پیشرفت فیزیکی پروژه ۴۸ درصد.",
|
||||
"summary_en": "A hospitality garden tower with continuous green terraces, currently under construction — 48% complete.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"The continuous green terraces form a living skin that measurably lowers the facade surface temperature in the island's hot climate.",
|
||||
"The structure has reached the ninth floor, and facade installation has begun on the southern elevation.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"slug": "aramesh-business-center",
|
||||
"title": "مرکز تجاری آرامش تهران",
|
||||
"title_en": "Aramesh Business Center Tehran",
|
||||
"location": "تهران، سعادتآباد",
|
||||
"location_en": "Saadatabad, Tehran",
|
||||
"year": "۱۴۰۶ (پیشبینی)",
|
||||
"year_en": "2027 (expected)",
|
||||
"area": "۲۷٬۳۰۰ متر مربع",
|
||||
"area_en": "27,300 m²",
|
||||
"floors": "۱۲ طبقه",
|
||||
"floors_en": "12 floors",
|
||||
"units": "۹۰ دفتر اداری",
|
||||
"units_en": "90 offices",
|
||||
"client": "مشارکت با هلدینگ آرامش",
|
||||
"client_en": "Partnership with Aramesh Holding",
|
||||
"summary": "مجتمع اداری-تجاری با هسته مرکزی شفاف و لابی دوبلکس؛ در مرحله اجرای سفتکاری.",
|
||||
"summary_en": "An office-retail complex with a transparent central core and double-height lobby; currently in structural works.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"The space planning was built around flexible offices: every level can be divided into two, three or six independent units.",
|
||||
"Mechanical installations are progressing in parallel with the structural works to shorten the overall timeline.",
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
BEFORE_AFTER = {
|
||||
"title": "از کانسپت تا خلق واقعیت",
|
||||
"title_en": "From Concept to Reality",
|
||||
"lead": "دستگیره را بکشید و ببینید نمای ساختمانی چگونه از حالت اولیه به فرم مدرن تبدیل میشود.",
|
||||
"lead_en": "Drag the handle to see how a building facade turns from a raw concept into its modern form.",
|
||||
"before_label": "کانسپت اولیه",
|
||||
"before_label_en": "Initial concept",
|
||||
"after_label": "پروژه تکمیلشده",
|
||||
"after_label_en": "Completed project",
|
||||
}
|
||||
|
||||
TIMELINE = [
|
||||
{"year": "۱۳۸۳", "year_en": "2004", "title": "آغاز مسیر", "title_en": "The Journey Begins", "desc": "تأسیس دفتر معماری آرامش با تیمی چهارنفره و نخستین پروژه بازسازی در تهران.", "desc_en": "Aramesh Architecture Office is founded by a four-person team, taking on its first renovation project in Tehran.", "image": IMAGES[2]},
|
||||
{"year": "۱۳۸۵", "year_en": "2006", "title": "نخستین ساخت مستقل", "title_en": "First Independent Build", "desc": "تحویل اولین ساختمان مسکونی هفتطبقه؛ آغاز همکاری با پیمانکاران سازهای بزرگ.", "desc_en": "Delivery of the first seven-story residential building and the start of partnerships with major structural contractors.", "image": IMAGES[0]},
|
||||
{"year": "۱۳۸۷", "year_en": "2008", "title": "ورود به بازار تجاری", "title_en": "Entering Commercial Market", "desc": "طراحی و اجرای اولین مجتمع تجاری با رویکرد بازدهی سرمایه و جریان مخاطب.", "desc_en": "Design and execution of the first commercial complex, driven by capital returns and visitor flow.", "image": IMAGES[1]},
|
||||
{"year": "۱۳۸۹", "year_en": "2010", "title": "استاندارد بینالمللی", "title_en": "International Standards", "desc": "استقرار نظام کنترل کیفیت و دریافت گواهینامههای مدیریت پروژه.", "desc_en": "A quality-control system is established and project-management certifications are earned.", "image": IMAGES[4]},
|
||||
{"year": "۱۳۹۵", "year_en": "2016", "title": "بلندمرتبهسازی", "title_en": "Going High-Rise", "desc": "آغاز ساخت نخستین برج بیستطبقه شرکت در شمال تهران.", "desc_en": "Construction begins on the company's first twenty-story tower in northern Tehran.", "image": IMAGES[3]},
|
||||
{"year": "۱۴۰۳", "year_en": "Today", "title": "گروه ساختمانی آرامش امروز", "title_en": "Aramesh Construction Group Today", "desc": "پرتفوی ۴۷ پروژه، دفاتر در سه شهر و صندوق سرمایهگذاری ساختمانی اختصاصی.", "desc_en": "A portfolio of 47 projects, offices in three cities and a dedicated real estate investment fund.", "image": IMAGES[0]},
|
||||
]
|
||||
|
||||
WHY = [
|
||||
{"title": "کیفیت بدون مصالحه", "title_en": "Quality Without Compromise", "desc": "انتخاب مصالح و مجریان بر اساس ماندگاری چنددههای، نه سریعترین تحویل.", "desc_en": "Materials and subcontractors are chosen for decades of durability, not the fastest delivery."},
|
||||
{"title": "شفافیت مالی کامل", "title_en": "Full Financial Transparency", "desc": "گزارش ماهانه هزینهها و پیشرفت فیزیکی برای همه شرکای پروژه.", "desc_en": "Monthly reporting of costs and physical progress for every project partner."},
|
||||
{"title": "تحویل بهموقع", "title_en": "On-Time Delivery", "desc": "۹۴٪ پروژههای ما در بازه زمانی قراردادی یا زودتر تحویل داده شدهاند.", "desc_en": "94% of our projects have been delivered on or ahead of the contractual schedule."},
|
||||
{"title": "طراحی اختصاصی", "title_en": "Bespoke Design", "desc": "هیچ نقشهای دو بار اجرا نمیشود؛ هر پروژه هویت معماری خودش را دارد.", "desc_en": "No drawing is ever executed twice — every project has its own architectural identity."},
|
||||
{"title": "خدمات پس از تحویل", "title_en": "After-Sales Service", "desc": "پنج سال پشتیبانی فنی و نگهداری تأسیسات پس از تحویل کلید.", "desc_en": "Five years of technical support and building-systems maintenance after handover."},
|
||||
{"title": "پایداری و انرژی", "title_en": "Sustainability & Energy", "desc": "طراحی پوسته و تأسیسات با هدف کاهش مصرف انرژی تا ۳۵ درصد.", "desc_en": "Envelope and building systems designed to cut energy consumption by up to 35%."},
|
||||
]
|
||||
|
||||
TESTIMONIALS = [
|
||||
{"name": "مهندس سارا کیانی", "name_en": "Sara Kiani", "role": "سرمایهگذار پروژه پارسه", "role_en": "Investor, Parseh Mall project", "quote": "گزارشهای ماهانه گروه ساختمانی آرامش آنقدر دقیق بود که هیچوقت نیاز نشد نگران سرمایهام باشم. پروژه دو ماه زودتر از موعد به بهرهبرداری رسید.", "quote_en": "Aramesh's monthly reports were so precise that I never had to worry about my investment. The project opened two months ahead of schedule."},
|
||||
{"name": "دکتر امیرحسین راد", "name_en": "Dr. Amirhossein Rad", "role": "ساکن برج الهیه", "role_en": "Resident, Elahieh Tower", "quote": "کیفیت اجرا در جزئیاتی دیده میشود که معمولاً کسی به آنها فکر نمیکند؛ از عایق صوتی پنجرهها تا نور غیرمستقیم راهروها.", "quote_en": "The build quality shows in details nobody usually thinks about — from the acoustic insulation of the windows to the indirect lighting in the corridors."},
|
||||
{"name": "مریم دلاور", "name_en": "Maryam Delavar", "role": "مدیر مجموعه ویلاهای دریاکنار", "role_en": "Manager, Daryakenar Villas", "quote": "همکاری با تیم طراحی، تجربهای واقعاً حرفهای بود. ایدههای ما را شنیدند و به زبان معماری ترجمه کردند.", "quote_en": "Working with the design team was a truly professional experience. They listened to our ideas and translated them into architecture."},
|
||||
]
|
||||
|
||||
TEAM = [
|
||||
{"name": "کامران آرامش", "name_en": "Kamran Aramesh", "role": "بنیانگذار و مدیرعامل", "role_en": "Founder & CEO", "bio": "بیش از سه دهه تجربه در ساخت بلندمرتبه.", "bio_en": "Three decades of high-rise construction experience."},
|
||||
{"name": "نگار شریفی", "name_en": "Negar Sharifi", "role": "مدیر ارشد طراحی", "role_en": "Chief Design Officer", "bio": "معمار ارشد، فارغالتحصیل دانشگاه تهران و میلان.", "bio_en": "Senior architect, graduate of the University of Tehran and Milan."},
|
||||
{"name": "بهزاد مرادی", "name_en": "Behzad Moradi", "role": "مدیر اجرایی پروژهها", "role_en": "Director of Project Execution", "bio": "مسئول کنترل کیفیت و زمانبندی همه کارگاهها.", "bio_en": "Responsible for quality control and scheduling across all sites."},
|
||||
{"name": "الهام نیکآیین", "name_en": "Elham Nikaein", "role": "مدیر سرمایهگذاری", "role_en": "Investment Director", "bio": "طراح ساختارهای مشارکت و تحلیل بازدهی ملکی.", "bio_en": "Designs partnership structures and analyzes property returns."},
|
||||
]
|
||||
|
||||
ARTICLES = [
|
||||
{
|
||||
"slug": "natural-light",
|
||||
"title": "معماری آرام: چرا نور طبیعی گرانترین مصالح ساختمان است؟",
|
||||
"title_en": "Quiet Architecture: Why Is Natural Light the Most Expensive Building Material?",
|
||||
"date": "۲۴ مرداد ۱۴۰۳",
|
||||
"date_en": "August 14, 2024",
|
||||
"category": "معماری",
|
||||
"category_en": "Architecture",
|
||||
"read": "۶ دقیقه",
|
||||
"read_en": "6 min read",
|
||||
"excerpt": "نور طبیعی نهتنها کیفیت زندگی در فضا را تعیین میکند، بلکه مستقیماً بر مصرف انرژی و ارزش بلندمدت ملک اثر میگذارد.",
|
||||
"excerpt_en": "Natural light not only defines the quality of life in a space — it directly affects energy consumption and the long-term value of the property.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"In the construction market, a unit's value is usually measured in square meters. But our experience over the past twenty years shows that the quality of light is more decisive than a few extra meters.",
|
||||
"Building orientation, bay depth and floor-to-ceiling height are the three main variables of natural light. The decision on all three is made before the first plan is drawn — and is hardly reversible afterwards.",
|
||||
"In Aramesh Elahieh Tower, rotating the building mass 12 degrees off north added two hours of useful winter light to the units — a cost-free decision with a decades-long effect.",
|
||||
"Our advice for choosing a unit is simple: visit at mid-morning and late afternoon, and judge the quality of light at exactly the hours you are actually home.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"slug": "real-estate-portfolio",
|
||||
"title": "راهنمای انتخاب سبد سرمایهگذاری ملکی در بازار امروز",
|
||||
"title_en": "A Guide to Building a Real Estate Portfolio in Today's Market",
|
||||
"date": "۱۰ مرداد ۱۴۰۳",
|
||||
"date_en": "July 31, 2024",
|
||||
"category": "سرمایهگذاری",
|
||||
"category_en": "Investment",
|
||||
"read": "۹ دقیقه",
|
||||
"read_en": "9 min read",
|
||||
"excerpt": "سه معیار کلیدی برای تشکیل سبدی متعادل از دارایی ملکی، بر اساس افق زمانی و سطح ریسک شما.",
|
||||
"excerpt_en": "Three key criteria for building a balanced property portfolio, based on your time horizon and risk appetite.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"A balanced property portfolio mixes assets with different liquidity — not all capital in one long-term project, not all in ready units.",
|
||||
"Time horizon is the first criterion. If your plan is shorter than two years, pre-purchasing in a project that has just started is a risky choice.",
|
||||
"The second criterion is reporting transparency. Without monthly reports of physical and financial progress, assessing the state of your capital is practically impossible.",
|
||||
"The third criterion is diversity of use. A residential–commercial mix measurably reduces the volatility of portfolio returns in downturns.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"slug": "facade-quality",
|
||||
"title": "پنج نکته فنی که کیفیت نما را پس از ده سال مشخص میکند",
|
||||
"title_en": "Five Technical Details That Reveal Facade Quality After Ten Years",
|
||||
"date": "۲۸ تیر ۱۴۰۳",
|
||||
"date_en": "July 18, 2024",
|
||||
"category": "اجرا",
|
||||
"category_en": "Construction",
|
||||
"read": "۵ دقیقه",
|
||||
"read_en": "5 min read",
|
||||
"excerpt": "نمای ساختمان در سال اول زیبا به نظر میرسد؛ تفاوت کیفیت اجرا در سال دهم آشکار میشود.",
|
||||
"excerpt_en": "A facade looks beautiful in its first year; the difference in workmanship shows in its tenth.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"Mechanical fixings of facade stone matter more than the stone itself. Adhesive fixing has a short life in Iran's hot-and-cold climate.",
|
||||
"Contraction joints must be designed on the drawing, not decided on site — their absence is the first cause of horizontal facade cracks.",
|
||||
"Window perimeter waterproofing is the most frequent point of failure. Installing waterproofing tape before the sill goes in removes that risk.",
|
||||
"Hot-dip galvanized sub-structures cost marginally more than painted ones — and last many times longer.",
|
||||
"Finally, take the annual facade inspection seriously: repairing one joint costs next to nothing compared with redoing the whole facade.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"slug": "commercial-yield",
|
||||
"title": "چگونه بازدهی یک پروژه تجاری را پیش از ساخت تخمین بزنیم؟",
|
||||
"title_en": "How to Estimate a Commercial Project's Yield Before Building It",
|
||||
"date": "۱۵ تیر ۱۴۰۳",
|
||||
"date_en": "July 5, 2024",
|
||||
"category": "سرمایهگذاری",
|
||||
"category_en": "Investment",
|
||||
"read": "۷ دقیقه",
|
||||
"read_en": "7 min read",
|
||||
"excerpt": "مدل سادهای برای برآورد بازدهی، بر پایه جریان مخاطب، ترکیب واحدها و نرخ اجاره منطقه.",
|
||||
"excerpt_en": "A simple yield-estimation model based on visitor flow, unit mix and local rental rates.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"Estimating commercial yield starts with three numbers: daily visitor flow, the rental rate per square meter in the area, and the net-to-gross floor ratio.",
|
||||
"A common mistake is ignoring the upper levels. Without a well-designed vertical path, levels three and above usually fail to reach even half of the ground-floor rate.",
|
||||
"Finally, write the conservative scenario too — if the project still makes sense in the pessimistic case, the investment is a rational one.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"slug": "facade-materials",
|
||||
"title": "مصالح نما: مقایسه سنگ، کامپوزیت و ترموود در اقلیم ایران",
|
||||
"title_en": "Facade Materials: Stone, Composite and Thermowood in Iran's Climate",
|
||||
"date": "۲ تیر ۱۴۰۳",
|
||||
"date_en": "June 22, 2024",
|
||||
"category": "اجرا",
|
||||
"category_en": "Construction",
|
||||
"read": "۸ دقیقه",
|
||||
"read_en": "8 min read",
|
||||
"excerpt": "هر مصالح نما در اقلیم متفاوتی درست کار میکند؛ انتخاب اشتباه، هزینه نگهداری را چند برابر میکند.",
|
||||
"excerpt_en": "Every facade material works in the right climate; the wrong choice multiplies maintenance costs.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"In a dry climate, stone has the best durability — but its weight demands a precise sub-structure and structural calculations.",
|
||||
"Composite is the fast, light choice, provided you pick a fire-rated grade and account for thermal expansion along the sheet.",
|
||||
"In the humid northern climate, thermowood is the best aesthetic answer — with a twice-yearly maintenance schedule.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"slug": "renovate-or-rebuild",
|
||||
"title": "بازسازی یا نوسازی؟ معیارهای تصمیمگیری برای مالکان",
|
||||
"title_en": "Renovate or Rebuild? Decision Criteria for Property Owners",
|
||||
"date": "۲۰ خرداد ۱۴۰۳",
|
||||
"date_en": "June 9, 2024",
|
||||
"category": "معماری",
|
||||
"category_en": "Architecture",
|
||||
"read": "۶ دقیقه",
|
||||
"read_en": "6 min read",
|
||||
"excerpt": "اگر عمر سازه و ضوابط شهری اجازه دهند، بازسازی میتواند بازدهی بالاتری از تخریب کامل داشته باشد.",
|
||||
"excerpt_en": "If the structure's age and city regulations allow, renovation can outperform full demolition and rebuild.",
|
||||
"body": [],
|
||||
"body_en": [
|
||||
"First the structure is assessed: if seismic retrofitting costs more than 40% of a new build, rebuilding is the more rational option.",
|
||||
"The second criterion is today's urban regulations. Sometimes demolition grants you less permissible floor area — which changes the decision entirely.",
|
||||
"In renovation, the greatest added value comes from three places: the facade, the entrance and the re-planning of the interior.",
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
FAQS = [
|
||||
{"question": "حداقل سرمایه برای مشارکت در پروژههای گروه ساختمانی آرامش چقدر است؟", "question_en": "What is the minimum capital to join Aramesh Construction Group projects?", "answer": "ساختار مشارکت هر پروژه متفاوت است، اما معمولاً واحدهای سرمایهگذاری از سطح مشخصی آغاز میشوند و جزئیات دقیق در جلسه ارزیابی اولیه ارائه میشود.", "answer_en": "Each project's partnership structure is different, but investment units usually start from a defined level, and the exact details are presented in the initial assessment meeting."},
|
||||
{"question": "مدت زمان معمول ساخت یک برج مسکونی چقدر است؟", "question_en": "How long does it take to build a residential tower?", "answer": "بسته به تعداد طبقات و شرایط زمین، میانگین اجرای یک برج مسکونی بین ۲۸ تا ۴۲ ماه از زمان صدور پروانه تا تحویل کلید است.", "answer_en": "Depending on the number of floors and site conditions, a residential tower takes on average 28 to 42 months from permit issuance to key handover."},
|
||||
{"question": "آیا امکان تغییر نقشه داخلی واحد وجود دارد؟", "question_en": "Can the unit's interior layout be customized?", "answer": "بله. تا پیش از پایان مرحله سفتکاری، امکان شخصیسازی پلان داخلی با هماهنگی تیم طراحی و تأیید سازه فراهم است.", "answer_en": "Yes. Until the structural phase is complete, the interior plan can be customized in coordination with the design team and structural approval."},
|
||||
{"question": "خدمات پس از تحویل شامل چه مواردی میشود؟", "question_en": "What does the after-sales service include?", "answer": "پنج سال پشتیبانی فنی تأسیسات مکانیکی و برقی، بازدید دورهای سالانه و تضمین اجرای نما و عایقکاری.", "answer_en": "Five years of technical support for mechanical and electrical systems, an annual inspection, and warranty on facade work and insulation."},
|
||||
{"question": "پروژهها در چه شهرهایی اجرا میشوند؟", "question_en": "In which cities do you build?", "answer": "در حال حاضر تهران، اصفهان و سواحل شمالی کشور مناطق اصلی فعالیت ما هستند و پروژهای نیز در جزیره کیش در دست ساخت است.", "answer_en": "Tehran, Isfahan and the northern coasts are currently our main regions, and a project is also under construction on Kish Island."},
|
||||
]
|
||||
|
||||
NAV_ITEMS = [
|
||||
{"label": "صفحه اصلی", "label_en": "Home", "href": "/"},
|
||||
{"label": "درباره ما", "label_en": "About", "href": "/about"},
|
||||
{"label": "خدمات", "label_en": "Services", "href": "/services"},
|
||||
{"label": "پروژهها", "label_en": "Projects", "href": "/projects"},
|
||||
{"label": "سرمایهگذاری", "label_en": "Investment", "href": "/investment"},
|
||||
{"label": "وبلاگ", "label_en": "Blog", "href": "/blog"},
|
||||
{"label": "سوالات متداول", "label_en": "FAQ", "href": "/faq"},
|
||||
{"label": "تماس با ما", "label_en": "Contact", "href": "/contact"},
|
||||
]
|
||||
|
||||
HERO = {
|
||||
"kicker": "از سال ۱۳۸۳ — تهران، اصفهان، سواحل شمال",
|
||||
"kicker_en": "Since 2004 — Tehran, Isfahan, Northern Coasts",
|
||||
"title": "ساختمانی که آرامش را معماری میکند",
|
||||
"title_en": "A building that architects tranquility",
|
||||
"title_highlight": "معماری",
|
||||
"title_highlight_en": "architects",
|
||||
"subtitle": "طراحی، ساخت و سرمایهگذاری در پروژههای مسکونی و تجاری لوکس؛ با استانداردی که در جزئیات دیده میشود و در سالها دوام میآورد.",
|
||||
"subtitle_en": "Design, construction and investment in luxury residential and commercial projects — to a standard you can see in the details and trust for years.",
|
||||
"badge_value": "۴۷",
|
||||
"badge_value_en": "47",
|
||||
"badge_label": "پروژه تحویلشده در بیستویک سال فعالیت حرفهای",
|
||||
"badge_label_en": "Projects delivered in twenty-one years of professional work",
|
||||
"cta_primary_label": "مشاهده پروژهها",
|
||||
"cta_primary_label_en": "View Projects",
|
||||
"cta_secondary_label": "مشاوره سرمایهگذاری",
|
||||
"cta_secondary_label_en": "Investment Advisory",
|
||||
"scroll_label": "اسکرول کنید",
|
||||
"scroll_label_en": "Scroll",
|
||||
}
|
||||
|
||||
STORY = {
|
||||
"title": "درباره ی ما",
|
||||
"title_en": "About Us",
|
||||
"paragraphs": [],
|
||||
"paragraphs_en": [
|
||||
"Aramesh Construction Group began as a small architecture office and is today one of Iran's recognized names in luxury construction. Through all these years one principle has not changed: a building must be made for living, not for a quick sale.",
|
||||
"Every project starts with a study of the land, light, climate and the residents' way of life; then the design, structural and execution teams carry it through a single process to key handover.",
|
||||
],
|
||||
"quote": "«ساختمان برای ما فقط آجر و بتن نیست؛ بلکه تعهدی است به کیفیت زندگی ساکنان. ما فضاهایی میسازیم که در گذر زمان ارزش و هویت خود را حفظ کنند.»",
|
||||
"quote_en": "\u201cA building, for us, is not just brick and concrete; it is a commitment to the quality of life of its residents. We build spaces that keep their value and identity as time passes.\u201d",
|
||||
"quote_author": "کامران آرامش — مدیرعامل شرکت ساختمانی آرامش",
|
||||
"quote_author_en": "Kamran Aramesh — CEO, Aramesh Construction Group",
|
||||
"stat1_value": "۹۴٪",
|
||||
"stat1_value_en": "94%",
|
||||
"stat1_label": "تحویل بهموقع پروژهها",
|
||||
"stat1_label_en": "On-time project delivery",
|
||||
"stat2_value": "۵ سال",
|
||||
"stat2_value_en": "5 years",
|
||||
"stat2_label": "پشتیبانی پس از تحویل",
|
||||
"stat2_label_en": "Post-handover support",
|
||||
"link_label": "داستان کامل ما",
|
||||
"link_label_en": "Our full story",
|
||||
"bento": [],
|
||||
"bento_en": [
|
||||
{"src": IMAGES[0], "alt": "Facade of an Aramesh residential tower in Tehran"},
|
||||
{"src": IMAGES[1], "alt": "Central atrium of Parseh Shopping Mall"},
|
||||
{"src": IMAGES[2], "alt": "Villas built on the northern coasts"},
|
||||
{"src": IMAGES[3], "alt": "Night view of the Niavaran Twin Towers"},
|
||||
],
|
||||
}
|
||||
|
||||
SECTION_HEADINGS = [
|
||||
{"key": "services", "title_en": "Services", "lead_en": "From the first line on paper to key handover, capital management and landscape design — every stage under one roof and one quality-control system."},
|
||||
{"key": "featured_projects", "title_en": "Featured Projects", "lead_en": "The work that says the most about our standard — both the delivered projects and the ones under construction today.", "cta_label_en": "All Projects"},
|
||||
{"key": "gallery", "title_en": "Gallery", "lead_en": "Frames from the sites and delivered projects of Aramesh Construction Group."},
|
||||
{"key": "timeline", "title_en": "Our Path", "lead_en": "From a four-person office to 47 projects. Walk through the timeline of our work."},
|
||||
{"key": "why_us", "title_en": "Why Aramesh Construction Group", "lead_en": "Six reasons clients and investors come back to us a second time."},
|
||||
{"key": "testimonials", "title_en": "Client Testimonials"},
|
||||
{"key": "team", "title_en": "Our Team", "lead_en": "The people who make each project's key decisions — and answer for them."},
|
||||
{"key": "articles", "label_en": "Blog", "title_en": "Latest Articles", "lead_en": "Notes from the architecture, execution and investment teams of Aramesh Construction Group on what's happening on site and in the market.", "cta_label_en": "All Articles"},
|
||||
{"key": "faq", "title_en": "Frequently Asked Questions", "lead_en": "Short answers to the questions investors and buyers ask most."},
|
||||
{"key": "investment_models", "title_en": "Partnership Models", "lead_en": "Depending on your capital, time horizon and risk appetite, one of these three paths is right for you."},
|
||||
{"key": "process", "title_en": "How We Work", "lead_en": "Four transparent steps, from the first meeting to key handover."},
|
||||
]
|
||||
|
||||
PAGE_HEROES = [
|
||||
{"key": "about", "title_en": "About Us", "lead_en": "Aramesh Construction Group is a team of architects, structural engineers and project managers working in luxury construction since 2004."},
|
||||
{"key": "services", "title_en": "Services", "lead_en": "Eight specialized fields covering a building project's full cycle, from idea to operation."},
|
||||
{"key": "projects", "title_en": "Projects", "lead_en": "A collection of residential towers, commercial centers and private villas — from delivered projects to today's active sites."},
|
||||
{"key": "investment", "title_en": "Investment", "lead_en": "Three clear paths into the luxury construction market, with transparent financial structures and regular reporting."},
|
||||
{"key": "blog", "title_en": "Blog", "lead_en": "Notes from the architecture, execution and investment teams of Aramesh Construction Group on what's happening on site and in the market."},
|
||||
{"key": "faq", "title_en": "Frequently Asked Questions", "lead_en": "Before you call, the answer to your question might be right here. If not, we would be glad to talk directly."},
|
||||
{"key": "contact", "title_en": "Contact Us", "lead_en": "For construction consultancy, investment or a project visit, our teams in three cities are ready to respond."},
|
||||
]
|
||||
|
||||
INVESTMENT_MODELS = [
|
||||
{
|
||||
"title": "مشارکت در ساخت",
|
||||
"title_en": "Joint Construction Partnership",
|
||||
"desc": "مالک زمین و گروه ساختمانی آرامش در سود پروژه شریک میشوند؛ اجرا، مجوزها و فروش بر عهده ماست.",
|
||||
"desc_en": "The landowner and Aramesh share the project's profit; execution, permits and sales are on us.",
|
||||
"points": [],
|
||||
"points_en": ["Free land assessment", "Transparent contract with performance guarantee", "Monthly progress reporting"],
|
||||
},
|
||||
{
|
||||
"title": "صندوق پروژهمحور",
|
||||
"title_en": "Project-Based Fund",
|
||||
"desc": "سرمایهگذاری روی یک پروژه مشخص با واحدهای قابل خرید و بازدهی محاسبهشده در پایان دوره.",
|
||||
"desc_en": "Investment in a specific project with purchasable units and a calculated yield at the end of the term.",
|
||||
"points": [],
|
||||
"points_en": ["Minimum 24-month term", "Quarterly valuation reports", "Investment units are transferable"],
|
||||
},
|
||||
{
|
||||
"title": "پیشخرید واحد",
|
||||
"title_en": "Pre-Purchase",
|
||||
"desc": "خرید واحد مسکونی یا تجاری در مراحل ابتدایی ساخت با قیمت پیش از تکمیل و پرداخت مرحلهای.",
|
||||
"desc_en": "Buying a residential or commercial unit in the early stages of construction, at a pre-completion price with staged payments.",
|
||||
"points": [],
|
||||
"points_en": ["Payments staged to match progress", "Interior layout customization", "Delivery-time guarantee"],
|
||||
},
|
||||
]
|
||||
|
||||
PROCESS_STEPS = [
|
||||
{"step": "۰۱", "step_en": "01", "title": "مطالعه و امکانسنجی", "title_en": "Study & Feasibility", "desc": "بررسی زمین، ضوابط شهری و تحلیل بازدهی اقتصادی پروژه.", "desc_en": "Site review, urban regulations and an economic yield analysis of the project."},
|
||||
{"step": "۰۲", "step_en": "02", "title": "طراحی و فاز اجرایی", "title_en": "Design & Construction Drawings", "desc": "کانسپت معماری، طراحی سازه و تأسیسات و تهیه نقشههای اجرایی.", "desc_en": "Architectural concept, structural and MEP design, and construction documentation."},
|
||||
{"step": "۰۳", "step_en": "03", "title": "اجرا و کنترل کیفیت", "title_en": "Execution & Quality Control", "desc": "ساخت با نظارت مستمر، گزارش ماهانه پیشرفت و کنترل هزینه.", "desc_en": "Construction with continuous supervision, monthly progress reports and cost control."},
|
||||
{"step": "۰۴", "step_en": "04", "title": "تحویل و پشتیبانی", "title_en": "Handover & Support", "desc": "تحویل کلید، آموزش بهرهبرداری و پنج سال پشتیبانی فنی.", "desc_en": "Key handover, operating walkthrough and five years of technical support."},
|
||||
]
|
||||
|
||||
OFFICES = [
|
||||
{"city": "تهران", "city_en": "Tehran", "address": "خیابان ولیعصر، برج آرامش، طبقه هجدهم", "address_en": "Valiasr St., Aramesh Tower, 18th Floor", "hours": "شنبه تا چهارشنبه، ۹ تا ۱۸", "hours_en": "Saturday–Wednesday, 9 AM–6 PM"},
|
||||
{"city": "اصفهان", "city_en": "Isfahan", "address": "خیابان چهارباغ بالا، مجتمع پارسه، طبقه ششم", "address_en": "Chaharbagh Bala St., Parseh Complex, 6th Floor", "hours": "شنبه تا چهارشنبه، ۹ تا ۱۷", "hours_en": "Saturday–Wednesday, 9 AM–5 PM"},
|
||||
{"city": "نوشهر", "city_en": "Nowshahr", "address": "بلوار دریا، دفتر پروژه دریاکنار", "address_en": "Darya Blvd., Daryakenar Project Office", "hours": "شنبه تا پنجشنبه، ۱۰ تا ۱۶", "hours_en": "Saturday–Thursday, 10 AM–4 PM"},
|
||||
]
|
||||
|
||||
GALLERY_IMAGES = [
|
||||
{"src": IMAGES[0], "alt_en": "Aramesh Construction Group project, No. 1"},
|
||||
{"src": IMAGES[1], "alt_en": "Aramesh Construction Group project, No. 2"},
|
||||
{"src": IMAGES[2], "alt_en": "Aramesh Construction Group project, No. 3"},
|
||||
{"src": IMAGES[3], "alt_en": "Aramesh Construction Group project, No. 4"},
|
||||
{"src": IMAGES[4], "alt_en": "Aramesh Construction Group project, No. 5"},
|
||||
{"src": IMAGES[1], "alt_en": "Aramesh Construction Group project, No. 6"},
|
||||
]
|
||||
|
||||
STATUS_LABELS = [
|
||||
{"key": "done", "label_en": "Completed"},
|
||||
{"key": "progress", "label_en": "In Progress"},
|
||||
]
|
||||
|
||||
CONTACT_SECTION = {
|
||||
"label": "تماس با ما",
|
||||
"label_en": "Contact Us",
|
||||
"title": "پروژهتان را با ما در میان بگذارید",
|
||||
"title_en": "Tell Us About Your Project",
|
||||
"lead": "شمارهتان را بگذارید؛ کارشناس ما در کمتر از یک روز کاری برای یک جلسه مشاوره رایگان تماس میگیرد.",
|
||||
"lead_en": "Leave your number — our expert will call you within one business day for a free consultation session.",
|
||||
"address_label": "دفتر مرکزی",
|
||||
"address_label_en": "Head Office",
|
||||
"phone_label": "تلفن",
|
||||
"phone_label_en": "Phone",
|
||||
"email_label": "ایمیل",
|
||||
"email_label_en": "Email",
|
||||
"name_label": "نام",
|
||||
"name_label_en": "Name",
|
||||
"name_placeholder": "نام و نام خانوادگی",
|
||||
"name_placeholder_en": "Full name",
|
||||
"phone_field_label": "شماره تلفن",
|
||||
"phone_field_label_en": "Phone number",
|
||||
"note_label": "توضیحات",
|
||||
"note_label_en": "Details",
|
||||
"note_optional_label": "(اختیاری)",
|
||||
"note_optional_label_en": "(optional)",
|
||||
"note_placeholder": "درباره پروژه یا درخواست خود بنویسید…",
|
||||
"note_placeholder_en": "Tell us about your project or request…",
|
||||
"submit_label": "ارسال درخواست مشاوره",
|
||||
"submit_label_en": "Request a Consultation",
|
||||
"sending_label": "در حال ارسال…",
|
||||
"sending_label_en": "Sending…",
|
||||
"success_title": "درخواست شما ثبت شد",
|
||||
"success_title_en": "Your Request Was Received",
|
||||
"success_text": "از اعتماد شما سپاسگزاریم. کارشناسان ما بهزودی با شما تماس میگیرند.",
|
||||
"success_text_en": "Thank you for your trust. Our experts will contact you shortly.",
|
||||
"success_button_label": "ثبت درخواست جدید",
|
||||
"success_button_label_en": "Submit Another Request",
|
||||
}
|
||||
|
||||
NEWSLETTER = {
|
||||
"title": "خبرنامه گروه ساختمانی آرامش",
|
||||
"title_en": "Aramesh Construction Group Newsletter",
|
||||
"lead": "هر ماه یک ایمیل: پروژههای جدید، فرصتهای سرمایهگذاری و یادداشتهای تیم معماری.",
|
||||
"lead_en": "One email a month: new projects, investment opportunities and notes from the architecture team.",
|
||||
"placeholder": "نشانی ایمیل شما",
|
||||
"placeholder_en": "Your email address",
|
||||
"button_label": "عضویت",
|
||||
"button_label_en": "Subscribe",
|
||||
"sending_label": "در حال ارسال…",
|
||||
"sending_label_en": "Sending…",
|
||||
"success_text": "عضویت شما ثبت شد.",
|
||||
"success_text_en": "Your subscription has been registered.",
|
||||
}
|
||||
|
||||
FOOTER = {
|
||||
"about_text": "گروه ساختمانی آرامش از سال ۱۳۸۳ ساختمانهایی میسازد که قرار است چند نسل در آنها زندگی کنند؛ معماری آرام، اجرای دقیق و سرمایهگذاری شفاف.",
|
||||
"about_text_en": "Since 2004, Aramesh Construction Group has been building for generations to come: calm architecture, precise execution and transparent investment.",
|
||||
"pages_heading": "صفحات",
|
||||
"pages_heading_en": "Pages",
|
||||
"services_heading": "خدمات",
|
||||
"services_heading_en": "Services",
|
||||
"contact_heading": "ارتباط با ما",
|
||||
"contact_heading_en": "Contact",
|
||||
"copyright": "© ۱۴۰۳ گروه ساختمانی آرامش — تمامی حقوق محفوظ است.",
|
||||
"copyright_en": "© 2025 Aramesh Construction Group — All rights reserved.",
|
||||
"tagline": "طراحی و ساخت با دقتِ معماری",
|
||||
"tagline_en": "Designed and built with architectural precision",
|
||||
"socials_en": [
|
||||
{"label": "Instagram", "href": "#", "icon": "instagram"},
|
||||
{"label": "LinkedIn", "href": "#", "icon": "linkedin"},
|
||||
{"label": "Telegram", "href": "#", "icon": "telegram"},
|
||||
],
|
||||
}
|
||||
|
||||
SEO_META = [
|
||||
{"page_key": "home", "title_en": "Aramesh Construction Group | Luxury Residential & Commercial Buildings", "description_en": "Design, construction and investment in luxury residential and commercial projects in Iran — 21 years of experience, 47 delivered projects."},
|
||||
{"page_key": "about", "title_en": "About Us | Aramesh Construction Group", "description_en": "Architects, structural engineers and project managers in luxury construction since 2004."},
|
||||
{"page_key": "services", "title_en": "Services | Aramesh Construction Group", "description_en": "Architectural design, high-rise construction, commercial complexes, villas, renovation and project management."},
|
||||
{"page_key": "projects", "title_en": "Projects | Aramesh Construction Group", "description_en": "Residential towers, commercial centers and private villas — delivered projects and active sites."},
|
||||
{"page_key": "investment", "title_en": "Investment | Aramesh Construction Group", "description_en": "Three transparent paths into the luxury construction market: joint construction, project-based funds and pre-purchase."},
|
||||
{"page_key": "blog", "title_en": "Blog | Aramesh Construction Group", "description_en": "Articles on architecture, construction and real estate investment from the Aramesh team."},
|
||||
{"page_key": "faq", "title_en": "FAQ | Aramesh Construction Group", "description_en": "Short answers to the most frequent questions from investors and buyers."},
|
||||
{"page_key": "contact", "title_en": "Contact Us | Aramesh Construction Group", "description_en": "Get in touch for construction consultancy, investment or a project visit — offices in Tehran, Isfahan and Nowshahr."},
|
||||
]
|
||||
@@ -0,0 +1,956 @@
|
||||
"""سئوی سمت سرور — robots.txt، sitemap.xml، llms.txt و سرو همهٔ صفحات با متای تزریقی.
|
||||
|
||||
فرانتاند یک SPA است؛ خزندههای جستوجو و شبکههای اجتماعی جاوااسکریپت اجرا نمیکنند.
|
||||
این ماژول همان index.html بیلد فرانتاند را میخواند و پیش از ارسال، تگهای
|
||||
title / description / canonical / OG / hreflang / JSON-LD را از دیتابیس داخل آن تزریق میکند —
|
||||
بازدیدکنندههای عادی همان SPA همیشگی را میبینند و خزندهها متای درست را در HTML اولیه میخوانند.
|
||||
(اسکیمای صفحه داخل <script id="seo-jsonld"> تزریق میشود؛ همان اسکریپتی که سمت مرورگر
|
||||
بعد از هیدریشن بازنویسی میشود — پس نسخهٔ تکراری ساخته نمیشود. اسکیمای Organization
|
||||
جداگانه و پایدار تزریق میشود و سمت مرورگر دست نمیخورد.)
|
||||
|
||||
دو زبانه بودن: نسخه فارسی روی مسیرهای اصلی و نسخه انگلیسی روی /en/... سرو میشود.
|
||||
لینکهای alternate (هم در head و هم در sitemap) فقط وقتی اعلام میشوند که ترجمهٔ
|
||||
انگلیسی واقعاً وجود داشته باشد — وگرنه گوگل محتوای فارسی را با برچسب «en» میبیند
|
||||
و مجموعهٔ hreflang ناسازگار میشود. صفحهٔ انگلیسیِ ترجمهنشده برای بازدیدکننده سرو
|
||||
میشود ولی هیچ ادعای hreflang ندارد.
|
||||
|
||||
حالت پیشنمایش (PREVIEW_MODE=on): robots.txt همهچیز را میبندد، sitemap خالی است
|
||||
و llms.txt با کد ۴۰۴ پاسخ میدهد — هیچ نشانیای از سایت خصوصی بیرون درز نمیکند.
|
||||
"""
|
||||
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, Response
|
||||
from fastapi.responses import HTMLResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from . import models
|
||||
from .config import settings
|
||||
from .database import get_db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
STATIC_PATHS = ["/", "/about", "/services", "/projects", "/investment", "/blog", "/faq", "/contact"]
|
||||
# صفحاتی که متای آنها از seo_meta خوانده میشود — کلید همان page_key است
|
||||
META_KEYS = ["home", "about", "services", "projects", "investment", "blog", "faq", "contact"]
|
||||
FALLBACK_FA_BRAND = "گروه ساختمانی آرامش"
|
||||
FALLBACK_EN_BRAND = "Aramesh Construction Group"
|
||||
# تصویر پیشفرض شبکههای اجتماعی — در frontend/public بیلد میشود
|
||||
DEFAULT_OG_IMAGE = "/og-default.jpg"
|
||||
DEFAULT_OG_SIZE = (1200, 630)
|
||||
# خزندههای هوش مصنوعی جستوجو/ارجاع — سیاست صریح «مجاز» تا قالبهای پیشفرض
|
||||
# «بستن همهچیز» اتفاقی آنها را نبندند (GPTBot آموزش است، OAI-SearchBot ارجاع چتجیپیتی)
|
||||
AI_SEARCH_BOTS = [
|
||||
"GPTBot",
|
||||
"OAI-SearchBot",
|
||||
"ChatGPT-User",
|
||||
"ClaudeBot",
|
||||
"Claude-SearchBot",
|
||||
"PerplexityBot",
|
||||
"Perplexity-User",
|
||||
"Google-Extended",
|
||||
"Applebot-Extended",
|
||||
]
|
||||
|
||||
|
||||
def _absolute(path: str) -> str:
|
||||
if not path:
|
||||
return ""
|
||||
if path.startswith(("http://", "https://")):
|
||||
return path
|
||||
site = settings.site_url.rstrip("/")
|
||||
return f"{site}{path}" if site else path
|
||||
|
||||
|
||||
def _en_path(path: str) -> str:
|
||||
"""مسیر انگلیسی معادل یک مسیر فارسی — / و /en یکدیگرند."""
|
||||
return "/en" if path == "/" else f"/en{path}"
|
||||
|
||||
|
||||
def _fa_path(path: str) -> str:
|
||||
"""مسیر فارسی معادل یک مسیر انگلیسی."""
|
||||
if path == "/en":
|
||||
return "/"
|
||||
return path[3:] if path.startswith("/en/") else path
|
||||
|
||||
|
||||
def _clip(text: str, limit: int) -> str:
|
||||
"""برش متن به طول مشخص برای توضیحهای تکخطی (llms.txt)."""
|
||||
text = " ".join((text or "").split())
|
||||
return text[:limit] + ("…" if len(text) > limit else "")
|
||||
|
||||
|
||||
# ---------- تاریخ مقاله — ISO میلادی یا شمسی دستنویس → ISO برای datePublished ----------
|
||||
|
||||
_FA_DIGITS = str.maketrans("۰۱۲۳۴۵۶۷۸۹", "0123456789")
|
||||
_FA_MONTHS = {
|
||||
"فروردین": 1, "اردیبهشت": 2, "خرداد": 3, "تیر": 4, "مرداد": 5, "شهریور": 6,
|
||||
"مهر": 7, "آبان": 8, "آذر": 9, "دی": 10, "بهمن": 11, "اسفند": 12,
|
||||
}
|
||||
|
||||
|
||||
def _jalali_to_gregorian(jy: int, jm: int, jd: int) -> tuple[int, int, int]:
|
||||
"""تبدیل تاریخ جلالی به میلادی — الگوریتم استاندارد jalaali."""
|
||||
jy += 1595
|
||||
days = -355668 + (365 * jy) + ((jy // 33) * 8) + (((jy % 33) + 3) // 4) + jd
|
||||
days += (jm - 1) * 31 if jm < 7 else ((jm - 7) * 30) + 186
|
||||
gy = 400 * (days // 146097)
|
||||
days %= 146097
|
||||
if days > 36524:
|
||||
days -= 1
|
||||
gy += 100 * (days // 36524)
|
||||
days %= 36524
|
||||
if days >= 365:
|
||||
days += 1
|
||||
gy += 4 * (days // 1461)
|
||||
days %= 1461
|
||||
if days > 365:
|
||||
gy += (days - 1) // 365
|
||||
days = (days - 1) % 365
|
||||
gd = days + 1
|
||||
leap = (gy % 4 == 0 and gy % 100 != 0) or (gy % 400 == 0)
|
||||
for gm, md in enumerate([31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], start=1):
|
||||
if gd <= md:
|
||||
return gy, gm, gd
|
||||
gd -= md
|
||||
return gy, 12, 31
|
||||
|
||||
|
||||
def _parse_site_date(value: str | None) -> str | None:
|
||||
"""تاریخ مقاله → ISO (YYYY-MM-DD) برای datePublished اسکیما؛ تاریخ نامفهوم → None.
|
||||
هم ISO میلادی (خروجی انتخابگر تاریخ پنل) و هم شمسی دستنویس («۲۴ مرداد ۱۴۰۳») را میفهمد."""
|
||||
raw = (value or "").strip().translate(_FA_DIGITS)
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(raw).date().isoformat()
|
||||
except ValueError:
|
||||
pass
|
||||
m = re.fullmatch(r"(\d{1,2})\s*([\u0600-\u06FF]+)\s*(\d{4})", raw)
|
||||
if m and m.group(2) in _FA_MONTHS:
|
||||
gy, gm, gd = _jalali_to_gregorian(int(m.group(3)), _FA_MONTHS[m.group(2)], int(m.group(1)))
|
||||
return date(gy, gm, gd).isoformat()
|
||||
return None
|
||||
|
||||
|
||||
# ---------- alternates — فقط وقتی ترجمهٔ انگلیسی واقعاً وجود دارد ----------
|
||||
|
||||
|
||||
def _alternate_pairs(path: str, lang: str, has_en: bool) -> list[tuple[str, str]]:
|
||||
"""جفتهای (hreflang، href) یک صفحه — مبنای مشترک head و sitemap.
|
||||
صفحهٔ انگلیسیِ ترجمهنشده هیچ ادعایی ندارد (لیست خالی)."""
|
||||
fa = path if lang == "fa" else _fa_path(path)
|
||||
if lang == "en" and not has_en:
|
||||
return []
|
||||
pairs = [("fa", _absolute(fa)), ("x-default", _absolute(fa))]
|
||||
if has_en:
|
||||
en = _en_path(path) if lang == "fa" else path
|
||||
pairs.insert(1, ("en", _absolute(en)))
|
||||
return pairs
|
||||
|
||||
|
||||
def _alternates(path: str, lang: str, has_en: bool = True) -> str:
|
||||
"""تگهای link alternate برای head — از همان جفتهای sitemap."""
|
||||
pairs = _alternate_pairs(path, lang, has_en)
|
||||
return "\n ".join(
|
||||
f'<link rel="alternate" hreflang="{lang_code}" href="{html.escape(href_)}" />'
|
||||
for lang_code, href_ in pairs
|
||||
)
|
||||
|
||||
|
||||
def _article_has_en(article: models.Article) -> bool:
|
||||
"""آیا ترجمهٔ انگلیسی واقعی برای مقاله ثبت شده است؟"""
|
||||
if (article.title_en or "").strip() or (article.excerpt_en or "").strip():
|
||||
return True
|
||||
return bool(isinstance(article.body_en, dict) and (article.body_en.get("content") or []))
|
||||
|
||||
|
||||
def _project_has_en(project: models.Project) -> bool:
|
||||
return bool((project.title_en or "").strip() or (project.summary_en or "").strip())
|
||||
|
||||
|
||||
# ---------- پوستهٔ HTML با متای تزریقی ----------
|
||||
|
||||
|
||||
def _read_index() -> str | None:
|
||||
try:
|
||||
return (Path(settings.frontend_dist) / "index.html").read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _default_og() -> str:
|
||||
"""تصویر پیشفرض OG — فقط وقتی فایل واقعاً در بیلد فرانتاند باشد."""
|
||||
if (Path(settings.frontend_dist) / DEFAULT_OG_IMAGE.lstrip("/")).is_file():
|
||||
return _absolute(DEFAULT_OG_IMAGE)
|
||||
return ""
|
||||
|
||||
|
||||
def _doc_text(doc: object, limit: int = 300) -> str:
|
||||
"""متن ساده سند TipTap — برای noscript و پیشنمایش."""
|
||||
words: list[str] = []
|
||||
|
||||
def walk(node: object) -> None:
|
||||
if not isinstance(node, dict):
|
||||
return
|
||||
if node.get("type") == "text" and isinstance(node.get("text"), str):
|
||||
words.append(node["text"])
|
||||
for child in node.get("content") or []:
|
||||
walk(child)
|
||||
|
||||
if isinstance(doc, dict):
|
||||
for block in doc.get("content") or []:
|
||||
walk(block)
|
||||
text = " ".join(words).strip()
|
||||
return text[:limit] + ("…" if len(text) > limit else "")
|
||||
|
||||
|
||||
def _shell(
|
||||
*,
|
||||
title: str,
|
||||
description: str,
|
||||
path: str,
|
||||
lang: str = "fa",
|
||||
has_en: bool = True,
|
||||
og_image: str = "",
|
||||
og_image_alt: str = "",
|
||||
og_type: str = "website",
|
||||
jsonld: dict | list | None = None,
|
||||
org_jsonld: dict | None = None,
|
||||
noscript: str = "",
|
||||
status_code: int = 200,
|
||||
) -> HTMLResponse:
|
||||
"""index.html فرانتاند با متای تزریقی؛ اگر بیلد در دسترس نبود، صفحه حداقلی."""
|
||||
title = title.strip() or (FALLBACK_EN_BRAND if lang == "en" else FALLBACK_FA_BRAND)
|
||||
description = description.strip()
|
||||
canonical = _absolute(path)
|
||||
esc = html.escape
|
||||
alternates = _alternates(path, lang, has_en)
|
||||
|
||||
# تصویر OG — تصویر اختصاصی صفحه یا تصویر پیشفرض برند
|
||||
custom_image = (og_image or "").strip()
|
||||
image = _absolute(custom_image) if custom_image else _default_og()
|
||||
image_is_default = not custom_image and bool(_default_og())
|
||||
|
||||
tags = [
|
||||
f'<link rel="canonical" href="{esc(canonical)}" />',
|
||||
f'<meta name="description" content="{esc(description)}" />',
|
||||
f'<meta property="og:title" content="{esc(title)}" />',
|
||||
f'<meta property="og:description" content="{esc(description)}" />',
|
||||
f'<meta property="og:type" content="{esc(og_type)}" />',
|
||||
f'<meta property="og:url" content="{esc(canonical)}" />',
|
||||
f'<meta property="og:locale" content="{"en_US" if lang == "en" else "fa_IR"}" />',
|
||||
f'<meta property="og:locale:alternate" content="{"fa_IR" if lang == "en" else "en_US"}" />',
|
||||
f'<meta name="twitter:card" content="summary_large_image" />',
|
||||
f'<meta name="twitter:title" content="{esc(title)}" />',
|
||||
f'<meta name="twitter:description" content="{esc(description)}" />',
|
||||
]
|
||||
if image:
|
||||
tags.append(f'<meta property="og:image" content="{esc(image)}" />')
|
||||
tags.append(f'<meta name="twitter:image" content="{esc(image)}" />')
|
||||
tags.append(f'<meta property="og:image:alt" content="{esc(og_image_alt.strip() or title)}" />')
|
||||
if image_is_default:
|
||||
tags.append(f'<meta property="og:image:width" content="{DEFAULT_OG_SIZE[0]}" />')
|
||||
tags.append(f'<meta property="og:image:height" content="{DEFAULT_OG_SIZE[1]}" />')
|
||||
if jsonld:
|
||||
payload = json.dumps(jsonld, ensure_ascii=False).replace("</", "<\\/")
|
||||
# id="seo-jsonld" — سمت مرورگر همان اسکریپت بازنویسی میشود، نه اینکه تکراری ساخته شود
|
||||
tags.append(f'<script type="application/ld+json" id="seo-jsonld">{payload}</script>')
|
||||
if org_jsonld:
|
||||
payload = json.dumps(org_jsonld, ensure_ascii=False).replace("</", "<\\/")
|
||||
tags.append(f'<script type="application/ld+json" id="seo-org-jsonld">{payload}</script>')
|
||||
block = "\n ".join(tags)
|
||||
|
||||
raw = _read_index()
|
||||
if raw is None:
|
||||
# بیلد فرانتاند سوار نشده — صفحه حداقلی با خودِ متا تا خزندهها دست خالی نمانند
|
||||
lang_attr = 'lang="en" dir="ltr"' if lang == "en" else 'lang="fa" dir="rtl"'
|
||||
body = f"<h1>{esc(title)}</h1><p>{esc(description)}</p>"
|
||||
return HTMLResponse(
|
||||
f'<!doctype html><html {lang_attr}><head><meta charset="utf-8">'
|
||||
f"<title>{esc(title)}</title>{alternates}{block}</head><body>{body}</body></html>",
|
||||
status_code=status_code,
|
||||
)
|
||||
|
||||
# اسکیمای Organization مینیمالِ پوستهٔ استاتیک حذف میشود تا با نسخهٔ غنی تزریقی تکراری نشود
|
||||
if org_jsonld:
|
||||
raw = re.sub(r'<script type="application/ld\+json">[^<]*</script>', "", raw, count=1)
|
||||
if lang == "en":
|
||||
# پوسته بیلدشده فارسی است — برای نسخه انگلیسی جهت، زبان و برند سند عوض میشود
|
||||
raw = re.sub(r'<html[^>]*>', '<html lang="en" dir="ltr">', raw, count=1)
|
||||
raw = raw.replace(FALLBACK_FA_BRAND, FALLBACK_EN_BRAND)
|
||||
# description استاتیک حذف میشود تا با متای تزریقی تکراری نشود
|
||||
raw = re.sub(r'<meta name="description"[^>]*/>\s*', '', raw, count=1)
|
||||
# og:locale — در پوسته استاتیک بهروز میشود و از بلوک تزریقی حذف تا دوباره نوشته نشود
|
||||
og_locale = "en_US" if lang == "en" else "fa_IR"
|
||||
if re.search(r'<meta property="og:locale"', raw):
|
||||
raw = re.sub(
|
||||
r'(<meta property="og:locale" content=")[^"]*(")',
|
||||
lambda m: f'{m.group(1)}{og_locale}{m.group(2)}',
|
||||
raw,
|
||||
count=1,
|
||||
)
|
||||
tags = [t for t in tags if 'og:locale' not in t]
|
||||
block = "\n ".join(tags)
|
||||
raw = re.sub(r"<title>.*?</title>", f"<title>{esc(title)}</title>", raw, count=1, flags=re.S)
|
||||
raw = raw.replace("</head>", f" {alternates}\n {block}\n </head>", 1)
|
||||
if noscript:
|
||||
raw = raw.replace("</body>", f"<noscript>{noscript}</noscript>\n </body>", 1)
|
||||
return HTMLResponse(raw, status_code=status_code)
|
||||
|
||||
|
||||
# ---------- موجودیتهای ساختیافته (JSON-LD) ----------
|
||||
|
||||
|
||||
def _brand_row(db: Session) -> models.Brand | None:
|
||||
return db.query(models.Brand).first()
|
||||
|
||||
|
||||
def _brand_name(db: Session, lang: str = "fa") -> str:
|
||||
brand = _brand_row(db)
|
||||
if brand is None:
|
||||
return FALLBACK_EN_BRAND if lang == "en" else FALLBACK_FA_BRAND
|
||||
if lang == "en":
|
||||
return brand.name_en or brand.name or FALLBACK_EN_BRAND
|
||||
return brand.name or FALLBACK_FA_BRAND
|
||||
|
||||
|
||||
def _page_meta(db: Session, page_key: str) -> models.SeoMeta | None:
|
||||
return db.query(models.SeoMeta).filter(models.SeoMeta.page_key == page_key).first()
|
||||
|
||||
|
||||
def _meta_for(db: Session, page_key: str, lang: str) -> tuple[str, str]:
|
||||
"""عنوان و توضیح سئوی یک صفحه به زبان درخواستی — با برگشت به فارسی."""
|
||||
meta = _page_meta(db, page_key)
|
||||
if meta is None:
|
||||
return "", ""
|
||||
if lang == "en":
|
||||
return meta.title_en or meta.title or "", meta.description_en or meta.description or ""
|
||||
return meta.title or "", meta.description or ""
|
||||
|
||||
|
||||
def _meta_desc_for(article: models.Article, lang: str) -> str:
|
||||
"""توضیح سئوی مقاله به زبان درخواستی — توضیح اختصاصی در اولویت، چکیده در برگشت."""
|
||||
if lang == "en":
|
||||
return (article.meta_description_en or article.meta_description or article.excerpt_en or article.excerpt or "").strip()
|
||||
return (article.meta_description or article.excerpt or "").strip()
|
||||
|
||||
|
||||
def _org_jsonld(db: Session, lang: str) -> dict:
|
||||
"""اسکیمای Organization — روی همهٔ صفحات تزریق میشود (موجودیت برند سایت).
|
||||
فقط دادههای واقعی: لوگو، شبکههای اجتماعی فوتر و تماس ثبتشده در پنل."""
|
||||
brand = _brand_row(db)
|
||||
org: dict = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Organization",
|
||||
"name": _brand_name(db, lang),
|
||||
}
|
||||
if settings.site_url:
|
||||
org["url"] = _absolute("/")
|
||||
logo = (brand.logo or "").strip() if brand else ""
|
||||
if logo:
|
||||
org["logo"] = _absolute(logo)
|
||||
footer = db.query(models.FooterContent).first()
|
||||
socials = []
|
||||
if footer is not None:
|
||||
socials = (footer.socials_en if lang == "en" and footer.socials_en else footer.socials) or []
|
||||
same_as: list[str] = []
|
||||
for item in socials if isinstance(socials, list) else []:
|
||||
if isinstance(item, dict):
|
||||
href_ = (item.get("href") or "").strip()
|
||||
if href_.startswith("http") and href_ not in same_as:
|
||||
same_as.append(href_)
|
||||
if same_as:
|
||||
org["sameAs"] = same_as
|
||||
phone = (brand.phone or "").strip() if brand else ""
|
||||
if phone:
|
||||
org["contactPoint"] = [
|
||||
{"@type": "ContactPoint", "contactType": "customer service", "telephone": phone}
|
||||
]
|
||||
email = (brand.email or "").strip() if brand else ""
|
||||
if email:
|
||||
org["email"] = email
|
||||
return org
|
||||
|
||||
|
||||
def _localbusiness_jsonld(db: Session, lang: str, path: str) -> dict | None:
|
||||
"""اسکیمای GeneralContractor از دفاتر ثبتشده — برای صفحههای تماس و درباره."""
|
||||
offices = db.query(models.Office).order_by(models.Office.position, models.Office.id).all()
|
||||
if not offices:
|
||||
return None
|
||||
brand = _brand_row(db)
|
||||
business: dict = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "GeneralContractor",
|
||||
"name": _brand_name(db, lang),
|
||||
"url": _absolute(path),
|
||||
}
|
||||
phone = (brand.phone or "").strip() if brand else ""
|
||||
if phone:
|
||||
business["telephone"] = phone
|
||||
email = (brand.email or "").strip() if brand else ""
|
||||
if email:
|
||||
business["email"] = email
|
||||
addresses: list[dict] = []
|
||||
areas: list[str] = []
|
||||
for office in offices:
|
||||
city = ((office.city_en or office.city) if lang == "en" else office.city).strip()
|
||||
street = ((office.address_en or office.address) if lang == "en" else office.address).strip()
|
||||
address: dict = {"@type": "PostalAddress", "addressCountry": "IR"}
|
||||
if street:
|
||||
address["streetAddress"] = street
|
||||
if city:
|
||||
address["addressLocality"] = city
|
||||
areas.append(city)
|
||||
addresses.append(address)
|
||||
business["address"] = addresses[0] if len(addresses) == 1 else addresses
|
||||
if areas:
|
||||
business["areaServed"] = sorted(set(areas))
|
||||
return business
|
||||
|
||||
|
||||
def _breadcrumb_jsonld(items: list[tuple[str, str]]) -> dict:
|
||||
"""اسکیمای BreadcrumbList — متناظر با مسیر بطری بصری صفحه."""
|
||||
return {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "BreadcrumbList",
|
||||
"itemListElement": [
|
||||
{"@type": "ListItem", "position": i + 1, "name": name, "item": _absolute(url)}
|
||||
for i, (name, url) in enumerate(items)
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _faq_entities(faqs: object, lang: str = "fa", faqs_en: object = None) -> list[dict]:
|
||||
"""ساخت mainEntity اسکیمای FAQPage از ردیفهای [{question, answer}]."""
|
||||
rows = faqs if isinstance(faqs, list) else []
|
||||
if lang == "en":
|
||||
rows_en = faqs_en if isinstance(faqs_en, list) else None
|
||||
if rows_en:
|
||||
rows = rows_en
|
||||
entities = []
|
||||
for item in rows:
|
||||
if isinstance(item, dict):
|
||||
question = (item.get("question") or "").strip()
|
||||
answer = (item.get("answer") or "").strip()
|
||||
if question and answer:
|
||||
entities.append(
|
||||
{"@type": "Question", "name": question,
|
||||
"acceptedAnswer": {"@type": "Answer", "text": answer}}
|
||||
)
|
||||
return entities
|
||||
|
||||
|
||||
def _faq_page_jsonld(db: Session, lang: str) -> dict | None:
|
||||
"""اسکیمای FAQPage صفحهٔ پرسشوپاسخ — از موجودیت faqs.
|
||||
(گوگل از اردیبهشت ۱۴۰۵ نتیجهٔ غنی FAQ برای همهٔ سایتها برداشت؛ این اسکیما برای
|
||||
موتورهای هوش مصنوعی است که پرسشوپاسخ ساختیافته را مستقیم میخوانند.)"""
|
||||
rows = db.query(models.Faq).order_by(models.Faq.position, models.Faq.id).all()
|
||||
entities = _faq_entities(
|
||||
[{"question": f.question, "answer": f.answer} for f in rows],
|
||||
lang,
|
||||
[{"question": f.question_en, "answer": f.answer_en} for f in rows],
|
||||
)
|
||||
if not entities:
|
||||
return None
|
||||
return {"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": entities}
|
||||
|
||||
|
||||
def _article_jsonld(article: models.Article, lang: str, db: Session) -> dict:
|
||||
"""اسکیمای Article — با نویسنده (Person در صورت ثبت نام)، تاریخ انتشار و ناشر."""
|
||||
brand = _brand_name(db, lang)
|
||||
title = (article.title_en or article.title) if lang == "en" else article.title
|
||||
en_slug = ((article.slug_en or "").strip() or article.slug) if lang == "en" else article.slug
|
||||
author_name = ((article.author_en or "").strip() or (article.author or "").strip()) if lang == "en" else (article.author or "").strip()
|
||||
publisher: dict = {"@type": "Organization", "name": brand}
|
||||
brand_row = _brand_row(db)
|
||||
logo = (brand_row.logo or "").strip() if brand_row else ""
|
||||
if logo:
|
||||
publisher["logo"] = {"@type": "ImageObject", "url": _absolute(logo)}
|
||||
schema: dict = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Article",
|
||||
"headline": title,
|
||||
"description": _meta_desc_for(article, lang),
|
||||
"inLanguage": lang,
|
||||
"author": {"@type": "Person", "name": author_name} if author_name else {"@type": "Organization", "name": brand},
|
||||
"publisher": publisher,
|
||||
"mainEntityOfPage": _absolute(f"/blog/{article.slug}" if lang == "fa" else f"/en/blog/{en_slug}"),
|
||||
}
|
||||
image = _absolute(article.image) if (article.image or "").strip() else ""
|
||||
if image:
|
||||
schema["image"] = image
|
||||
published = _parse_site_date(article.date_en if lang == "en" else article.date) or _parse_site_date(article.date)
|
||||
if published:
|
||||
schema["datePublished"] = published
|
||||
return schema
|
||||
|
||||
|
||||
def _nav_label(db: Session, href: str, lang: str) -> str:
|
||||
"""برچسب فارسی/انگلیسی یک مسیر از ناوبری — برای پیشفرض عنوان و بردکرامب."""
|
||||
nav = db.query(models.NavItem).filter(models.NavItem.href == href).first()
|
||||
if nav is None:
|
||||
return ""
|
||||
return ((nav.label_en or nav.label) if lang == "en" else nav.label or "").strip()
|
||||
|
||||
|
||||
# ---------- robots.txt و sitemap.xml و llms.txt ----------
|
||||
|
||||
|
||||
@router.get("/robots.txt", response_class=Response)
|
||||
def robots(db: Session = Depends(get_db)):
|
||||
# پیشنمایش خصوصی — هیچ خزندهای نباید چیزی ذخیره کند
|
||||
if settings.preview_mode:
|
||||
return Response(
|
||||
content="User-agent: *\nDisallow: /\n",
|
||||
media_type="text/plain; charset=utf-8",
|
||||
)
|
||||
lines = ["User-agent: *", "Disallow: /admin", "Disallow: /api", ""]
|
||||
# سیاست صریح خزندههای هوش مصنوعی — رباتهای جستوجو/ارجاع آزادند تا محتوا
|
||||
# در پاسخهای ChatGPT/Claude/Perplexity/Gemini ارجاع شود
|
||||
for bot in AI_SEARCH_BOTS:
|
||||
lines += [f"User-agent: {bot}", "Allow: /", ""]
|
||||
# خزندهٔ تهاجمی با سود کم
|
||||
lines += ["User-agent: Bytespider", "Disallow: /", ""]
|
||||
if settings.site_url:
|
||||
lines.append(f"Sitemap: {_absolute('/sitemap.xml')}")
|
||||
return Response(content="\n".join(lines), media_type="text/plain; charset=utf-8")
|
||||
|
||||
|
||||
def _static_has_en(db: Session, page_key: str) -> bool:
|
||||
"""آیا صفحهٔ استاتیک ترجمهٔ انگلیسی واقعی دارد؟ (متای سئوی انگلیسی ثبت شده باشد)"""
|
||||
meta = _page_meta(db, page_key)
|
||||
return bool(
|
||||
meta
|
||||
and ((meta.title_en or "").strip() or (meta.description_en or "").strip())
|
||||
)
|
||||
|
||||
|
||||
@router.get("/sitemap.xml", response_class=Response)
|
||||
def sitemap(db: Session = Depends(get_db)):
|
||||
# پیشنمایش خصوصی — نقشه سایت خالی تا هیچ نشانیای اعلام نشود
|
||||
if settings.preview_mode:
|
||||
xml = (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>\n'
|
||||
)
|
||||
return Response(content=xml, media_type="application/xml; charset=utf-8")
|
||||
esc = html.escape
|
||||
|
||||
articles = {
|
||||
a.slug: a
|
||||
for a in db.query(models.Article)
|
||||
.filter(models.Article.status == "published")
|
||||
.order_by(models.Article.position, models.Article.id)
|
||||
.all()
|
||||
}
|
||||
projects = {
|
||||
p.slug: p for p in db.query(models.Project).order_by(models.Project.position, models.Project.id).all()
|
||||
}
|
||||
|
||||
def entry(loc: str, lang: str, has_en: bool) -> str:
|
||||
pairs = _alternate_pairs(loc, lang, has_en)
|
||||
links = "\n".join(
|
||||
f' <xhtml:link rel="alternate" hreflang="{code}" href="{esc(href_)}" />'
|
||||
for code, href_ in pairs
|
||||
)
|
||||
return f" <url><loc>{esc(_absolute(loc))}</loc>\n{links}\n </url>"
|
||||
|
||||
urls: list[str] = []
|
||||
# صفحات استاتیک فارسی + معادلهای انگلیسیِ ترجمهشده
|
||||
for path in STATIC_PATHS:
|
||||
page_key = "home" if path == "/" else path.strip("/")
|
||||
has_en = _static_has_en(db, page_key)
|
||||
urls.append(entry(path, "fa", has_en))
|
||||
if has_en:
|
||||
urls.append(entry(_en_path(path), "en", True))
|
||||
# مقالهها و پروژهها — alternate انگلیسی فقط با وجود ترجمهٔ واقعی
|
||||
for slug, article in articles.items():
|
||||
fa_path = f"/blog/{slug}"
|
||||
has_en = _article_has_en(article)
|
||||
urls.append(entry(fa_path, "fa", has_en))
|
||||
if has_en:
|
||||
urls.append(entry(_en_path(fa_path), "en", True))
|
||||
for slug, project in projects.items():
|
||||
fa_path = f"/projects/{slug}"
|
||||
has_en = _project_has_en(project)
|
||||
urls.append(entry(fa_path, "fa", has_en))
|
||||
if has_en:
|
||||
urls.append(entry(_en_path(fa_path), "en", True))
|
||||
xml = (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
|
||||
'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
|
||||
f"{chr(10).join(urls)}\n</urlset>\n"
|
||||
)
|
||||
return Response(content=xml, media_type="application/xml; charset=utf-8")
|
||||
|
||||
|
||||
@router.get("/llms.txt", response_class=Response)
|
||||
def llms_txt(db: Session = Depends(get_db)):
|
||||
"""راهنمای سایت برای دستیارهای هوش مصنوعی — برند، واقعیتهای کلیدی و صفحههای اصلی.
|
||||
در حالت پیشنمایش خصوصی ۴۰۴ میدهد تا ساختار سایت بیرون درز نکند."""
|
||||
if settings.preview_mode:
|
||||
return Response(status_code=404)
|
||||
brand = _brand_name(db, "en")
|
||||
_, home_desc = _meta_for(db, "home", "en")
|
||||
lines = [
|
||||
f"# {brand}",
|
||||
f"> {_clip(home_desc or 'Construction group — engineering, contracting and property investment.', 200)}",
|
||||
"",
|
||||
]
|
||||
services = [
|
||||
(s.title_en or s.title).strip()
|
||||
for s in db.query(models.Service).order_by(models.Service.position, models.Service.id).all()
|
||||
if (s.title_en or s.title).strip()
|
||||
]
|
||||
offices = db.query(models.Office).order_by(models.Office.position, models.Office.id).all()
|
||||
cities = [
|
||||
(o.city_en or o.city).strip() for o in offices if (o.city_en or o.city).strip()
|
||||
]
|
||||
facts = []
|
||||
if services:
|
||||
facts.append(f"- Services: {', '.join(services)}")
|
||||
if cities:
|
||||
facts.append(f"- Offices: {', '.join(sorted(set(cities)))}")
|
||||
facts.append("- Languages: Persian at / and English at /en")
|
||||
lines += ["## Key Facts", *facts, ""]
|
||||
lines.append("## Pages")
|
||||
for page_key, label in [
|
||||
("home", "Home"), ("about", "About"), ("services", "Services"),
|
||||
("projects", "Projects"), ("blog", "Blog"), ("faq", "FAQ"), ("contact", "Contact"),
|
||||
]:
|
||||
title, description = _meta_for(db, page_key, "en")
|
||||
if page_key == "home":
|
||||
url = "/"
|
||||
else:
|
||||
url = f"/en/{page_key}" if page_key != "projects" else "/en/projects"
|
||||
summary = _clip(description, 100)
|
||||
lines.append(f"- [{label}]({_absolute(url)}): {summary or label}")
|
||||
featured_projects = (
|
||||
db.query(models.Project).order_by(models.Project.position, models.Project.id).limit(6).all()
|
||||
)
|
||||
if featured_projects:
|
||||
lines += ["", "## Featured Projects"]
|
||||
for p in featured_projects:
|
||||
title = (p.title_en or p.title).strip()
|
||||
summary = _clip(p.summary_en or p.summary, 100)
|
||||
lines.append(f"- [{title}]({_absolute('/en/projects/' + p.slug)}): {summary}")
|
||||
latest = (
|
||||
db.query(models.Article)
|
||||
.filter(models.Article.status == "published")
|
||||
.order_by(models.Article.position, models.Article.id)
|
||||
.limit(6)
|
||||
.all()
|
||||
)
|
||||
if latest:
|
||||
lines += ["", "## Recent Articles"]
|
||||
for a in latest:
|
||||
title = (a.title_en or a.title).strip()
|
||||
summary = _clip(a.excerpt_en or a.excerpt, 100)
|
||||
lines.append(f"- [{title}]({_absolute('/en/blog/' + a.slug)}): {summary}")
|
||||
brand_row = _brand_row(db)
|
||||
contact_lines = []
|
||||
if brand_row and (brand_row.phone or "").strip():
|
||||
contact_lines.append(f"- Phone: {brand_row.phone.strip()}")
|
||||
if brand_row and (brand_row.email or "").strip():
|
||||
contact_lines.append(f"- Email: {brand_row.email.strip()}")
|
||||
for o in offices:
|
||||
city = (o.city_en or o.city).strip()
|
||||
street = ((o.address_en or o.address) or o.address).strip()
|
||||
if city or street:
|
||||
contact_lines.append(f"- Office: {_clip(street + ('، ' + city if city and street else city), 120)}")
|
||||
if contact_lines:
|
||||
lines += ["", "## Contact", *contact_lines]
|
||||
return Response(content="\n".join(lines) + "\n", media_type="text/plain; charset=utf-8")
|
||||
|
||||
|
||||
# ---------- صفحات استاتیک فارسی ----------
|
||||
|
||||
|
||||
def _static_shell(db: Session, *, path: str, page_key: str, lang: str = "fa") -> HTMLResponse:
|
||||
"""پوستهٔ صفحات استاتیک — متا از seo_meta، اسکیمای اختصاصی هر صفحه."""
|
||||
title, description = _meta_for(db, page_key, lang)
|
||||
brand = _brand_name(db, lang)
|
||||
if not title:
|
||||
# عنوان پیشفرض از برچسب ناوبری همان صفحه
|
||||
label = _nav_label(db, f"/{page_key}", lang)
|
||||
title = f"{label} | {brand}" if label else brand
|
||||
jsonld: list[dict] = []
|
||||
if page_key == "faq":
|
||||
faq_schema = _faq_page_jsonld(db, lang)
|
||||
if faq_schema:
|
||||
jsonld.append(faq_schema)
|
||||
elif page_key in ("contact", "about"):
|
||||
business = _localbusiness_jsonld(db, lang, path)
|
||||
if business:
|
||||
jsonld.append(business)
|
||||
return _shell(
|
||||
title=title,
|
||||
description=description,
|
||||
path=path,
|
||||
lang=lang,
|
||||
has_en=_static_has_en(db, page_key),
|
||||
jsonld=jsonld or None,
|
||||
org_jsonld=_org_jsonld(db, lang),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
def home(db: Session = Depends(get_db)):
|
||||
return _static_shell(db, path="/", page_key="home")
|
||||
|
||||
|
||||
@router.get("/about", response_class=HTMLResponse)
|
||||
def about_page(db: Session = Depends(get_db)):
|
||||
return _static_shell(db, path="/about", page_key="about")
|
||||
|
||||
|
||||
@router.get("/services", response_class=HTMLResponse)
|
||||
def services_page(db: Session = Depends(get_db)):
|
||||
return _static_shell(db, path="/services", page_key="services")
|
||||
|
||||
|
||||
@router.get("/investment", response_class=HTMLResponse)
|
||||
def investment_page(db: Session = Depends(get_db)):
|
||||
return _static_shell(db, path="/investment", page_key="investment")
|
||||
|
||||
|
||||
@router.get("/faq", response_class=HTMLResponse)
|
||||
def faq_page(db: Session = Depends(get_db)):
|
||||
return _static_shell(db, path="/faq", page_key="faq")
|
||||
|
||||
|
||||
@router.get("/contact", response_class=HTMLResponse)
|
||||
def contact_page(db: Session = Depends(get_db)):
|
||||
return _static_shell(db, path="/contact", page_key="contact")
|
||||
|
||||
|
||||
# ---------- صفحات وبلاگ ----------
|
||||
|
||||
|
||||
@router.get("/blog", response_class=HTMLResponse)
|
||||
def blog_list(db: Session = Depends(get_db)):
|
||||
return _static_shell(db, path="/blog", page_key="blog")
|
||||
|
||||
|
||||
@router.get("/blog/{slug}", response_class=HTMLResponse)
|
||||
def blog_detail(slug: str, db: Session = Depends(get_db)):
|
||||
article = (
|
||||
db.query(models.Article)
|
||||
.filter(models.Article.slug == slug, models.Article.status == "published")
|
||||
.first()
|
||||
)
|
||||
if article is None:
|
||||
# مقاله ناموجود یا پیشنویس — کد وضعیت ۴۰۴ تا خزنده صفحه را ایندکس نکند؛
|
||||
# SPA همان پیام «یافت نشد» را نشان میدهد
|
||||
return _shell(
|
||||
title=_brand_name(db), description="", path=f"/blog/{slug}",
|
||||
org_jsonld=_org_jsonld(db, "fa"), status_code=404,
|
||||
)
|
||||
|
||||
brand = _brand_name(db)
|
||||
title = article.title
|
||||
first_text = _doc_text(article.body) if not isinstance(article.body, list) else " ".join(article.body[:2])
|
||||
faq_schema = _faq_jsonld(article, "fa")
|
||||
breadcrumb = _breadcrumb_jsonld([
|
||||
(_nav_label(db, "/", "fa") or "خانه", "/"),
|
||||
(_nav_label(db, "/blog", "fa") or "وبلاگ", "/blog"),
|
||||
(title, f"/blog/{article.slug}"),
|
||||
])
|
||||
jsonld: list[dict] = [_article_jsonld(article, "fa", db), breadcrumb]
|
||||
if faq_schema:
|
||||
jsonld.append(faq_schema)
|
||||
noscript = f"<h1>{html.escape(title)}</h1><p>{html.escape(first_text)}</p>"
|
||||
return _shell(
|
||||
title=f"{title} | {brand}",
|
||||
description=_meta_desc_for(article, "fa"),
|
||||
path=f"/blog/{article.slug}",
|
||||
has_en=_article_has_en(article),
|
||||
og_image=article.image,
|
||||
og_image_alt=article.image_alt or title,
|
||||
og_type="article",
|
||||
jsonld=jsonld,
|
||||
org_jsonld=_org_jsonld(db, "fa"),
|
||||
noscript=noscript,
|
||||
)
|
||||
|
||||
|
||||
def _faq_jsonld(article: models.Article, lang: str) -> dict | None:
|
||||
"""اسکیمای FAQPage از پرسشوپاسخهای پایان مقاله."""
|
||||
entities = _faq_entities(article.faqs, lang, article.faqs_en)
|
||||
if not entities:
|
||||
return None
|
||||
return {"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": entities}
|
||||
|
||||
|
||||
# ---------- صفحات پروژه ----------
|
||||
|
||||
|
||||
@router.get("/projects", response_class=HTMLResponse)
|
||||
def projects_list(db: Session = Depends(get_db)):
|
||||
return _static_shell(db, path="/projects", page_key="projects")
|
||||
|
||||
|
||||
@router.get("/projects/{slug}", response_class=HTMLResponse)
|
||||
def project_detail(slug: str, db: Session = Depends(get_db)):
|
||||
project = db.query(models.Project).filter(models.Project.slug == slug).first()
|
||||
if project is None:
|
||||
return _shell(
|
||||
title=_brand_name(db), description="", path=f"/projects/{slug}",
|
||||
org_jsonld=_org_jsonld(db, "fa"), status_code=404,
|
||||
)
|
||||
|
||||
brand = _brand_name(db)
|
||||
jsonld = [
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "WebPage",
|
||||
"name": project.title,
|
||||
"description": project.summary,
|
||||
"image": _absolute(project.image),
|
||||
"inLanguage": "fa",
|
||||
},
|
||||
_breadcrumb_jsonld([
|
||||
(_nav_label(db, "/", "fa") or "خانه", "/"),
|
||||
(_nav_label(db, "/projects", "fa") or "پروژهها", "/projects"),
|
||||
(project.title, f"/projects/{project.slug}"),
|
||||
]),
|
||||
]
|
||||
return _shell(
|
||||
title=f"{project.title} | {brand}",
|
||||
description=project.summary,
|
||||
path=f"/projects/{project.slug}",
|
||||
has_en=_project_has_en(project),
|
||||
og_image=project.image,
|
||||
og_image_alt=project.title,
|
||||
jsonld=jsonld,
|
||||
org_jsonld=_org_jsonld(db, "fa"),
|
||||
)
|
||||
|
||||
|
||||
# ---------- صفحات انگلیسی (/en/...) ----------
|
||||
|
||||
|
||||
def _en_blog_detail(article: models.Article, db: Session) -> HTMLResponse:
|
||||
brand = _brand_name(db, "en")
|
||||
title = article.title_en or article.title
|
||||
body = article.body_en if isinstance(article.body_en, dict) else article.body
|
||||
first_text = _doc_text(body) if not isinstance(body, list) else " ".join(body[:2])
|
||||
faq_schema = _faq_jsonld(article, "en")
|
||||
breadcrumb = _breadcrumb_jsonld([
|
||||
(_nav_label(db, "/", "en") or "Home", "/"),
|
||||
(_nav_label(db, "/blog", "en") or "Blog", "/en/blog"),
|
||||
(title, f"/en/blog/{(article.slug_en or '').strip() or article.slug}"),
|
||||
])
|
||||
jsonld: list[dict] = [_article_jsonld(article, "en", db), breadcrumb]
|
||||
if faq_schema:
|
||||
jsonld.append(faq_schema)
|
||||
noscript = f"<h1>{html.escape(title)}</h1><p>{html.escape(first_text)}</p>"
|
||||
return _shell(
|
||||
title=f"{title} | {brand}",
|
||||
description=_meta_desc_for(article, "en"),
|
||||
path=f"/en/blog/{(article.slug_en or '').strip() or article.slug}",
|
||||
lang="en",
|
||||
has_en=_article_has_en(article),
|
||||
og_image=article.image,
|
||||
og_image_alt=article.image_alt or title,
|
||||
og_type="article",
|
||||
jsonld=jsonld,
|
||||
org_jsonld=_org_jsonld(db, "en"),
|
||||
noscript=noscript,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/en", response_class=HTMLResponse)
|
||||
@router.get("/en/", response_class=HTMLResponse)
|
||||
def en_home(db: Session = Depends(get_db)):
|
||||
return _static_shell(db, path="/en", page_key="home", lang="en")
|
||||
|
||||
|
||||
@router.get("/en/blog", response_class=HTMLResponse)
|
||||
def en_blog_list(db: Session = Depends(get_db)):
|
||||
return _static_shell(db, path="/en/blog", page_key="blog", lang="en")
|
||||
|
||||
|
||||
@router.get("/en/blog/{slug}", response_class=HTMLResponse)
|
||||
def en_blog_detail_route(slug: str, db: Session = Depends(get_db)):
|
||||
article = (
|
||||
db.query(models.Article)
|
||||
.filter(
|
||||
(models.Article.slug_en == slug)
|
||||
| ((models.Article.slug_en == "") & (models.Article.slug == slug)),
|
||||
models.Article.status == "published",
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if article is None:
|
||||
return _shell(
|
||||
title=_brand_name(db, "en"), description="", path=f"/en/blog/{slug}", lang="en",
|
||||
org_jsonld=_org_jsonld(db, "en"), status_code=404,
|
||||
)
|
||||
return _en_blog_detail(article, db)
|
||||
|
||||
|
||||
@router.get("/en/projects", response_class=HTMLResponse)
|
||||
def en_projects_list(db: Session = Depends(get_db)):
|
||||
return _static_shell(db, path="/en/projects", page_key="projects", lang="en")
|
||||
|
||||
|
||||
@router.get("/en/projects/{slug}", response_class=HTMLResponse)
|
||||
def en_project_detail(slug: str, db: Session = Depends(get_db)):
|
||||
project = db.query(models.Project).filter(models.Project.slug == slug).first()
|
||||
if project is None:
|
||||
return _shell(
|
||||
title=_brand_name(db, "en"), description="", path=f"/en/projects/{slug}", lang="en",
|
||||
org_jsonld=_org_jsonld(db, "en"), status_code=404,
|
||||
)
|
||||
|
||||
brand = _brand_name(db, "en")
|
||||
title = project.title_en or project.title
|
||||
summary = project.summary_en or project.summary
|
||||
jsonld = [
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "WebPage",
|
||||
"name": title,
|
||||
"description": summary,
|
||||
"image": _absolute(project.image),
|
||||
"inLanguage": "en",
|
||||
},
|
||||
_breadcrumb_jsonld([
|
||||
(_nav_label(db, "/", "en") or "Home", "/"),
|
||||
(_nav_label(db, "/projects", "en") or "Projects", "/en/projects"),
|
||||
(title, f"/en/projects/{project.slug}"),
|
||||
]),
|
||||
]
|
||||
return _shell(
|
||||
title=f"{title} | {brand}",
|
||||
description=summary,
|
||||
path=f"/en/projects/{project.slug}",
|
||||
lang="en",
|
||||
has_en=_project_has_en(project),
|
||||
og_image=project.image,
|
||||
og_image_alt=title,
|
||||
jsonld=jsonld,
|
||||
org_jsonld=_org_jsonld(db, "en"),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/en/{path:path}", response_class=HTMLResponse)
|
||||
def en_page(path: str, db: Session = Depends(get_db)):
|
||||
"""بقیه مسیرهای انگلیسی (about، services، ...) — متا از seo_meta به انگلیسی.
|
||||
مسیرهای ناشناخته ۴۰۴ میگیرند — پوستهٔ ۲۰۰ با عنوان برند، خطای soft-404 است."""
|
||||
page_key = path.split("/")[0] if path else ""
|
||||
if page_key not in META_KEYS:
|
||||
return _shell(
|
||||
title=_brand_name(db, "en"), description="", path=f"/en/{path}".rstrip("/"), lang="en",
|
||||
org_jsonld=_org_jsonld(db, "en"), status_code=404,
|
||||
)
|
||||
return _static_shell(db, path=f"/en/{path}".rstrip("/"), page_key=page_key, lang="en")
|
||||
@@ -0,0 +1,49 @@
|
||||
"""محیط Alembic — متادیتا از مدلهای SQLAlchemy میآید و آدرس دیتابیس از تنظیمات."""
|
||||
|
||||
import os
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
from app import models # noqa: F401 — ثبت مدلها در متادیتا
|
||||
from app.config import settings
|
||||
from app.database import Base
|
||||
|
||||
config = context.config
|
||||
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def get_url() -> str:
|
||||
return os.environ.get("DATABASE_URL", settings.database_url)
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(
|
||||
url=get_url(),
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
configuration = config.get_section(config.config_ini_section, {})
|
||||
configuration["sqlalchemy.url"] = get_url()
|
||||
connectable = engine_from_config(configuration, prefix="sqlalchemy.", poolclass=pool.NullPool)
|
||||
with connectable.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,25 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,25 @@
|
||||
"""نقطه شروع زنجیره مهاجرتها — جداول پایه با create_all ساخته میشوند.
|
||||
|
||||
ساخت اولیه ۲۹ جدول بر عهده Base.metadata.create_all است (در CMD کانتینر پیش از
|
||||
این مهاجرت اجرا میشود و برای دیتابیسهای موجود بیاثر است). از این نسخه به بعد
|
||||
هر تغییر اسکیما باید یک revision واقعی Alembic باشد — نه create_all و نه
|
||||
تغییر دستی — تا مسیر ارتقا و بازگشت آزمایشپذیر بماند.
|
||||
|
||||
Revision ID: 0001
|
||||
Revises:
|
||||
Create Date: 2026-09-18
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
revision: str = "0001"
|
||||
down_revision: Union[str, None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -0,0 +1,43 @@
|
||||
"""ستونهای چندزبانه مقاله — اسلاگ/کلیدواژه/نویسنده انگلیسی و تگهای دو زبانه.
|
||||
|
||||
فیلدهای «نویسنده» و «متا دیسکریپشن» در ادیتور تا پیش از این نسخه یا مشترک
|
||||
بودند یا بیاثر؛ از این نسخه هر زبان ستون خودش را دارد.
|
||||
|
||||
Revision ID: 0002
|
||||
Revises: 0001
|
||||
Create Date: 2026-10-01
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "0002"
|
||||
down_revision: Union[str, None] = "0001"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
articles = sa.table("articles")
|
||||
columns = sa.inspect(op.get_bind()).get_columns("articles")
|
||||
existing = {c["name"] for c in columns}
|
||||
if "slug_en" not in existing:
|
||||
op.add_column("articles", sa.Column("slug_en", sa.String(128), nullable=False, server_default=""))
|
||||
if "seo_keyphrase_en" not in existing:
|
||||
op.add_column("articles", sa.Column("seo_keyphrase_en", sa.String(128), nullable=False, server_default=""))
|
||||
if "author_en" not in existing:
|
||||
op.add_column("articles", sa.Column("author_en", sa.String(128), nullable=False, server_default=""))
|
||||
if "tags" not in existing:
|
||||
op.add_column("articles", sa.Column("tags", sa.JSON(), nullable=False, server_default="[]"))
|
||||
if "tags_en" not in existing:
|
||||
op.add_column("articles", sa.Column("tags_en", sa.JSON(), nullable=False, server_default="[]"))
|
||||
_ = articles
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("articles", "tags_en")
|
||||
op.drop_column("articles", "tags")
|
||||
op.drop_column("articles", "author_en")
|
||||
op.drop_column("articles", "seo_keyphrase_en")
|
||||
op.drop_column("articles", "slug_en")
|
||||
@@ -0,0 +1,31 @@
|
||||
"""لوگوی انگلیسی برند — ستون logo_en در جدول brand.
|
||||
|
||||
نسخهٔ انگلیسی سایت لوگوی اختصاصی خودش را دارد؛ فیلد مشترک logo برای هر دو
|
||||
زبان کافی نبود. بازگشت به فارسی با خالیبودن ستون انجام میشود.
|
||||
|
||||
Revision ID: 0003
|
||||
Revises: 0002
|
||||
Create Date: 2026-10-01
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "0003"
|
||||
down_revision: Union[str, None] = "0002"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
cols = sa.inspect(op.get_bind()).get_columns("brand")
|
||||
existing = {c["name"] for c in cols}
|
||||
if "logo_en" not in existing:
|
||||
op.add_column("brand", sa.Column("logo_en", sa.Text(), nullable=False, server_default=""))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
cols = sa.inspect(op.get_bind()).get_columns("brand")
|
||||
if "logo_en" in {c["name"] for c in cols}:
|
||||
op.drop_column("brand", "logo_en")
|
||||
@@ -0,0 +1,4 @@
|
||||
# وابستگیهای توسعه و تست — pip install -r requirements-dev.txt
|
||||
-r requirements.txt
|
||||
pytest==8.3.4
|
||||
httpx==0.27.2
|
||||
@@ -1,9 +1,21 @@
|
||||
fastapi>=0.115.8
|
||||
uvicorn[standard]>=0.34.0
|
||||
sqlalchemy>=2.0.36
|
||||
psycopg[binary]>=3.2.3
|
||||
pydantic>=2.10.4
|
||||
pydantic-settings>=2.6.1
|
||||
PyJWT>=2.10.1
|
||||
bcrypt>=4.2.1
|
||||
email-validator>=2.2.0
|
||||
# نسخهها دقیق پین شدهاند تا ارتقای خودکار یک وابستگی، استقرار را نشکند.
|
||||
# ارتقا: نسخه را دستی بالا ببرید و روی محیط آمادهسازی تست کنید.
|
||||
fastapi==0.115.8
|
||||
uvicorn[standard]==0.34.0
|
||||
sqlalchemy==2.0.36
|
||||
psycopg[binary]==3.2.3
|
||||
pydantic==2.10.4
|
||||
pydantic-settings==2.6.1
|
||||
PyJWT==2.10.1
|
||||
bcrypt==4.2.1
|
||||
email-validator==2.2.0
|
||||
boto3==1.35.0
|
||||
python-multipart==0.0.18
|
||||
# پاکسازی HTML سمت سرور (تیپتپ و فیلدهای غنی)
|
||||
nh3==0.2.20
|
||||
# بهینهسازی تصویر در زمان آپلود (تغییر اندازه/فشردهسازی مجدد)
|
||||
Pillow==11.1.0
|
||||
# متریکهای Prometheus برای مانیتورینگ (در /metrics داخلی)
|
||||
prometheus-fastapi-instrumentator==7.0.0
|
||||
# مهاجرتهای نسخهدار اسکیما
|
||||
alembic==1.14.0
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""پیکربندی تستها — دیتابیس SQLite فایلمحور و دادههای حداقلی.
|
||||
|
||||
متغیرهای محیطی پیش از ایمپورت app تنظیم میشوند تا settings همانها را بخواند.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
os.environ["DATABASE_URL"] = "sqlite:///./test.db?check_same_thread=false"
|
||||
os.environ["SECRET_KEY"] = "test-secret-key"
|
||||
os.environ["ADMIN_USERNAME"] = "admin"
|
||||
os.environ["ADMIN_PASSWORD"] = "test-admin-pass-1"
|
||||
os.environ["SITE_URL"] = "https://test.example"
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import models
|
||||
from app.auth import hash_password
|
||||
from app.config import settings
|
||||
from app.database import Base, SessionLocal, engine
|
||||
from app.main import app
|
||||
|
||||
TEST_DB = pathlib.Path("test.db")
|
||||
|
||||
DOC = {"type": "doc", "content": [{"type": "paragraph"}]}
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def seed_db(tmp_path_factory):
|
||||
# اتصالات ساخت جدول در ایمپورت ماژول باید بسته شوند تا فایل قدیمی حذف شود
|
||||
engine.dispose()
|
||||
if TEST_DB.exists():
|
||||
TEST_DB.unlink()
|
||||
Base.metadata.create_all(bind=engine)
|
||||
# dist ساختگی فرانتاند برای تست تزریق متا در صفحات جزئیات
|
||||
dist = tmp_path_factory.mktemp("dist")
|
||||
(dist / "index.html").write_text(
|
||||
"<!doctype html><html><head><title>Shell</title></head>"
|
||||
"<body><div id=\"root\"></div></body></html>",
|
||||
encoding="utf-8",
|
||||
)
|
||||
settings.frontend_dist = str(dist)
|
||||
settings.site_url = "https://test.example"
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
db.add(models.AdminUser(username="admin", password_hash=hash_password("test-admin-pass-1")))
|
||||
db.add(models.Brand(name="گروه ساختمانی آرامش"))
|
||||
db.add(
|
||||
models.Article(
|
||||
slug="published-post", title="مقاله منتشرشده", status="published",
|
||||
excerpt="چکیده مقاله", body=DOC, position=1,
|
||||
)
|
||||
)
|
||||
db.add(
|
||||
models.Article(
|
||||
slug="draft-post", title="پیشنویس", status="draft",
|
||||
excerpt="چکیده پیشنویس", body=DOC, position=2,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
yield
|
||||
db.close()
|
||||
engine.dispose()
|
||||
if TEST_DB.exists():
|
||||
TEST_DB.unlink()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reset_rate_limiter():
|
||||
from app import rate_limit
|
||||
|
||||
rate_limit._failed.clear()
|
||||
rate_limit.contact_limiter._events.clear()
|
||||
rate_limit.newsletter_limiter._events.clear()
|
||||
yield
|
||||
rate_limit._failed.clear()
|
||||
rate_limit.contact_limiter._events.clear()
|
||||
rate_limit.newsletter_limiter._events.clear()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def auth_client(client):
|
||||
res = client.post("/api/auth/login", json={"username": "admin", "password": "test-admin-pass-1"})
|
||||
assert res.status_code == 200, res.text
|
||||
token = res.json()["access_token"]
|
||||
client.headers.update({"Authorization": f"Bearer {token}"})
|
||||
yield client
|
||||
client.headers.pop("Authorization", None)
|
||||
@@ -0,0 +1,679 @@
|
||||
"""تستهای API — مسیرهای عمومی، احراز هویت، CRUD مدیریت، پیشنویس مقاله و سئو."""
|
||||
|
||||
import re
|
||||
import socket
|
||||
|
||||
DOC = {"type": "doc", "content": [{"type": "paragraph"}]}
|
||||
|
||||
|
||||
# ---------- عمومی ----------
|
||||
|
||||
|
||||
def test_live(client):
|
||||
"""liveness — پروسه زنده است، بدون وابستگی."""
|
||||
res = client.get("/api/live")
|
||||
assert res.status_code == 200
|
||||
assert res.json()["status"] == "ok"
|
||||
|
||||
|
||||
def test_health_deep(client):
|
||||
"""بررسی عمق — DB (SQLite در تست) سالم است؛ MinIO در محیط تست در دسترس نیست
|
||||
پس /api/health باید 503 و وضعیت degraded با جزئیات هر وابستگی بدهد."""
|
||||
res = client.get("/api/health")
|
||||
assert res.status_code == 503
|
||||
body = res.json()
|
||||
assert body["status"] == "degraded"
|
||||
assert body["checks"]["database"] == "ok"
|
||||
assert body["checks"]["storage"] == "error"
|
||||
|
||||
|
||||
def test_site_hides_draft_articles(client):
|
||||
res = client.get("/api/site")
|
||||
assert res.status_code == 200
|
||||
slugs = [a["slug"] for a in res.json()["articles"]]
|
||||
assert "published-post" in slugs
|
||||
assert "draft-post" not in slugs
|
||||
|
||||
|
||||
def test_public_articles_hide_drafts(client):
|
||||
res = client.get("/api/articles")
|
||||
assert all(a["status"] == "published" for a in res.json())
|
||||
assert client.get("/api/articles/draft-post").status_code == 404
|
||||
|
||||
|
||||
def test_admin_endpoints_reject_anonymous(client):
|
||||
assert client.get("/api/admin/articles").status_code == 401
|
||||
|
||||
|
||||
# ---------- احراز هویت ----------
|
||||
|
||||
|
||||
def test_login_success_and_failure(client):
|
||||
assert (
|
||||
client.post("/api/auth/login", json={"username": "admin", "password": "wrong"}).status_code
|
||||
== 401
|
||||
)
|
||||
res = client.post("/api/auth/login", json={"username": "admin", "password": "test-admin-pass-1"})
|
||||
assert res.status_code == 200
|
||||
assert res.json()["access_token"]
|
||||
|
||||
|
||||
def test_change_password(auth_client, client):
|
||||
res = auth_client.post(
|
||||
"/api/auth/change-password",
|
||||
json={"current_password": "wrong", "new_password": "brand-new-pass-9"},
|
||||
)
|
||||
assert res.status_code == 400
|
||||
|
||||
res = auth_client.post(
|
||||
"/api/auth/change-password",
|
||||
json={"current_password": "test-admin-pass-1", "new_password": "brand-new-pass-9"},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
|
||||
# رمز قدیمی رد و رمز جدید قبول میشود
|
||||
assert (
|
||||
client.post("/api/auth/login", json={"username": "admin", "password": "test-admin-pass-1"}).status_code
|
||||
== 401
|
||||
)
|
||||
assert (
|
||||
client.post("/api/auth/login", json={"username": "admin", "password": "brand-new-pass-9"}).status_code
|
||||
== 200
|
||||
)
|
||||
|
||||
# بازگرداندن رمز برای تستهای بعدی
|
||||
res = client.post("/api/auth/login", json={"username": "admin", "password": "brand-new-pass-9"})
|
||||
auth = {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||
res = client.post(
|
||||
"/api/auth/change-password",
|
||||
json={"current_password": "brand-new-pass-9", "new_password": "test-admin-pass-1"},
|
||||
headers=auth,
|
||||
)
|
||||
assert res.status_code == 200
|
||||
|
||||
|
||||
def test_login_rate_limited(client):
|
||||
for _ in range(5):
|
||||
res = client.post("/api/auth/login", json={"username": "admin", "password": "wrong"})
|
||||
assert res.status_code == 401
|
||||
res = client.post("/api/auth/login", json={"username": "admin", "password": "wrong"})
|
||||
assert res.status_code == 429
|
||||
assert "Retry-After" in res.headers
|
||||
|
||||
|
||||
# ---------- CRUD مدیریت ----------
|
||||
|
||||
|
||||
def test_article_crud_and_draft_flow(auth_client, client):
|
||||
created = auth_client.post(
|
||||
"/api/admin/articles",
|
||||
json={"slug": "flow-post", "title": "مقاله جریان", "body": DOC},
|
||||
)
|
||||
assert created.status_code == 201, created.text
|
||||
article = created.json()
|
||||
# مقاله تازه پیشنویس است و در سایت عمومی دیده نمیشود
|
||||
assert article["status"] == "draft"
|
||||
assert "flow-post" not in [a["slug"] for a in client.get("/api/articles").json()]
|
||||
|
||||
res = auth_client.patch(f"/api/admin/articles/{article['id']}", json={"seo_keyphrase": "ساختمان"})
|
||||
assert res.json()["seo_keyphrase"] == "ساختمان"
|
||||
|
||||
res = auth_client.patch(f"/api/admin/articles/{article['id']}", json={"status": "published"})
|
||||
assert res.status_code == 200
|
||||
assert "flow-post" in [a["slug"] for a in client.get("/api/articles").json()]
|
||||
|
||||
assert auth_client.delete(f"/api/admin/articles/{article['id']}").status_code == 204
|
||||
assert "flow-post" not in [a["slug"] for a in client.get("/api/articles").json()]
|
||||
|
||||
|
||||
def test_service_roundtrip_and_reorder(auth_client):
|
||||
ids = []
|
||||
for name in ("خدمت الف", "خدمت ب"):
|
||||
res = auth_client.post("/api/admin/services", json={"title": name})
|
||||
assert res.status_code == 201
|
||||
ids.append(res.json()["id"])
|
||||
|
||||
res = auth_client.post("/api/admin/services/reorder", json={"ids": ids[::-1]})
|
||||
assert res.status_code == 200
|
||||
ordered = [s["id"] for s in res.json() if s["id"] in ids]
|
||||
assert ordered == ids[::-1]
|
||||
|
||||
res = auth_client.patch(f"/api/admin/services/{ids[0]}", json={"desc": "توضیح تازه"})
|
||||
assert res.json()["desc"] == "توضیح تازه"
|
||||
|
||||
for i in ids:
|
||||
assert auth_client.delete(f"/api/admin/services/{i}").status_code == 204
|
||||
|
||||
|
||||
def test_seo_meta_create_and_patch(auth_client):
|
||||
res = auth_client.post(
|
||||
"/api/admin/seo-meta", json={"page_key": "test-page", "title": "عنوان", "description": "توضیح"}
|
||||
)
|
||||
assert res.status_code == 201
|
||||
meta_id = res.json()["id"]
|
||||
res = auth_client.patch(f"/api/admin/seo-meta/{meta_id}", json={"title": "عنوان تازه"})
|
||||
assert res.json()["title"] == "عنوان تازه"
|
||||
assert auth_client.delete(f"/api/admin/seo-meta/{meta_id}").status_code == 204
|
||||
|
||||
|
||||
# ---------- سئو ----------
|
||||
|
||||
|
||||
def test_robots_txt(client):
|
||||
res = client.get("/robots.txt")
|
||||
assert res.status_code == 200
|
||||
assert "Disallow: /admin" in res.text
|
||||
assert "Sitemap: https://test.example/sitemap.xml" in res.text
|
||||
|
||||
|
||||
def test_sitemap_includes_published_only(client):
|
||||
res = client.get("/sitemap.xml")
|
||||
assert res.status_code == 200
|
||||
assert "/blog/published-post" in res.text
|
||||
assert "/blog/draft-post" not in res.text
|
||||
assert res.text.startswith("<?xml")
|
||||
|
||||
|
||||
def test_head_injection_for_article(client):
|
||||
res = client.get("/blog/published-post")
|
||||
assert res.status_code == 200
|
||||
assert "مقاله منتشرشده" in res.text
|
||||
assert 'property="og:title"' in res.text
|
||||
assert "application/ld+json" in res.text
|
||||
assert "https://test.example/blog/published-post" in res.text
|
||||
|
||||
|
||||
def test_head_not_injected_for_draft(client):
|
||||
res = client.get("/blog/draft-post")
|
||||
assert res.status_code == 200
|
||||
assert "پیشنویس" not in res.text # عنوان پیشنویس افشا نمیشود
|
||||
assert "application/ld+json" not in res.text
|
||||
|
||||
|
||||
def test_head_replaces_title_once(client):
|
||||
res = client.get("/blog/published-post")
|
||||
assert len(re.findall(r"<title>", res.text)) == 1
|
||||
|
||||
|
||||
# ---------- دوزبانه ----------
|
||||
|
||||
|
||||
def test_bilingual_project_and_en_seo_shell(auth_client, client):
|
||||
created = auth_client.post(
|
||||
"/api/admin/projects",
|
||||
json={
|
||||
"slug": "bilingual-tower",
|
||||
"title": "برج دوزبانه",
|
||||
"title_en": "Bilingual Tower",
|
||||
"summary": "خلاصه فارسی",
|
||||
"summary_en": "English summary",
|
||||
"body": [],
|
||||
"body_en": ["English paragraph"],
|
||||
},
|
||||
)
|
||||
assert created.status_code == 201, created.text
|
||||
pid = created.json()["id"]
|
||||
|
||||
# GET /api/site هر دو زبان را برمیگرداند
|
||||
project = next(p for p in client.get("/api/site").json()["projects"] if p["slug"] == "bilingual-tower")
|
||||
assert project["title"] == "برج دوزبانه"
|
||||
assert project["title_en"] == "Bilingual Tower"
|
||||
assert project["body_en"] == ["English paragraph"]
|
||||
|
||||
# پوسته سئوی انگلیسی — جهت و متای انگلیسی و hreflang متقابل
|
||||
res = client.get("/en/projects/bilingual-tower")
|
||||
assert res.status_code == 200
|
||||
assert 'lang="en" dir="ltr"' in res.text
|
||||
assert "Bilingual Tower" in res.text
|
||||
assert "English summary" in res.text
|
||||
assert 'hreflang="fa"' in res.text
|
||||
assert "https://test.example/projects/bilingual-tower" in res.text
|
||||
assert "https://test.example/en/projects/bilingual-tower" in res.text
|
||||
|
||||
# sitemap دو زبانه با alternates
|
||||
sm = client.get("/sitemap.xml").text
|
||||
assert "xmlns:xhtml" in sm
|
||||
assert 'hreflang="en"' in sm
|
||||
assert "/en/projects/bilingual-tower" in sm
|
||||
|
||||
# پوسته فارسی هم alternates دارد
|
||||
assert 'hreflang="en"' in client.get("/blog/published-post").text
|
||||
|
||||
# صفحه استاتیک انگلیسی از مسیر catch-all سرو میشود
|
||||
res = client.get("/en/about")
|
||||
assert res.status_code == 200
|
||||
assert 'lang="en"' in res.text
|
||||
|
||||
assert auth_client.delete(f"/api/admin/projects/{pid}").status_code == 204
|
||||
assert "bilingual-tower" not in client.get("/sitemap.xml").text
|
||||
|
||||
|
||||
def test_bilingual_article_en_shell(auth_client, client):
|
||||
articles = auth_client.get("/api/admin/articles").json()
|
||||
article = next(a for a in articles if a["slug"] == "published-post")
|
||||
res = auth_client.patch(
|
||||
f"/api/admin/articles/{article['id']}",
|
||||
json={
|
||||
"title_en": "Published EN",
|
||||
"excerpt_en": "English excerpt",
|
||||
"body_en": DOC,
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
|
||||
res = client.get("/en/blog/published-post")
|
||||
assert res.status_code == 200
|
||||
assert "Published EN" in res.text
|
||||
assert "English excerpt" in res.text
|
||||
assert '"inLanguage": "en"' in res.text
|
||||
|
||||
|
||||
def test_en_backfill_fills_only_empty_fields(auth_client, client):
|
||||
"""backfill ترجمههای خالی را پر میکند و مقدار ثبتشده را بازنویسی نمیکند."""
|
||||
from app.migrations import backfill_en_content
|
||||
|
||||
backfill_en_content()
|
||||
brand = client.get("/api/site").json()["brand"]
|
||||
assert brand["name_en"] == "Aramesh Construction Group"
|
||||
|
||||
# مقدار دستیِ ادمین محترم شمرده میشود
|
||||
res = auth_client.patch(f"/api/admin/brand/{brand['id']}", json={"name_en": "Custom EN Name"})
|
||||
assert res.status_code == 200
|
||||
backfill_en_content()
|
||||
assert client.get("/api/site").json()["brand"]["name_en"] == "Custom EN Name"
|
||||
|
||||
|
||||
# ---------- محافظت فرمها و پاکسازی ----------
|
||||
|
||||
|
||||
def test_contact_honeypot_saves_nothing(client, auth_client):
|
||||
"""دامنهٔ پنهان پرشده یعنی ربات — پاسخ موفقِ قلابی، بدون ذخیره."""
|
||||
res = client.post(
|
||||
"/api/contact",
|
||||
json={"name": "ربات تستی", "phone": "09120000000", "website": "spam"},
|
||||
)
|
||||
assert res.status_code == 201
|
||||
assert res.json()["id"] == 0 # رکورد قلابی — در دیتابیس نیست
|
||||
assert auth_client.get("/api/admin/messages").json() == []
|
||||
|
||||
|
||||
def test_contact_rate_limited(client, auth_client):
|
||||
"""ارسال ششم در پنجرهٔ ۱۵ دقیقهای رد میشود (۵ مجاز برای هر IP)."""
|
||||
for _ in range(5):
|
||||
res = client.post(
|
||||
"/api/contact", json={"name": "کاربر تماس", "phone": "09120000000"}
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
res = client.post("/api/contact", json={"name": "کاربر تماس", "phone": "09120000000"})
|
||||
assert res.status_code == 429
|
||||
assert "Retry-After" in res.headers
|
||||
|
||||
|
||||
def test_newsletter_honeypot_saves_nothing(client, auth_client):
|
||||
res = client.post(
|
||||
"/api/newsletter", json={"email": "bot@example.com", "website": "spam"}
|
||||
)
|
||||
assert res.status_code == 201
|
||||
assert res.json()["id"] == 0
|
||||
assert auth_client.get("/api/admin/subscribers").json() == []
|
||||
|
||||
|
||||
def test_message_and_subscriber_csv_export(auth_client):
|
||||
auth_client.post("/api/contact", json={"name": "کاربر تماس", "phone": "09120000000"})
|
||||
res = auth_client.get("/api/admin/messages/export.csv")
|
||||
assert res.status_code == 200
|
||||
assert res.headers["content-type"].startswith("text/csv")
|
||||
assert "کاربر تماس" in res.text
|
||||
|
||||
auth_client.post("/api/newsletter", json={"email": "sale@example.com"})
|
||||
res = auth_client.get("/api/admin/subscribers/export.csv")
|
||||
assert res.status_code == 200
|
||||
assert "sale@example.com" in res.text
|
||||
|
||||
|
||||
def test_article_body_url_sanitization(auth_client):
|
||||
"""اسکیمهای خطرناک در href/src سند TipTap در زمان ذخیره حذف میشوند."""
|
||||
res = auth_client.post(
|
||||
"/api/admin/articles",
|
||||
json={
|
||||
"slug": "sanitized-post",
|
||||
"title": "مقاله پاکسازیشده",
|
||||
"status": "published",
|
||||
"body": {
|
||||
"type": "doc",
|
||||
"content": [
|
||||
{
|
||||
"type": "paragraph",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"marks": [
|
||||
{"type": "link", "attrs": {"href": "javascript:alert(1)"}},
|
||||
],
|
||||
"text": "لینک خطرناک",
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
assert res.status_code == 201, res.text
|
||||
body = res.json()["body"]
|
||||
marks = body["content"][0]["content"][0].get("marks", [])
|
||||
assert all("href" not in m.get("attrs", {}) for m in marks)
|
||||
|
||||
|
||||
# ---------- نامگذاری تصاویر، درونریزی و پرسشوپاسخ مقاله ----------
|
||||
|
||||
|
||||
class _FakeS3:
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.objects = {}
|
||||
|
||||
def put_object(self, **kwargs):
|
||||
self.objects[kwargs["Key"]] = kwargs["Body"]
|
||||
|
||||
|
||||
def _mock_storage(monkeypatch):
|
||||
"""MinIO در تست در دسترس نیست — کلاینت S3 و DNS عمومی جعل میشوند."""
|
||||
fake = _FakeS3()
|
||||
monkeypatch.setattr("app.api.admin.boto3.client", lambda *a, **k: fake)
|
||||
monkeypatch.setattr(
|
||||
"app.api.admin.socket.getaddrinfo",
|
||||
lambda host, port, *a, **k: [(socket.AF_INET, None, None, "", ("93.184.216.34", 0))],
|
||||
)
|
||||
return fake
|
||||
|
||||
|
||||
def _png_bytes() -> bytes:
|
||||
from PIL import Image
|
||||
import io
|
||||
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (8, 8), (200, 120, 60)).save(buf, "PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_upload_with_readable_name(auth_client, monkeypatch):
|
||||
_mock_storage(monkeypatch)
|
||||
res = auth_client.post(
|
||||
"/api/admin/upload",
|
||||
files={"file": ("raw name.png", _png_bytes(), "image/png")},
|
||||
data={"name": "برج الهیه tower!"},
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
key = res.json()["key"]
|
||||
# نام خوانا (فارسی/لاتین، بدون نویسه ناامن) + پسوند یکتا + نرمالشدن به WebP
|
||||
assert "برج-الهیه-tower" in key
|
||||
assert key.endswith(".webp")
|
||||
assert res.json()["content_type"] == "image/webp"
|
||||
assert "!" not in key
|
||||
|
||||
|
||||
def _animated_gif_bytes() -> bytes:
|
||||
from PIL import Image
|
||||
import io
|
||||
|
||||
buf = io.BytesIO()
|
||||
first = Image.new("RGB", (12, 8), (200, 120, 60))
|
||||
second = Image.new("RGB", (12, 8), (60, 120, 200))
|
||||
first.save(buf, "GIF", save_all=True, append_images=[second], duration=100, loop=0)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_upload_jpeg_converted_to_webp(auth_client, monkeypatch):
|
||||
_mock_storage(monkeypatch)
|
||||
from PIL import Image
|
||||
import io
|
||||
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (3000, 1500), (10, 10, 10)).save(buf, "JPEG", quality=90)
|
||||
res = auth_client.post(
|
||||
"/api/admin/upload",
|
||||
files={"file": ("tower.jpg", buf.getvalue(), "image/jpeg")},
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
body = res.json()
|
||||
assert body["content_type"] == "image/webp"
|
||||
assert body["key"].endswith(".webp")
|
||||
# سقف ضلع ۲۰۰۰ پیکسل روی خروجی اعمال شده
|
||||
assert body["width"] == 2000 and body["height"] == 1000
|
||||
|
||||
|
||||
def test_upload_animated_gif_becomes_static_webp(auth_client, monkeypatch):
|
||||
fake = _mock_storage(monkeypatch)
|
||||
res = auth_client.post(
|
||||
"/api/admin/upload",
|
||||
files={"file": ("anim.gif", _animated_gif_bytes(), "image/gif")},
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
assert res.json()["content_type"] == "image/webp"
|
||||
from PIL import Image
|
||||
import io
|
||||
|
||||
stored = next(iter(fake.objects.values()))
|
||||
out = Image.open(io.BytesIO(stored))
|
||||
assert out.format == "WEBP"
|
||||
# هیچ آپلودی هرگز متحرک ذخیره نمیشود — پوستر فریم اول
|
||||
assert getattr(out, "n_frames", 1) == 1
|
||||
|
||||
|
||||
def test_upload_undecodable_file_rejected(auth_client, monkeypatch):
|
||||
_mock_storage(monkeypatch)
|
||||
res = auth_client.post(
|
||||
"/api/admin/upload",
|
||||
files={"file": ("notes.txt", b"this is not a media file at all", "text/plain")},
|
||||
)
|
||||
assert res.status_code == 415
|
||||
|
||||
|
||||
def test_upload_video_becomes_static_webp_poster(auth_client, monkeypatch):
|
||||
# ویدیو تنها با FFmpeg قابل پذیرش است — بدون آن ۴۱۵، با آن پوستر تکفریمی WebP
|
||||
import shutil as _shutil
|
||||
import subprocess as _subprocess
|
||||
import tempfile as _tempfile
|
||||
import os as _os
|
||||
|
||||
fake = _mock_storage(monkeypatch)
|
||||
if _shutil.which("ffmpeg") is None:
|
||||
res = auth_client.post(
|
||||
"/api/admin/upload",
|
||||
files={"file": ("clip.mp4", b"\x00\x00\x00\x18ftypmp42", "video/mp4")},
|
||||
)
|
||||
assert res.status_code == 415
|
||||
return
|
||||
|
||||
with _tempfile.TemporaryDirectory() as tmp:
|
||||
clip = _os.path.join(tmp, "clip.mp4")
|
||||
_subprocess.run(
|
||||
["ffmpeg", "-y", "-v", "error", "-f", "lavfi",
|
||||
"-i", "testsrc=duration=0.5:size=128x96:rate=10", clip],
|
||||
check=True, capture_output=True, timeout=30,
|
||||
)
|
||||
with open(clip, "rb") as fh:
|
||||
clip_bytes = fh.read()
|
||||
|
||||
res = auth_client.post(
|
||||
"/api/admin/upload",
|
||||
files={"file": ("clip.mp4", clip_bytes, "video/mp4")},
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
assert res.json()["content_type"] == "image/webp"
|
||||
from PIL import Image
|
||||
import io
|
||||
|
||||
stored = next(iter(fake.objects.values()))
|
||||
out = Image.open(io.BytesIO(stored))
|
||||
# ویدیو هرگز وب متحرک نمیشود — در کارتها سوسو نمیزند
|
||||
assert getattr(out, "n_frames", 1) == 1
|
||||
|
||||
|
||||
def test_upload_without_name_uses_filename(auth_client, monkeypatch):
|
||||
_mock_storage(monkeypatch)
|
||||
res = auth_client.post(
|
||||
"/api/admin/upload",
|
||||
files={"file": ("Elahieh Tower.jpg", _png_bytes(), "image/jpeg")},
|
||||
data={"name": ""},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert "Elahieh-Tower" in res.json()["key"]
|
||||
|
||||
|
||||
def test_import_image_rejects_internal_host(auth_client):
|
||||
# SSRF — میزبان حلقهمحلی/خصوصی رد میشود پیش از هر درخواست شبکه
|
||||
res = auth_client.post("/api/admin/import-image", json={"url": "http://127.0.0.1:9000/x.png"})
|
||||
assert res.status_code == 400
|
||||
res = auth_client.post("/api/admin/import-image", json={"url": "http://192.168.1.5/x.png"})
|
||||
assert res.status_code == 400
|
||||
res = auth_client.post("/api/admin/import-image", json={"url": "file:///etc/passwd"})
|
||||
assert res.status_code == 400
|
||||
|
||||
|
||||
def test_import_image_rejects_bad_content_type(auth_client, monkeypatch):
|
||||
_mock_storage(monkeypatch)
|
||||
import io as _io
|
||||
|
||||
class FakeResponse:
|
||||
def __init__(self):
|
||||
self.headers = {"Content-Type": "text/html"}
|
||||
|
||||
def read(self, n):
|
||||
return b"<html></html>"
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
def fake_urlopen(request, timeout):
|
||||
return FakeResponse()
|
||||
|
||||
monkeypatch.setattr("app.api.admin.urllib.request.urlopen", fake_urlopen)
|
||||
res = auth_client.post("/api/admin/import-image", json={"url": "https://example.com/page"})
|
||||
assert res.status_code == 415
|
||||
|
||||
|
||||
def test_import_image_happy_path(auth_client, monkeypatch):
|
||||
_mock_storage(monkeypatch)
|
||||
class FakeResponse:
|
||||
def __init__(self):
|
||||
self.headers = {"Content-Type": "image/png"}
|
||||
|
||||
def read(self, n):
|
||||
return _png_bytes()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr("app.api.admin.urllib.request.urlopen", lambda request, timeout: FakeResponse())
|
||||
res = auth_client.post("/api/admin/import-image", json={"url": "https://wiki.example/Elahieh pic.png?token=1"})
|
||||
assert res.status_code == 200, res.text
|
||||
assert res.json()["url"].startswith("/media/")
|
||||
assert res.json()["key"].endswith(".webp")
|
||||
assert "Elahieh-pic" in res.json()["key"]
|
||||
|
||||
|
||||
def test_article_persists_image_meta_and_faqs(auth_client, client):
|
||||
created = auth_client.post(
|
||||
"/api/admin/articles",
|
||||
json={"slug": "meta-article", "title": "متادیتا", "body": DOC},
|
||||
)
|
||||
assert created.status_code == 201, created.text
|
||||
article_id = created.json()["id"]
|
||||
|
||||
faqs = [{"question": "هزینه چقدر است؟", "answer": "بستگی به پروژه دارد."}]
|
||||
res = auth_client.patch(
|
||||
f"/api/admin/articles/{article_id}",
|
||||
json={
|
||||
"image_alt": "نمای برج الهیه",
|
||||
"image_title": "برج آرامش",
|
||||
"faqs": faqs,
|
||||
"faqs_en": [{"question": "What is the cost?", "answer": "Depends on the project."}],
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
assert res.json()["image_alt"] == "نمای برج الهیه"
|
||||
assert res.json()["image_title"] == "برج آرامش"
|
||||
assert res.json()["faqs"] == faqs
|
||||
|
||||
# انتشار و سپس خروجی عمومی — همین مقادیر برمیگردد
|
||||
assert auth_client.patch(f"/api/admin/articles/{article_id}", json={"status": "published"}).status_code == 200
|
||||
public = client.get("/api/articles/meta-article").json()
|
||||
assert public["image_alt"] == "نمای برج الهیه"
|
||||
assert public["faqs"] == faqs
|
||||
|
||||
assert auth_client.delete(f"/api/admin/articles/{article_id}").status_code == 204
|
||||
|
||||
|
||||
def test_blog_shell_includes_faqpage_jsonld(auth_client, client):
|
||||
created = auth_client.post(
|
||||
"/api/admin/articles",
|
||||
json={
|
||||
"slug": "faq-article",
|
||||
"title": "مقاله پرسشوپاسخ",
|
||||
"body": DOC,
|
||||
"status": "published",
|
||||
"faqs": [{"question": "زمان ساخت؟", "answer": "۳۰ ماه."}],
|
||||
},
|
||||
)
|
||||
assert created.status_code == 201, created.text
|
||||
|
||||
res = client.get("/blog/faq-article")
|
||||
assert res.status_code == 200
|
||||
assert "FAQPage" in res.text
|
||||
assert "زمان ساخت؟" in res.text
|
||||
|
||||
# نسخه انگلیسی بدون ترجمه → همان فارسی؛ با ترجمه → انگلیسی
|
||||
en = client.get("/en/blog/faq-article").text
|
||||
assert "FAQPage" in en
|
||||
article_id = created.json()["id"]
|
||||
auth_client.patch(
|
||||
f"/api/admin/articles/{article_id}",
|
||||
json={"faqs_en": [{"question": "How long?", "answer": "Thirty months."}]},
|
||||
)
|
||||
en = client.get("/en/blog/faq-article").text
|
||||
assert "How long?" in en
|
||||
assert "زمان ساخت؟" not in en
|
||||
|
||||
auth_client.delete(f"/api/admin/articles/{article_id}")
|
||||
|
||||
|
||||
def test_blog_shell_without_faqs_has_no_faqpage(client):
|
||||
res = client.get("/blog/published-post")
|
||||
assert res.status_code == 200
|
||||
assert "FAQPage" not in res.text
|
||||
|
||||
|
||||
# ---------- پیشنمایش خصوصی (برای انتشار عمومی خاموش میشود) ----------
|
||||
|
||||
|
||||
def test_preview_mode_blocks_robots_and_sitemap(client, monkeypatch):
|
||||
from app.config import settings
|
||||
|
||||
monkeypatch.setattr(settings, "preview_mode", True)
|
||||
try:
|
||||
robots = client.get("/robots.txt")
|
||||
assert robots.status_code == 200
|
||||
assert "Disallow: /" in robots.text
|
||||
assert "Sitemap:" not in robots.text
|
||||
|
||||
sitemap = client.get("/sitemap.xml")
|
||||
assert sitemap.status_code == 200
|
||||
assert "published-post" not in sitemap.text
|
||||
|
||||
# لایه دوم: هدر noindex روی همه پاسخها
|
||||
assert "noindex" in client.get("/api/health").headers.get("X-Robots-Tag", "")
|
||||
finally:
|
||||
monkeypatch.setattr(settings, "preview_mode", False)
|
||||
|
||||
|
||||
def test_public_mode_allows_indexing(client):
|
||||
robots = client.get("/robots.txt").text
|
||||
assert "Disallow: /admin" in robots
|
||||
assert "Sitemap:" in robots
|
||||
assert "noindex" not in client.get("/api/health").headers.get("X-Robots-Tag", "")
|
||||
@@ -0,0 +1,12 @@
|
||||
# کانتکست بیلد باریک
|
||||
__pycache__/
|
||||
**/__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
venv/
|
||||
.env
|
||||
.env.*
|
||||
README.md
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
test_pure.py
|
||||
@@ -0,0 +1,28 @@
|
||||
# سرویس چتبات — این مقادیر را در .env ریشه پروژه بگذارید (نه اینجا)
|
||||
# این فایل فقط مستندسازی متغیرهاست.
|
||||
|
||||
# --- اجباری ---
|
||||
# دیتابیس سایت (فقط خواندن) — در داکر از docker-compose.yml تزریق میشود
|
||||
# DATABASE_URL=postgresql+psycopg://aramesh:PASSWORD@db:5432/arameshplaza
|
||||
|
||||
# LLM سازگار با OpenAI — بدون این چتبات پاسخ نمیدهد
|
||||
# مثال سرور داخلی: LLM_BASE_URL=http://172.16.22.21:4460/v1
|
||||
# مثال سرویس ابری: LLM_BASE_URL=https://api.example.com/v1
|
||||
LLM_BASE_URL=
|
||||
LLM_API_KEY=
|
||||
LLM_MODEL=openai/gpt-oss-120b
|
||||
|
||||
# --- اختیاری ---
|
||||
# توکن محافظت از POST /chat/reindex — اگر خالی باشد مسیر ۴۰۳ میدهد
|
||||
CHAT_REINDEX_TOKEN=
|
||||
# ریرنکر را روی سرور کمرم خاموش کنید (RERANKER_ENABLED=false)
|
||||
RERANKER_ENABLED=true
|
||||
# وزن جستوجوی معنایی در ترکیب نمرهها (۰ تا ۱) — پیشفرض ۰.۵
|
||||
ALPHA_DENSE=0.5
|
||||
# تعداد سند نهایی به LLM — پیشفرض ۳
|
||||
BEST_OF_K=3
|
||||
# بازسازی خودکار ایندکس پس از تغییر محتوا (ثانیه، ۰ = خاموش)
|
||||
INDEX_REFRESH_SECONDS=600
|
||||
# محدودیت نرخ: حداکثر پیام در پنجره زمانی (پیشفرض ۲۰ پیام در ۳۰۰ ثانیه)
|
||||
RATE_LIMIT_MESSAGES=20
|
||||
RATE_LIMIT_WINDOW=300
|
||||
@@ -0,0 +1,34 @@
|
||||
# سرویس چتبات — پایتون + مدلهای بازیابی (CPU)
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /srv
|
||||
|
||||
# همهٔ وابستگیهای سنگین (numpy/scikit-learn/torch/psycopg) ویل prebuilt دارند —
|
||||
# بدون کامپایلر؛ دسترسی apt در شبکهٔ بیلد قابلاعتماد نیست
|
||||
COPY requirements.txt /srv/chatbot/requirements.txt
|
||||
# torch روی PyPI پیشفرض لینوکس نسخهٔ CUDA است و کل استک nvidia را میآورد
|
||||
# (ایمیج ~۹.۷GB روی سرور بدون GPU). نسخهٔ CPU حدود ۲۰۰MB است — همین اول نصب
|
||||
# میشود تا pip در گام بعد آن را برآوردهشده ببیند.
|
||||
# روی ماشینی با GPU میتوان این خط را حذف کرد.
|
||||
RUN pip install --no-cache-dir --index-url https://download.pytorch.org/whl/cpu "torch>=2.2"
|
||||
RUN pip install --no-cache-dir -r /srv/chatbot/requirements.txt
|
||||
|
||||
COPY . /srv/chatbot/
|
||||
|
||||
# مدل امبدینگ/ریرنکر در /data کش میشود (والیوم داکر) — بردارها در pgvector میروند و فایل ایندکس جدا وجود ندارد
|
||||
ENV HF_HOME=/data/hf \
|
||||
HF_CACHE_DIR=/data/hf
|
||||
VOLUME /data
|
||||
|
||||
# کاربر بدون دسترسی root — فقط /data باید نوشتنی باشد (کش مدلها)
|
||||
RUN useradd --system --create-home appuser \
|
||||
&& mkdir -p /data \
|
||||
&& chown -R appuser:appuser /srv/chatbot /data
|
||||
USER appuser
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=180s --retries=5 \
|
||||
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/chat/healthz')" || exit 1
|
||||
|
||||
CMD ["uvicorn", "chatbot.app:api", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips=*"]
|
||||
@@ -0,0 +1,144 @@
|
||||
# دستیار هوشمند سایت (چتبات)
|
||||
|
||||
سرویس گفتگوی محتوای سایت «گروه ساختمانی آرامش» — بازدیدکننده به فارسی سؤال میپرسد و
|
||||
دستیار **فقط از روی محتوای خود سایت** (مقالهها، پروژهها، خدمات، سؤالات متداول، اطلاعات تماس و…)
|
||||
پاسخ میدهد؛ اگر پاسخ در محتوا نباشد، بهجای ساخت جواب، صادقانه اعلام میکند.
|
||||
|
||||
این سرویس پورت خط لولهٔ پروژهٔ `llm-srerver-chatbot` (نسخه v13) با چهار تغییر اصلی برای این سایت است:
|
||||
|
||||
1. **پایگاه sparse بهجای SPLADE از BM25 استفاده میکند** — SPLADE انگلیسیمحور است و روی
|
||||
فارسی عملاً بیفایده؛ BM25 با نرمالسازی فارسی (ی/ک عربی، اعراب، ارقام، نیمفاصله) جایگزین شده است.
|
||||
2. **ذخیرهساز برداری pgvector است، نه FAISS** — بردارها در یک دیتابیس جدا (`aramesh_chatbot`)
|
||||
روی همان نمونه Postgres نگهداری میشوند؛ همگامسازی افزایشی است (فقط سطرهای جدید/تغییریافته
|
||||
امبد میشوند)، بکاپگیری با خود دیتابیس است و فایل ایندکس جدا وجود ندارد.
|
||||
3. **تأخیر کمتر** — مسیریابی `alpha` با LLM و گسترش چندپرسشی (multi-query) بهصورت پیشفرض
|
||||
خاموشاند (با متغیر محیطی قابل فعالسازی)؛ بازنویسی پرسش فقط وقتی تاریخچه گفتگو وجود دارد اجرا میشود.
|
||||
4. **استریم واقعی توکنبهتوکن** با `astream_events` بهجای دیف پیامهای کامل.
|
||||
|
||||
## خط لوله هر پیام
|
||||
|
||||
```
|
||||
پرسش کاربر
|
||||
│
|
||||
├─[اگر تاریخچه هست] بازنویسی پرسش با LLM (حل ضمیرها و اشارهها: «اون دومی» → موضوع واقعی)
|
||||
│
|
||||
├─ بازیابی ترکیبی: pgvector (معنایی، کسینوسی روی HNSW — MiniLM چندزبانه)
|
||||
│ + BM25 (کلیدواژه، متن نرمالشده فارسی)
|
||||
│ نمرهها min-max → ترکیب α×معنایی + (1-α)×کلیدواژه
|
||||
│
|
||||
├─ برش خوشهای (K-Means K=2 + silhouette ≥ 0.55) — مرز طبیعی کیفیت
|
||||
│
|
||||
├─ ریرنک با BAAI/bge-reranker-v2-m3 → نگهداشتن ۳ سند برتر
|
||||
│
|
||||
└─ تولید پاسخ فارسی با LLM (قواعد تکیه بر داده + معرفی صفحه مرتبط + پیام جایگزین مشخص)
|
||||
```
|
||||
|
||||
ایندکس از محتوای PostgreSQL سایت ساخته میشود (`articles` منتشرشده + پرسشوپاسخهای
|
||||
پایان مقاله، `projects` با مشخصات کامل، `services`، `faqs`، `brand`، `offices`،
|
||||
`investment_models`، `process_steps`، `why_us`، `team`، `testimonials`، `timeline`،
|
||||
`story`، و متنهای مدیریت محتوا: `stats`، `hero`، `page_heroes`، `section_headings`،
|
||||
`footer`، `before_after`). سطرهای جایگاهخالی (متن زیر ~۳۰ نویسه) ایندکس نمیشوند.
|
||||
متنهای بلند به قطعات ~۷۰۰ نویسهای همپوشان برش میخورند.
|
||||
|
||||
- **ایندکس برداری در pgvector**: جدول `chatbot_chunks` در دیتابیس اختصاصی
|
||||
`aramesh_chatbot` (روی همان نمونه Postgres) با ستون `embedding vector(384)` و
|
||||
ایندکس HNSW کسینوسی؛ هر قطعه `doc_id` پایدار (شامل url: `type:url-key:occ:chunk`)
|
||||
و `content_hash` دارد و همگامسازی فقط سطرهای جدید/تغییریافته را امبد میکند.
|
||||
دیتابیس و جدول در شروع سرویس خودکار ساخته میشوند.
|
||||
- **تیتر در متن قطعه**: در سندهای تکقطعهای که تیترشان در متن نیست (مثلاً نام پروژه)،
|
||||
تیتر به ابتدای متن میچسبد تا BM25 و جستوجوی معنایی پیدایش کنند.
|
||||
- **بازسازی خودکار**: یک حلقهٔ پسزمینه هر `INDEX_REFRESH_SECONDS` ثانیه محتوا را چک
|
||||
میکند و اگر ادمین چیزی را در پنل عوض کرده باشد، فقط تغییرات همگام میشود
|
||||
(امبد اجباری همه: `POST /chat/reindex`).
|
||||
- **ماندگاری گفتگو**: در حافظهٔ همان پروسه (MemorySaver لنگگراف) — با ریاستارت پاک میشود.
|
||||
- **گزارش گفتگوها**: هر پاسخ (بههمراه تعداد سند بازیابیشده، تشخیص «پاسخی نبود» و تأخیر)
|
||||
در جدول `chat_logs` همان دیتابیس ذخیره میشود تا پرسشهای بیپاسخ — یعنی شکافهای
|
||||
دانش — قابل کشف باشند؛ `GET /chat/stats` جمعبندی میدهد.
|
||||
|
||||
## متغیرهای محیطی (در `.env` ریشه پروژه)
|
||||
|
||||
| متغیر | پیشفرض | توضیح |
|
||||
|---|---|---|
|
||||
| `LLM_BASE_URL` | خالی | **اجباری** — نشانی سرویس LLM سازگار با OpenAI. بدون آن چتبات بالا میآید ولی پاسخ نمیدهد |
|
||||
| `LLM_API_KEY` | خالی | کلید API (برای سرور داخلی `not-needed` بگذارید) |
|
||||
| `LLM_MODEL` | `openai/gpt-oss-120b` | نام مدل |
|
||||
| `CHAT_REINDEX_TOKEN` | خالی | توکن `POST /chat/reindex` — اگر خالی باشد آن مسیر ۴۰۳ میدهد |
|
||||
| `CHATBOT_DB_NAME` | `aramesh_chatbot` | نام دیتابیس اختصاصی چتبات روی همان نمونه Postgres (بردارها اینجا میروند) |
|
||||
| `EMBEDDING_DIM` | `384` | بعد بردار مدل امبدینگ — با تعویض مدل امبدینگ باید هماهنگ شود |
|
||||
| `RERANKER_ENABLED` | `true` | روی سرور کمرم (زیر ~۴GB) `false` بگذارید |
|
||||
| `ALPHA_DENSE` | `0.5` | وزن جستوجوی معنایی در ترکیب نمرهها (۰ تا ۱) |
|
||||
| `BEST_OF_K` | `3` | تعداد سند نهایی که به LLM میرود |
|
||||
| `INDEX_REFRESH_SECONDS` | `600` | بازسازی خودکار ایندکس پس از تغییر محتوا (۰ = خاموش) |
|
||||
| `RATE_LIMIT_MESSAGES` / `RATE_LIMIT_WINDOW` | `20` / `300` | سقف پیام هر IP در پنجره زمانی (ثانیه) |
|
||||
|
||||
`DATABASE_URL` در داکر از `docker-compose.yml` تزریق میشود — دیتابیس سایت فقط خوانده
|
||||
میشود و نوشتن (بردارها) فقط در دیتابیس جدا `aramesh_chatbot` انجام میگیرد.
|
||||
|
||||
## پیشنیاز pgvector
|
||||
|
||||
سرویس `db` استک از ایمیج `pgvector/pgvector:pg17` استفاده میکند (همان postgres:17 +
|
||||
افزونهٔ vector). اگر Postgres سایت روی نمونهٔ دیگری است، باید افزونهٔ pgvector روی آن
|
||||
فعال باشد؛ در غیر این صورت شروع چتبات با خطای واضح متوقف میشود.
|
||||
|
||||
## مسیرها
|
||||
|
||||
| مسیر | توضیح |
|
||||
|---|---|
|
||||
| `GET /chat/stream?message=…&thread_id=…` | استریم SSE توکنبهتوکن پاسخ (`{"content": …}` و در پایان `{"done": true, "fallback": true|false}`) |
|
||||
| `GET /chat/suggestions` | ۴ پیشنهاد پرسش (کش ۱۰ دقیقه؛ جایگزین: خود سؤالات متداول) |
|
||||
| `GET /chat/eval?message=…` | مخصوص ارزیابی — پاسخ + اسناد بازیابیشده با thread تازه |
|
||||
| `GET /chat/stats` | آمار گفتگوها (کل، ۷ روز اخیر، نرخ پیام جایگزین)؛ فهرست پرسشهای بیپاسخ اخیر فقط با هدر `X-Reindex-Token` |
|
||||
| `GET /chat/healthz` | وضعیت ایندکس/LLM/تعداد اسناد |
|
||||
| `POST /chat/reindex` | بازسازی اجباری ایندکس (هدر `X-Reindex-Token`) |
|
||||
|
||||
مسیرهای `GET /chat/{scope}/stream|eval|suggestions` هم برای سازگاری با اسکریپت
|
||||
`eval_ragas.py` قدیمی موجود است — کافی است `--url` را به نشانی این سرویس بدهید.
|
||||
|
||||
## ارزیابی
|
||||
|
||||
مجموعه طلایی `eval_set.json` (پرسشهای واقعی از محتوای دیتابیس + یک کنترل مثبت برای
|
||||
«نباید قیمت بسازد») با `eval_run.py` اجرا میشود — داخل کانتینر:
|
||||
|
||||
```bash
|
||||
docker exec aramesh-site-chatbot-1 python /srv/chatbot/eval_run.py --out /tmp/report.md
|
||||
docker exec aramesh-site-chatbot-1 cat /tmp/report.md
|
||||
```
|
||||
|
||||
خروجی: وضعیت هر پرسش (`pass` / `miss` / `manual` / `fallback-expected` / `unexpected-fallback`)،
|
||||
منابع بازیابیشده و زمان پاسخ — برای سنجش اثر تغییرات دانش و کشف پسرفتها.
|
||||
|
||||
## اجرا
|
||||
|
||||
با داکر (بخشی از استک اصلی است — `docker compose up -d --build`):
|
||||
|
||||
```bash
|
||||
# در .env ریشه:
|
||||
LLM_BASE_URL=http://172.16.22.21:4460/v1 # یا هر سرویس سازگار با OpenAI
|
||||
LLM_API_KEY=not-needed
|
||||
```
|
||||
|
||||
اولین بوت مدلها را دانلود میکند (~۱.۵GB: امبدینگ + ریرنکر) و در والیوم
|
||||
`chatbot_cache` کش میشود؛ بوتهای بعدی چند ثانیه طول میکشد.
|
||||
|
||||
اجرای محلی بدون داکر:
|
||||
|
||||
```bash
|
||||
cd chatbot
|
||||
python -m venv .venv && source .venv/bin/activate # ویندوز: .venv\Scripts\activate
|
||||
pip install -r requirements.txt
|
||||
export DATABASE_URL="postgresql+psycopg://aramesh:PASS@localhost:5432/arameshplaza"
|
||||
export LLM_BASE_URL="http://…" LLM_MODEL="openai/gpt-oss-120b"
|
||||
uvicorn chatbot.app:api --port 8000 # از ریشه پوشه والد
|
||||
```
|
||||
|
||||
## منابع مورد نیاز
|
||||
|
||||
- **رم**: با ریرنکر ~۴GB (مدل ۵۶۸M پارامتری روی CPU)؛ بدون ریرنکر ~۲GB
|
||||
- **CPU**: امبدینگ و ریرنک روی CPU اجرا میشوند؛ GPU لازم نیست
|
||||
- **شبکه**: دسترسی به PostgreSQL و به نشانی `LLM_BASE_URL`
|
||||
|
||||
## نکات امنیتی
|
||||
|
||||
- دیتابیس سایت فقط **خواندن**؛ نوشتن فقط در دیتابیس اختصاصی `aramesh_chatbot` انجام میشود
|
||||
- محدودسازی نرخ per-IP فعال است (پیشفرض ۲۰ پیام در ۵ دقیقه)
|
||||
- CORS باز است ولی کوکی/اعتبارنامهای رد و بدل نمیشود؛ در تولید همهچیز هممبدأ (پشت Traefik) است
|
||||
@@ -0,0 +1 @@
|
||||
"""سرویس چتبات سایت آرامش — بازیابی ترکیبی روی محتوای PostgreSQL."""
|
||||
@@ -0,0 +1,315 @@
|
||||
"""سرویس چتبات سایت آرامش — FastAPI با استریم SSE و بازیابی ترکیبی روی محتوای دیتابیس."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from collections import defaultdict, deque
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Query, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from langchain_core.messages import AIMessage, HumanMessage
|
||||
|
||||
from . import content as content_mod
|
||||
from . import pipeline
|
||||
from . import vectorstore
|
||||
from .config import settings
|
||||
from .indexing import INDEX, sync_index
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
||||
)
|
||||
log = logging.getLogger("chatbot")
|
||||
|
||||
|
||||
# --- چرخه حیات: ساخت ایندکس در شروع + بازسازی خودکار وقتی محتوا عوض شود ---
|
||||
|
||||
_refresh_task: asyncio.Task | None = None
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
try:
|
||||
await asyncio.to_thread(sync_index)
|
||||
except Exception as e:
|
||||
log.critical("Initial index sync failed: %s — chat will be unavailable until reindex", e)
|
||||
global _refresh_task
|
||||
_refresh_task = asyncio.create_task(_refresh_loop())
|
||||
yield
|
||||
_refresh_task.cancel()
|
||||
|
||||
|
||||
async def _refresh_loop() -> None:
|
||||
interval = settings.index_refresh_seconds
|
||||
if interval <= 0:
|
||||
return
|
||||
while True:
|
||||
await asyncio.sleep(interval)
|
||||
try:
|
||||
# همگامسازی افزایشی است — فقط سطرهای جدید/تغییریافته امبد میشوند
|
||||
await asyncio.to_thread(sync_index)
|
||||
except Exception as e:
|
||||
log.warning("Background index refresh failed: %s", e)
|
||||
|
||||
|
||||
api = FastAPI(
|
||||
title="Aramesh Site Chatbot",
|
||||
version="1.0.0",
|
||||
description="دستیار گفتگوی محتوای سایت — بازیابی ترکیبی (pgvector + BM25) با ریرنکر BGE",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
api.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=False,
|
||||
allow_methods=["GET", "POST"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
# --- محدودسازی نرخ درخواست سبک در حافظه (پنجره لغزان per-IP) ---
|
||||
|
||||
_hits: dict[str, deque] = defaultdict(deque)
|
||||
_last_sweep = 0.0
|
||||
|
||||
|
||||
def _rate_limited(ip: str) -> bool:
|
||||
global _last_sweep
|
||||
now = time.time()
|
||||
# پاکسازی دورهای کلیدهای بیمصرف تا دیکشنری بینهایت بزرگ نشود
|
||||
if now - _last_sweep > settings.rate_limit_window:
|
||||
stale = [k for k, q in _hits.items() if not q or now - q[-1] > settings.rate_limit_window]
|
||||
for k in stale:
|
||||
_hits.pop(k, None)
|
||||
_last_sweep = now
|
||||
window = _hits[ip]
|
||||
while window and now - window[0] > settings.rate_limit_window:
|
||||
window.popleft()
|
||||
if len(window) >= settings.rate_limit_messages:
|
||||
return True
|
||||
window.append(now)
|
||||
return False
|
||||
|
||||
|
||||
def _client_ip(request: Request | None) -> str:
|
||||
if request is None:
|
||||
return "?"
|
||||
forwarded = request.headers.get("x-forwarded-for")
|
||||
return forwarded.split(",")[0].strip() if forwarded else (request.client.host if request.client else "?")
|
||||
|
||||
|
||||
# --- کمکیهای SSE ---
|
||||
|
||||
def _sse(payload: dict) -> str:
|
||||
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
def _chunk_text(chunk) -> str:
|
||||
"""استخراج متن از قطعه استریم LLM (رشته یا لیست بخشها)."""
|
||||
content = getattr(chunk, "content", "")
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
return "".join(p.get("text", "") for p in content if isinstance(p, dict))
|
||||
return ""
|
||||
|
||||
|
||||
async def _stream_answer(message: str, thread_id: str):
|
||||
if not INDEX.ready:
|
||||
yield _sse({"error": "ایندکس محتوا هنوز آماده نیست؛ چند لحظه بعد دوباره تلاش کنید.", "done": True})
|
||||
return
|
||||
if pipeline.get_llm() is None:
|
||||
yield _sse({"error": pipeline.LLM_UNAVAILABLE, "done": True})
|
||||
return
|
||||
|
||||
config = {"configurable": {"thread_id": thread_id}}
|
||||
inputs = {"messages": [HumanMessage(content=message)]}
|
||||
started = time.time()
|
||||
answer_parts: list[str] = []
|
||||
try:
|
||||
async for event in pipeline.graph.astream_events(inputs, config=config, version="v2"):
|
||||
# فقط توکنهای پاسخ نهایی — نه فراخوانیهای کمکی (بازنویسی/گسترش پرسش)
|
||||
if event["event"] == "on_chat_model_stream" and "generate" in (event.get("tags") or []):
|
||||
text = _chunk_text(event["data"]["chunk"])
|
||||
if text:
|
||||
answer_parts.append(text)
|
||||
yield _sse({"content": text, "done": False})
|
||||
|
||||
# وضعیت نهایی گراف: تعداد اسناد بازیابیشده — برای تشخیص «پاسخی نبود»
|
||||
n_docs = 0
|
||||
try:
|
||||
state = await pipeline.graph.aget_state(config)
|
||||
n_docs = len(state.values.get("documents") or [])
|
||||
except Exception as e:
|
||||
log.warning("Final state fetch failed: %s", e)
|
||||
answer = "".join(answer_parts)
|
||||
is_fallback = n_docs == 0 or answer.strip() == pipeline.FALLBACK_MESSAGE
|
||||
await asyncio.to_thread(
|
||||
vectorstore.log_chat, thread_id, message, answer, n_docs, is_fallback,
|
||||
int((time.time() - started) * 1000),
|
||||
)
|
||||
yield _sse({"content": "", "done": True, "fallback": is_fallback})
|
||||
except Exception as e:
|
||||
log.exception("Streaming failed")
|
||||
yield _sse({"error": f"خطا در تولید پاسخ: {e}", "done": True})
|
||||
|
||||
|
||||
# --- مسیرها ---
|
||||
|
||||
@api.get("/chat/healthz")
|
||||
async def healthz():
|
||||
return {
|
||||
"status": "ok",
|
||||
"index_ready": INDEX.ready,
|
||||
"documents": len(INDEX.docs),
|
||||
"vectors": await asyncio.to_thread(vectorstore.vector_count),
|
||||
"llm_configured": bool(settings.llm_base_url),
|
||||
"reranker_enabled": settings.reranker_enabled,
|
||||
}
|
||||
|
||||
|
||||
@api.get("/chat/suggestions")
|
||||
async def suggestions():
|
||||
return {"questions": _get_suggestions()}
|
||||
|
||||
|
||||
@api.get("/chat/eval")
|
||||
async def eval_question(message: str = Query(...)):
|
||||
"""مخصوص ارزیابی RAGAS — پاسخ + اسناد بازیابیشده، با thread تازه."""
|
||||
if not INDEX.ready:
|
||||
return {"error": "index not ready", "question": message, "answer": "", "contexts": []}
|
||||
if pipeline.get_llm() is None:
|
||||
return {"error": "llm not configured", "question": message, "answer": "", "contexts": []}
|
||||
|
||||
thread_id = f"eval_{uuid.uuid4().hex[:10]}"
|
||||
config = {"configurable": {"thread_id": thread_id}}
|
||||
inputs = {"messages": [HumanMessage(content=message)]}
|
||||
final_state = await pipeline.graph.ainvoke(inputs, config=config)
|
||||
|
||||
answer = ""
|
||||
for msg in reversed(final_state.get("messages", [])):
|
||||
if isinstance(msg, AIMessage):
|
||||
answer = msg.content if isinstance(msg.content, str) else str(msg.content)
|
||||
break
|
||||
return {
|
||||
"question": message,
|
||||
"contextualized_query": final_state.get("contextualized_query") or message,
|
||||
"answer": answer,
|
||||
"contexts": final_state.get("documents", []),
|
||||
"thread_id": thread_id,
|
||||
}
|
||||
|
||||
|
||||
@api.get("/chat/stats")
|
||||
async def chat_stats(request: Request):
|
||||
"""آمار گفتگوها — جمعبندی برای همه؛ پرسشهای بیپاسخ اخیر فقط با توکن."""
|
||||
stats = await asyncio.to_thread(vectorstore.chat_stats)
|
||||
payload = {
|
||||
"total_logged": stats["total_logged"],
|
||||
"last_7d": stats["last_7d"],
|
||||
"fallback_7d": stats["fallback_7d"],
|
||||
}
|
||||
if settings.reindex_token and request.headers.get("x-reindex-token") == settings.reindex_token:
|
||||
payload["recent_fallback_questions"] = stats["recent_fallback_questions"]
|
||||
return payload
|
||||
|
||||
|
||||
@api.post("/chat/reindex")
|
||||
async def reindex(request: Request):
|
||||
"""همگامسازی اجباری (امبد دوباره همه سطرها) — با توکن محافظت میشود."""
|
||||
if settings.reindex_token and request.headers.get("x-reindex-token") != settings.reindex_token:
|
||||
raise HTTPException(status_code=403, detail="invalid reindex token")
|
||||
stats = await asyncio.to_thread(sync_index, True)
|
||||
return {"status": "ok", "documents": len(INDEX.docs), "stats": stats}
|
||||
|
||||
|
||||
# سازگاری با eval_ragas.py قدیمی که آدرس را /chat/{username}/eval میسازد
|
||||
|
||||
@api.get("/chat/{scope}/stream")
|
||||
async def stream_chat_scoped(scope: str, message: str = Query(...), thread_id: str = Query(default=""), request: Request = None):
|
||||
return await stream_chat(message=message, thread_id=thread_id, request=request)
|
||||
|
||||
|
||||
@api.get("/chat/{scope}/eval")
|
||||
async def eval_scoped(scope: str, message: str = Query(...)):
|
||||
return await eval_question(message=message)
|
||||
|
||||
|
||||
@api.get("/chat/{scope}/suggestions")
|
||||
async def suggestions_scoped(scope: str):
|
||||
return {"questions": _get_suggestions()}
|
||||
|
||||
|
||||
@api.get("/chat/stream")
|
||||
async def stream_chat(message: str = Query(...), thread_id: str = Query(default=""), request: Request = None):
|
||||
"""استریم توکنبهتوکن پاسخ با SSE."""
|
||||
if _rate_limited(_client_ip(request)):
|
||||
raise HTTPException(status_code=429, detail="تعداد پیامهای شما زیاد است؛ کمی بعد دوباره تلاش کنید.")
|
||||
|
||||
thread_id = thread_id or f"t_{uuid.uuid4().hex[:10]}"
|
||||
|
||||
async def generate():
|
||||
async for chunk in _stream_answer(message, thread_id):
|
||||
yield chunk
|
||||
|
||||
return StreamingResponse(
|
||||
generate(),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
|
||||
|
||||
# --- پیشنهاد پرسشها (کششده) ---
|
||||
|
||||
_suggestions_cache: tuple[float, list[str]] = (0.0, [])
|
||||
|
||||
|
||||
def _get_suggestions() -> list[str]:
|
||||
global _suggestions_cache
|
||||
now = time.time()
|
||||
if _suggestions_cache[1] and now - _suggestions_cache[0] < settings.suggestions_ttl:
|
||||
return _suggestions_cache[1]
|
||||
|
||||
questions: list[str] = []
|
||||
if INDEX.ready:
|
||||
faqs = [d for d in INDEX.docs if d["type"] == "faq"][:8]
|
||||
titles = [d["title"] for d in INDEX.docs if d["type"] == "article"][:10]
|
||||
model = pipeline.get_llm()
|
||||
if model and (faqs or titles):
|
||||
material = "\n".join([d["text"][:200] for d in faqs] + titles)
|
||||
try:
|
||||
prompt = (
|
||||
"بر اساس محتوای سایت «گروه ساختمانی آرامش» ۴ پرسش کوتاه و جذاب بنویس که بازدیدکننده "
|
||||
"احتمالاً میپرسد. هر پرسش حداکثر ۱۰ کلمه و به فارسی.\n"
|
||||
'فقط آرایه JSON رشتهای برگردان: ["پرسش ۱", "پرسش ۲", ...]\n\n'
|
||||
f"محتوا:\n{material[:2000]}"
|
||||
)
|
||||
resp = model.invoke([HumanMessage(content=prompt)])
|
||||
text = resp.content if isinstance(resp.content, str) else ""
|
||||
if text.startswith("```"):
|
||||
text = text.split("```")[1]
|
||||
text = text[4:] if text.startswith("json") else text
|
||||
import re
|
||||
match = re.search(r"\[.*\]", text, re.DOTALL)
|
||||
if match:
|
||||
questions = [q.strip() for q in json.loads(match.group()) if isinstance(q, str) and q.strip()][:4]
|
||||
except Exception as e:
|
||||
log.warning("Suggestion generation failed: %s", e)
|
||||
if not questions and faqs:
|
||||
# جایگزین: خود پرسشهای متداول
|
||||
questions = [d["text"].split("\n")[0].removeprefix("پرسش: ") for d in faqs[:4]]
|
||||
|
||||
_suggestions_cache = (now, questions)
|
||||
return questions
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(api, host="0.0.0.0", port=8000)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""تنظیمات سرویس چتبات — از متغیرهای محیطی یا فایل .env خوانده میشود."""
|
||||
|
||||
from pydantic import AliasChoices, Field
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
||||
|
||||
# دیتابیس سایت (فقط خواندن) — همان DATABASE_URL بکاند
|
||||
database_url: str = "postgresql+psycopg://aramesh:aramesh@localhost:5432/arameshplaza"
|
||||
# دیتابیس اختصاصی چتبات روی همان نمونه Postgres — بردارها اینجا نوشته میشوند
|
||||
# تا دیتابیس سایت فقطخواندنی بماند؛ در شروع سرویس خودکار ساخته میشود
|
||||
chatbot_db_name: str = "aramesh_chatbot"
|
||||
|
||||
# LLM سازگار با OpenAI — اجباری؛ بدون آن پاسخگویی غیرفعال است
|
||||
llm_base_url: str = ""
|
||||
llm_api_key: str = ""
|
||||
llm_model: str = "openai/gpt-oss-120b"
|
||||
|
||||
# مدلهای بازیابی
|
||||
embedding_model: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
|
||||
# بعد بردار خروجی مدل امبدینگ (MiniLM-L12 = 384) — با تغییر مدل باید عوض شود
|
||||
embedding_dim: int = 384
|
||||
reranker_model: str = "BAAI/bge-reranker-v2-m3"
|
||||
reranker_enabled: bool = True
|
||||
reranker_device: str = "cpu"
|
||||
|
||||
# وزن جستوجوی معنایی در ترکیب نمرهها (۰ = فقط کلیدواژه، ۱ = فقط معنایی)
|
||||
alpha_dense: float = 0.5
|
||||
# تعداد سند نهایی که به LLM داده میشود
|
||||
best_of_k: int = 3
|
||||
# تعداد نتیجه هر پایگاه (معنایی و کلیدواژه) برای هر پرسوجو
|
||||
retrieve_k: int = 12
|
||||
# بازنویسی پرسوجو با تاریخچه گفتگو (فقط وقتی تاریخچه هست صدا زده میشود)
|
||||
contextualize_enabled: bool = True
|
||||
# گسترش پرسوجو به چند نوع — برای پیکره کوچک پیشفرض خاموش (تأخیر کمتر)
|
||||
query_expansion: bool = False
|
||||
|
||||
# مسیر کش مدلها (در داکر روی والیوم /data سوار میشود)
|
||||
hf_cache_dir: str = "/data/hf"
|
||||
|
||||
# محدودسازی نرخ درخواست هر IP (تعداد پیام در پنجره زمانی به ثانیه)
|
||||
rate_limit_messages: int = 20
|
||||
rate_limit_window: int = 300
|
||||
|
||||
# توکن بازسازی ایندکس — اگر خالی باشد مسیر reindex فقط از داخل شبکه کار میکند
|
||||
# (.env از نام CHAT_REINDEX_TOKEN استفاده میکند — هر دو نام پذیرفته میشود)
|
||||
reindex_token: str = Field(
|
||||
default="", validation_alias=AliasChoices("REINDEX_TOKEN", "CHAT_REINDEX_TOKEN")
|
||||
)
|
||||
|
||||
# ماندگاری کش پیشنهادها و زمینه سایت (ثانیه)
|
||||
suggestions_ttl: int = 600
|
||||
site_context_ttl: int = 120
|
||||
|
||||
# بازسازی خودکار ایندکس وقتی محتوای دیتابیس عوض شود (۰ = خاموش)
|
||||
index_refresh_seconds: int = 600
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,473 @@
|
||||
"""خواندن محتوای سایت از PostgreSQL و تبدیل آن به سندهای قابل ایندکس.
|
||||
|
||||
هر سند یک dict با کلیدهای text / type / title / url است. بدنه مقالهها و
|
||||
پروژهها هم میتواند آرایه پاراگراف باشد و هم سند TipTap (JSON) — هر دو
|
||||
پشتیبانی میشوند. مقالههای پیشنویس ایندکس نمیشوند؛ اما پرسشوپاسخهای
|
||||
پایان مقالههای منتشرشده بهعنوان سند faq ایندکس میشوند.
|
||||
|
||||
بهجز جدولهای محتوایی، متنهای مدیریت محتوا (آمار، هیرو، هیرو صفحهها،
|
||||
تیتر بخشها، فوتر، قبل/بعد) هم ایندکس میشوند — ادعاهای مرکزی سایت
|
||||
(سال تجربه، تعداد پروژه و…) فقط آنجا ثبت شدهاند.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from .persian import normalize
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# URL پایه صفحات — چتبات مسیر نسبی میدهد؛ فرانتاند روی همان دامنه است
|
||||
_ARTICLE_URL = "/blog/{slug}"
|
||||
_PROJECT_URL = "/projects/{slug}"
|
||||
|
||||
# بخشهای صفحه اصلی و صفحات داخلی — برای نسبت دادن URL به تیتر بخشها
|
||||
_SECTION_URL = {
|
||||
"services": "/services",
|
||||
"featured_projects": "/projects",
|
||||
"articles": "/blog",
|
||||
"faq": "/faq",
|
||||
"investment_models": "/investment",
|
||||
"process": "/investment",
|
||||
}
|
||||
|
||||
# سندهای کوتاهتر از این جایگاهخالیاند («خدمت جدید» و امثال آن) — ایندکس نمیشوند
|
||||
_MIN_DOC_CHARS = 30
|
||||
|
||||
|
||||
def _psycopg_dsn(database_url: str) -> str:
|
||||
"""DATABASE_URL فرمت SQLAlchemy (postgresql+psycopg://) را به DSN psycopg3 تبدیل میکند."""
|
||||
return database_url.replace("+psycopg", "").replace("+asyncpg", "")
|
||||
|
||||
|
||||
def _fetch_rows(dsn: str, sql: str) -> list[dict[str, Any]]:
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
with psycopg.connect(dsn, row_factory=dict_row, connect_timeout=10) as conn:
|
||||
cur = conn.execute(sql)
|
||||
return cur.fetchall()
|
||||
|
||||
|
||||
def tiptap_blocks(node: Any) -> list[str]:
|
||||
"""متن بلوکبهبلوک از سند TipTap (یا هر JSON تو در تو) بیرون میکشد."""
|
||||
if not isinstance(node, dict):
|
||||
return []
|
||||
ntype = node.get("type")
|
||||
if ntype in ("paragraph", "heading", "codeBlock"):
|
||||
text = _inline_text(node).strip()
|
||||
return [text] if text else []
|
||||
blocks: list[str] = []
|
||||
for child in node.get("content") or []:
|
||||
blocks.extend(tiptap_blocks(child))
|
||||
return blocks
|
||||
|
||||
|
||||
def _inline_text(node: dict) -> str:
|
||||
parts: list[str] = []
|
||||
for child in node.get("content") or []:
|
||||
ctype = child.get("type")
|
||||
if ctype == "text":
|
||||
parts.append(child.get("text", ""))
|
||||
elif ctype == "hardBreak":
|
||||
parts.append(" ")
|
||||
elif ctype == "image":
|
||||
alt = (child.get("attrs") or {}).get("alt") or ""
|
||||
if alt:
|
||||
parts.append(f"[تصویر: {alt}]")
|
||||
else:
|
||||
parts.append(_inline_text(child))
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def body_to_text(body: Any) -> str:
|
||||
"""بدنه مقاله/پروژه (آرایه پاراگراف یا سند TipTap) → متن یکپارچه."""
|
||||
if not body:
|
||||
return ""
|
||||
if isinstance(body, list):
|
||||
# فرمت قدیمی: آرایه رشتهای پاراگرافها
|
||||
return "\n".join(str(p).strip() for p in body if str(p).strip())
|
||||
blocks = tiptap_blocks(body)
|
||||
return "\n".join(b for b in blocks if b)
|
||||
|
||||
|
||||
def _doc(text: str, dtype: str, title: str, url: str) -> dict | None:
|
||||
text = (text or "").strip()
|
||||
if len(text) < _MIN_DOC_CHARS:
|
||||
if text:
|
||||
log.info("Skipped tiny doc (%d chars, type=%s, title=%s)", len(text), dtype, title)
|
||||
return None
|
||||
return {"text": text, "type": dtype, "title": title, "url": url}
|
||||
|
||||
|
||||
def _clean(value: Any) -> str:
|
||||
return normalize(str(value or "")).strip()
|
||||
|
||||
|
||||
def _format_stat_rows(rows: list[dict[str, Any]]) -> list[str]:
|
||||
"""سطرهای جدول stats → «۲۳+ سال تجربه ساخت» (پسوند تکحرفی میچسبد، بقیه با فاصله)."""
|
||||
parts: list[str] = []
|
||||
for r in rows:
|
||||
suffix = _clean(r.get("suffix"))
|
||||
value = str(r.get("value") or "").strip()
|
||||
if not value:
|
||||
continue
|
||||
num = f"{value}{suffix}" if len(suffix) == 1 else f"{value} {suffix}".strip()
|
||||
parts.append(f"{num} {_clean(r.get('label'))}".strip())
|
||||
return parts
|
||||
|
||||
|
||||
def fetch_site_documents(database_url: str) -> list[dict]:
|
||||
"""همه محتوای عمومی سایت را به سند تبدیل میکند (بدون وابستگی به ORM بکاند)."""
|
||||
dsn = _psycopg_dsn(database_url)
|
||||
docs: list[dict] = []
|
||||
|
||||
# --- برند و اطلاعات تماس (رکورد یگانه) ---
|
||||
brand_rows = _fetch_rows(dsn, "SELECT name, phone, email, address FROM brand LIMIT 1")
|
||||
if brand_rows:
|
||||
b = brand_rows[0]
|
||||
contact = "\n".join(
|
||||
filter(None, [
|
||||
f"نام مجموعه: {_clean(b['name'])}",
|
||||
f"تلفن تماس: {_clean(b['phone'])}",
|
||||
f"ایمیل: {_clean(b['email'])}",
|
||||
f"آدرس: {_clean(b['address'])}",
|
||||
])
|
||||
)
|
||||
d = _doc(contact, "contact", "اطلاعات تماس", "/contact")
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- آمار و افتخارات — اعداد مرکزی سایت فقط اینجا ثبتاند ---
|
||||
stats = _format_stat_rows(_fetch_rows(dsn, "SELECT value, suffix, label FROM stats ORDER BY position"))
|
||||
if stats:
|
||||
d = _doc("آمار و افتخارات مجموعه: " + "؛ ".join(stats), "stats", "آمار و افتخارات", "/")
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- هیرو صفحه اصلی (رکورد یگانه) ---
|
||||
hero_rows = _fetch_rows(
|
||||
dsn,
|
||||
"SELECT kicker, title, title_highlight, subtitle, badge_value, badge_label FROM hero LIMIT 1",
|
||||
)
|
||||
if hero_rows:
|
||||
h = hero_rows[0]
|
||||
title = _clean(h["title"])
|
||||
if _clean(h["title_highlight"]):
|
||||
title = f"{title} (کلمهٔ برجسته: {_clean(h['title_highlight'])})"
|
||||
lines = list(filter(None, [
|
||||
f"شعار بالای تیتر: {_clean(h['kicker'])}" if _clean(h["kicker"]) else "",
|
||||
f"تیتر اصلی: {title}" if title else "",
|
||||
f"زیرتیتر: {_clean(h['subtitle'])}" if _clean(h["subtitle"]) else "",
|
||||
(
|
||||
f"نشان: {_clean(h['badge_value'])} {_clean(h['badge_label'])}"
|
||||
if _clean(h["badge_value"]) or _clean(h["badge_label"]) else ""
|
||||
),
|
||||
]))
|
||||
d = _doc("\n".join(lines), "hero", "معرفی صفحه اصلی", "/")
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- دفاتر ---
|
||||
for row in _fetch_rows(dsn, "SELECT city, address, hours FROM offices ORDER BY position"):
|
||||
d = _doc(
|
||||
f"دفتر {_clean(row['city'])} — آدرس: {_clean(row['address'])} — ساعت کاری: {_clean(row['hours'])}",
|
||||
"office", f"دفتر {_clean(row['city'])}", "/contact",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- خدمات ---
|
||||
for row in _fetch_rows(dsn, 'SELECT title, "desc" FROM services ORDER BY position'):
|
||||
d = _doc(
|
||||
f"خدمت «{_clean(row['title'])}»: {_clean(row['desc'])}",
|
||||
"service", _clean(row["title"]), "/services",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- پرسشهای متداول ---
|
||||
for row in _fetch_rows(dsn, "SELECT question, answer FROM faqs ORDER BY position"):
|
||||
d = _doc(
|
||||
f"پرسش: {_clean(row['question'])}\nپاسخ: {_clean(row['answer'])}",
|
||||
"faq", _clean(row["question"]), "/faq",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- پروژهها (شامل پروژههای نقشهٔ صفحه پروژهها — فقط مشخصات، بدون توضیح) ---
|
||||
for row in _fetch_rows(
|
||||
dsn,
|
||||
"""
|
||||
SELECT slug, title, location, year, status, area, floors, land_area, pilot_floors,
|
||||
units_residential, units_commercial, units_office, client,
|
||||
project_type, usage, summary, body
|
||||
FROM projects ORDER BY position
|
||||
""",
|
||||
):
|
||||
units = "، ".join(
|
||||
f"{v} واحد {label}"
|
||||
for label, col in (("مسکونی", row["units_residential"]),
|
||||
("تجاری", row["units_commercial"]),
|
||||
("اداری", row["units_office"]))
|
||||
if (v := _clean(col)) and v != "0"
|
||||
)
|
||||
meta = "\n".join(filter(None, [
|
||||
f"مکان: {_clean(row['location'])}" if row["location"] else "",
|
||||
f"سال: {_clean(row['year'])}" if row["year"] else "",
|
||||
f"وضعیت: {'در حال ساخت' if row['status'] == 'progress' else 'تکمیلشده'}",
|
||||
f"نوع پروژه: {_clean(row['project_type'])}" if row["project_type"] else "",
|
||||
f"کاربری: {_clean(row['usage'])}" if row["usage"] else "",
|
||||
f"متراژ زیربنا: {_clean(row['area'])}" if row["area"] else "",
|
||||
f"عرصه: {_clean(row['land_area'])}" if row["land_area"] else "",
|
||||
f"طبقات: {_clean(row['floors'])}" if row["floors"] else "",
|
||||
f"طبقات پیلوت: {_clean(row['pilot_floors'])}" if row["pilot_floors"] else "",
|
||||
f"واحدها: {units}" if units else "",
|
||||
f"کارفرما: {_clean(row['client'])}" if row["client"] else "",
|
||||
]))
|
||||
text = "\n".join(filter(None, [
|
||||
f"پروژه «{_clean(row['title'])}»",
|
||||
meta,
|
||||
_clean(row["summary"]),
|
||||
body_to_text(row["body"]),
|
||||
]))
|
||||
d = _doc(text, "project", _clean(row["title"]), _PROJECT_URL.format(slug=row["slug"]))
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- مقالهها (فقط منتشرشده) + پرسشوپاسخهای پایان مقاله ---
|
||||
for row in _fetch_rows(
|
||||
dsn,
|
||||
"SELECT slug, title, date, category, excerpt, body, faqs FROM articles WHERE status = 'published' ORDER BY position",
|
||||
):
|
||||
text = "\n".join(filter(None, [
|
||||
f"دستهبندی: {_clean(row['category'])}" if row["category"] else "",
|
||||
_clean(row["excerpt"]),
|
||||
body_to_text(row["body"]),
|
||||
]))
|
||||
d = _doc(text, "article", _clean(row["title"]), _ARTICLE_URL.format(slug=row["slug"]))
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
article_url = _ARTICLE_URL.format(slug=row["slug"])
|
||||
for f in row["faqs"] or []:
|
||||
if not isinstance(f, dict):
|
||||
continue
|
||||
q, a = _clean(f.get("question")), _clean(f.get("answer"))
|
||||
d = _doc(f"پرسش: {q}\nپاسخ: {a}", "faq", q, article_url)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- مدلهای سرمایهگذاری ---
|
||||
for row in _fetch_rows(dsn, 'SELECT title, "desc", points FROM investment_models ORDER BY position'):
|
||||
points = "؛ ".join(_clean(p) for p in (row["points"] or []))
|
||||
d = _doc(
|
||||
"\n".join(filter(None, [
|
||||
f"«{_clean(row['title'])}»: {_clean(row['desc'])}",
|
||||
f"نکات: {points}" if points else "",
|
||||
])),
|
||||
"investment", _clean(row["title"]), "/investment",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- مراحل همکاری ---
|
||||
for row in _fetch_rows(dsn, 'SELECT step, title, "desc" FROM process_steps ORDER BY position'):
|
||||
d = _doc(
|
||||
f"مرحله {_clean(row['step'])} — {_clean(row['title'])}: {_clean(row['desc'])}",
|
||||
"process", _clean(row["title"]), "/investment",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- تیتر و توضیح بخشها (مدیریت محتوا) ---
|
||||
for row in _fetch_rows(dsn, "SELECT key, title, lead FROM section_headings ORDER BY key"):
|
||||
text = "\n".join(filter(None, [_clean(row["title"]), _clean(row["lead"])]))
|
||||
d = _doc(text, "section", _clean(row["title"]), _SECTION_URL.get(row["key"], "/"))
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- هیرو صفحههای داخلی (about/services/projects/… ) ---
|
||||
for row in _fetch_rows(dsn, "SELECT key, title, lead FROM page_heroes ORDER BY key"):
|
||||
text = "\n".join(filter(None, [_clean(row["title"]), _clean(row["lead"])]))
|
||||
d = _doc(text, "page_hero", _clean(row["title"]), f"/{row['key']}")
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- قبل/بعد (بخش صفحه اصلی) ---
|
||||
ba_rows = _fetch_rows(dsn, "SELECT title, lead FROM before_after LIMIT 1")
|
||||
if ba_rows:
|
||||
text = "\n".join(filter(None, [_clean(ba_rows[0]["title"]), _clean(ba_rows[0]["lead"])]))
|
||||
d = _doc(text, "before_after", _clean(ba_rows[0]["title"]) or "قبل و بعد", "/")
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
# --- چرا ما / تیم / نظرسنجی / تایملاین / داستان ما / فوتر ---
|
||||
for row in _fetch_rows(dsn, 'SELECT title, "desc" FROM why_us ORDER BY position'):
|
||||
d = _doc(f"{_clean(row['title'])}: {_clean(row['desc'])}", "about", _clean(row["title"]), "/about")
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
for row in _fetch_rows(dsn, "SELECT name, role, bio FROM team ORDER BY position"):
|
||||
d = _doc(
|
||||
f"{_clean(row['name'])} — {_clean(row['role'])}. {_clean(row['bio'])}",
|
||||
"team", _clean(row["name"]), "/about",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
testimonial_rows = _fetch_rows(dsn, "SELECT name, role, quote FROM testimonials ORDER BY position")
|
||||
for row in testimonial_rows:
|
||||
d = _doc(
|
||||
f"نظر {_clean(row['name'])} ({_clean(row['role'])}): {_clean(row['quote'])}",
|
||||
"testimonial", _clean(row["name"]), "/",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
# سند تجمیعی — پرسشهای طبیعی مثل «نظرات مشتریان چیست؟» به تکنفرها نمیرسند
|
||||
# (بیریشهسازی BM25: «نظرات» با «نظر» و «مشتریان» با «کارفرما» هیچ اشتراکی ندارند)
|
||||
if len(testimonial_rows) >= 2:
|
||||
agg = "؛ ".join(
|
||||
f"{_clean(t['name'])} ({_clean(t['role'])}): {_clean(t['quote'])}"
|
||||
for t in testimonial_rows
|
||||
)
|
||||
d = _doc(f"نظرات مشتریان و کارفرمایان پروژهها:\n{agg}", "testimonial", "نظرات مشتریان", "/")
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
for row in _fetch_rows(dsn, 'SELECT year, title, "desc" FROM timeline ORDER BY position'):
|
||||
d = _doc(
|
||||
f"سال {_clean(row['year'])} — {_clean(row['title'])}: {_clean(row['desc'])}",
|
||||
"timeline", _clean(row["title"]), "/about",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
story_rows = _fetch_rows(dsn, "SELECT title, paragraphs, quote FROM story LIMIT 1")
|
||||
if story_rows and story_rows[0]:
|
||||
s = story_rows[0]
|
||||
paragraphs = "\n".join(_clean(p) for p in (s["paragraphs"] or []) if _clean(p))
|
||||
text = "\n".join(filter(None, [_clean(s["title"]), paragraphs, _clean(s["quote"])]))
|
||||
d = _doc(text, "about", _clean(s["title"]) or "درباره ما", "/about")
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
footer_rows = _fetch_rows(dsn, "SELECT about_text FROM footer LIMIT 1")
|
||||
if footer_rows and _clean(footer_rows[0]["about_text"]):
|
||||
d = _doc(
|
||||
_clean(footer_rows[0]["about_text"]),
|
||||
"about", "درباره مجموعه (فوتر)", "/",
|
||||
)
|
||||
if d:
|
||||
docs.append(d)
|
||||
|
||||
log.info("Fetched %d documents from site database", len(docs))
|
||||
return docs
|
||||
|
||||
|
||||
def _url_key(url: str) -> str:
|
||||
"""URL → کلید یکتا برای doc_id («/projects/x» → «projects-x»)."""
|
||||
return url.strip("/").replace("/", "-") or "home"
|
||||
|
||||
|
||||
def chunk_documents(docs: list[dict], chunk_size: int = 700, overlap: int = 120) -> list[dict]:
|
||||
"""متنهای بلند (مقاله/پروژه) را به قطعات همپوشان تقسیم میکند.
|
||||
|
||||
هر قطعه یک doc_id پایدار میگیرد («type:url-key:ترتیب در همان url:شماره قطعه») تا
|
||||
همگامسازی افزایشی pgvector بتواند فقط سطرهای تغییر یافته را امبد کند.
|
||||
URL بخشی از doc_id است — بدون آن همه پروژهها/مقالهها که url یکتا دارند
|
||||
روی همان id میافتند و در جدول بردار یکدیگر را بازنویسی میکنند.
|
||||
"""
|
||||
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
||||
|
||||
from .vectorstore import chunk_content_hash
|
||||
|
||||
splitter = RecursiveCharacterTextSplitter(
|
||||
chunk_size=chunk_size,
|
||||
chunk_overlap=overlap,
|
||||
separators=["\n", "۔", ".", "،", " ", ""],
|
||||
)
|
||||
|
||||
# شماره ردیف هر سند در میان سندهای همtype و هم-url (برای FAQs که url یکسان دارند)
|
||||
occurrence: dict[str, int] = {}
|
||||
|
||||
out: list[dict] = []
|
||||
for doc in docs:
|
||||
key = f"{doc['type']}|{doc['url']}"
|
||||
occ = occurrence.get(key, 0)
|
||||
occurrence[key] = occ + 1
|
||||
|
||||
pieces = splitter.split_text(doc["text"]) if len(doc["text"]) > chunk_size * 1.3 else [doc["text"]]
|
||||
for i, piece in enumerate(pieces, 1):
|
||||
if len(pieces) == 1:
|
||||
# تیتر باید در متن امبدشده باشد تا BM25/معنایی پیدایش کند —
|
||||
# در سندهای تکقطعهای که تیترشان در متن نیست، به ابتدای قطعه میچسبد
|
||||
text = piece if not doc["title"] or doc["title"] in piece[:150] else f"{doc['title']}\n{piece}"
|
||||
else:
|
||||
text = f"[{doc['title']} — بخش {i} از {len(pieces)}]\n{piece}"
|
||||
chunk = {
|
||||
"doc_id": f"{doc['type']}:{_url_key(doc['url'])}:{occ}:{i}",
|
||||
"text": text,
|
||||
"type": doc["type"],
|
||||
"title": doc["title"],
|
||||
"url": doc["url"],
|
||||
}
|
||||
chunk["content_hash"] = chunk_content_hash(chunk)
|
||||
out.append(chunk)
|
||||
|
||||
log.info("Chunked %d documents into %d pieces", len(docs), len(out))
|
||||
return out
|
||||
|
||||
|
||||
def content_fingerprint(docs: list[dict]) -> str:
|
||||
"""هش کل محتوا — فقط برای لاگ؛ تشخیص تغییر ردیفی در vectorstore انجام میشود."""
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
payload = json.dumps(docs, ensure_ascii=False, sort_keys=True)
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
# --- زمینه همیشهتازه سایت (بلوک کوتاه تماس/خدمات برای پرامپت) ---
|
||||
_site_context_cache: tuple[float, str] | None = None
|
||||
|
||||
|
||||
def fetch_site_context(database_url: str, ttl: int = 120) -> str:
|
||||
"""نام برند، تماس، خدمات، آمار و دفاتر — با کش کوتاهمدت تا هر پیام یک کوئری سبک بزند."""
|
||||
global _site_context_cache
|
||||
import time as _time
|
||||
|
||||
now = _time.time()
|
||||
if _site_context_cache and now - _site_context_cache[0] < ttl:
|
||||
return _site_context_cache[1]
|
||||
try:
|
||||
dsn = _psycopg_dsn(database_url)
|
||||
brand = _fetch_rows(dsn, "SELECT name, phone, email, address FROM brand LIMIT 1")
|
||||
services = _fetch_rows(dsn, "SELECT title FROM services ORDER BY position")
|
||||
stats = _format_stat_rows(
|
||||
_fetch_rows(dsn, "SELECT value, suffix, label FROM stats ORDER BY position")
|
||||
)
|
||||
offices = _fetch_rows(dsn, "SELECT city, address FROM offices ORDER BY position")
|
||||
lines: list[str] = []
|
||||
if brand:
|
||||
b = brand[0]
|
||||
lines += [
|
||||
f"نام مجموعه: {_clean(b['name'])}",
|
||||
f"تلفن تماس: {_clean(b['phone'])}",
|
||||
f"ایمیل: {_clean(b['email'])}",
|
||||
f"آدرس: {_clean(b['address'])}",
|
||||
]
|
||||
if services:
|
||||
lines.append("خدمات سایت: " + "، ".join(_clean(s["title"]) for s in services))
|
||||
if stats:
|
||||
lines.append("آمار: " + "؛ ".join(stats))
|
||||
if offices:
|
||||
lines.append("دفاتر: " + "؛ ".join(
|
||||
f"{_clean(o['city'])} ({_clean(o['address'])})" for o in offices
|
||||
))
|
||||
ctx = "\n".join(lines)
|
||||
_site_context_cache = (now, ctx)
|
||||
return ctx
|
||||
except Exception as e:
|
||||
log.warning("Site context fetch failed: %s", e)
|
||||
return _site_context_cache[1] if _site_context_cache else ""
|
||||
@@ -0,0 +1,20 @@
|
||||
"""مدل امبدینگ — با لود تنبل تا اولین استفاده (برای تستهای سبک، torch لود نمیشود)."""
|
||||
|
||||
import os
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
from .config import settings
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def get_embeddings():
|
||||
from langchain_huggingface import HuggingFaceEmbeddings
|
||||
|
||||
os.makedirs(settings.hf_cache_dir, exist_ok=True)
|
||||
return HuggingFaceEmbeddings(
|
||||
model_name=settings.embedding_model,
|
||||
model_kwargs={"device": "cpu"},
|
||||
encode_kwargs={"normalize_embeddings": False},
|
||||
cache_folder=settings.hf_cache_dir,
|
||||
)
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""اجرای مجموعه طلایی روی سرویس چتبات و ساخت گزارش مارکداون.
|
||||
|
||||
استفاده (داخل کانتینر یا هر جا که به سرویس دسترسی هست):
|
||||
python eval_run.py --base http://localhost:8000
|
||||
python eval_run.py --out eval-report.md
|
||||
|
||||
هر پرسش از /chat/eval سرویس میشود؛ پاسخ با زیررشتههای انتظار
|
||||
(پس از نرمالسازی فارسی) مقایسه و رتبهبندی میشود:
|
||||
pass — همه/یکی از انتظارها برآورده شد
|
||||
miss — انتظار برآورده نشد (پاسخ احتمالاً نادرست یا بیربط)
|
||||
manual — انتظار عددی تعریف نشده؛ بازبینی دستی
|
||||
fallback-expected / unexpected-fallback — پیام جایگزین
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
FALLBACK_MESSAGE = (
|
||||
"متأسفانه اطلاعات دقیقی در این باره در سایت ثبت نشده است. "
|
||||
"برای راهنمایی بیشتر میتوانید از صفحه «تماس با ما» با ما در ارتباط باشید."
|
||||
)
|
||||
|
||||
|
||||
def ask(base: str, question: str, timeout: int = 180) -> dict:
|
||||
url = f"{base}/chat/eval?{urllib.parse.urlencode({'message': question})}"
|
||||
with urllib.request.urlopen(url, timeout=timeout) as r:
|
||||
return json.load(r)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="اجرای مجموعه طلایی ارزیابی چتبات")
|
||||
ap.add_argument("--base", default="http://localhost:8000", help="نشانی سرویس چتبات")
|
||||
ap.add_argument("--set", dest="eval_set",
|
||||
default=str(Path(__file__).with_name("eval_set.json")))
|
||||
ap.add_argument("--out", default="-", help="فایل خروجی گزارش (- = stdout)")
|
||||
ap.add_argument("--sleep", type=float, default=0.5, help="مکث بین پرسشها (ثانیه)")
|
||||
args = ap.parse_args()
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from chatbot.persian import normalize
|
||||
|
||||
data = json.loads(Path(args.eval_set).read_text(encoding="utf-8"))
|
||||
rows: list[dict] = []
|
||||
|
||||
for item in data["questions"]:
|
||||
q = item["q"]
|
||||
t0 = time.time()
|
||||
try:
|
||||
res = ask(args.base, q)
|
||||
except Exception as e:
|
||||
rows.append({**item, "answer": f"ERROR: {e}", "sources": [], "seconds": 0.0,
|
||||
"status": "error", "fallback": False})
|
||||
print(f" error: {q[:50]}", file=sys.stderr)
|
||||
continue
|
||||
seconds = time.time() - t0
|
||||
answer = str(res.get("answer", ""))
|
||||
contexts = res.get("contexts") or []
|
||||
is_fallback = answer.strip() == FALLBACK_MESSAGE or not contexts
|
||||
|
||||
if item.get("expect_fallback"):
|
||||
status = "fallback-expected" if is_fallback else "unexpected-answer"
|
||||
elif is_fallback:
|
||||
status = "unexpected-fallback"
|
||||
else:
|
||||
needles = [normalize(s) for s in item.get("expect_any", [])]
|
||||
if not needles:
|
||||
status = "manual"
|
||||
elif any(n in normalize(answer) for n in needles):
|
||||
status = "pass"
|
||||
else:
|
||||
status = "miss"
|
||||
|
||||
rows.append({**item, "answer": answer, "sources": contexts, "seconds": seconds,
|
||||
"status": status, "fallback": is_fallback})
|
||||
print(f" [{status}] {q[:50]}", file=sys.stderr)
|
||||
|
||||
time.sleep(args.sleep)
|
||||
|
||||
# --- گزارش ---
|
||||
lines = [f"# گزارش ارزیابی چتبات — {time.strftime('%Y-%m-%d %H:%M')}", ""]
|
||||
counts: dict[str, int] = {}
|
||||
for r in rows:
|
||||
counts[r["status"]] = counts.get(r["status"], 0) + 1
|
||||
graded = [r for r in rows if r["status"] in ("pass", "miss", "unexpected-fallback", "unexpected-answer")]
|
||||
ok = sum(1 for r in rows if r["status"] in ("pass", "fallback-expected"))
|
||||
lines += [
|
||||
f"- مجموع پرسشها: {len(rows)} — درست: {ok} — خطا: {counts.get('miss', 0) + counts.get('unexpected-fallback', 0) + counts.get('unexpected-answer', 0)}",
|
||||
f"- بازبینی دستی: {counts.get('manual', 0)} — خطای فنی: {counts.get('error', 0)}",
|
||||
f"- میانگین زمان پاسخ: {sum(r['seconds'] for r in rows) / max(len(rows), 1):.1f}s",
|
||||
"",
|
||||
]
|
||||
for r in rows:
|
||||
srcs = [c.rsplit("(منبع:", 1)[-1].strip(" ()\n") for c in r["sources"]] if r["sources"] else []
|
||||
lines += [
|
||||
f"## [{r['status']}] {r['q']}",
|
||||
f"*موضوع: {r.get('topic', '?')} — {r['seconds']:.1f}s — منابع: {'، '.join(srcs) or '—'}*",
|
||||
"",
|
||||
r["answer"],
|
||||
"",
|
||||
]
|
||||
|
||||
report = "\n".join(lines)
|
||||
if args.out == "-":
|
||||
print(report)
|
||||
else:
|
||||
Path(args.out).write_text(report, encoding="utf-8")
|
||||
print(f"Report written to {args.out}", file=sys.stderr)
|
||||
|
||||
return 1 if any(r["status"] in ("miss", "unexpected-answer") for r in rows) else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"description": "مجموعه طلایی ارزیابی چتبات — پرسشها از واقعیتهای زنده دیتابیس سایت ساخته شدهاند. expect_any: حداقل یکی از این زیررشتهها (پس از نرمالسازی) در پاسخ باشد؛ expect_fallback: انتظار پیام جایگزین (شکاف دانش). رشتههای خالی = بررسی دستی.",
|
||||
"questions": [
|
||||
{"q": "پروژه میرزا طاهر ۵ کجا ساخته شده و چند متر زیربنا دارد؟", "topic": "projects", "expect_any": ["8100"]},
|
||||
{"q": "پروژه آرامش - بابک کی و کجا تحویل شده؟", "topic": "projects", "expect_any": ["1405", "6200"]},
|
||||
{"q": "وضعیت پروژه میرزاطاهر ۶ چطور است؟", "topic": "projects", "expect_any": ["در حال ساخت"]},
|
||||
{"q": "کدام پروژه شما در محله گورتان اصفهان است؟", "topic": "projects", "expect_any": ["وحدت"]},
|
||||
{"q": "پروژه میرزا طاهر ۵ چند واحد مسکونی دارد؟", "topic": "projects", "expect_any": ["29"]},
|
||||
{"q": "گروه ساختمانی آرامش چند سال سابقه دارد؟", "topic": "stats", "expect_any": ["23", "1381"]},
|
||||
{"q": "تا امروز چند پروژه تحویل دادهاید؟", "topic": "stats", "expect_any": ["64"]},
|
||||
{"q": "مجموع متراژ ساختوساز شما چقدر است؟", "topic": "stats", "expect_any": ["111"]},
|
||||
{"q": "چند خانواده در پروژههای شما ساکن هستند؟", "topic": "stats", "expect_any": ["500"]},
|
||||
{"q": "شماره تماس شما چیست؟", "topic": "contact", "expect_any": ["09133107809"]},
|
||||
{"q": "دفتر تهران کجاست؟", "topic": "offices", "expect_any": ["ولیعصر"]},
|
||||
{"q": "آدرس ایمیل مجموعه چیست؟", "topic": "contact", "expect_any": ["arameshsakhtemani"]},
|
||||
{"q": "دفاتر شما در چه شهرهایی است؟", "topic": "offices", "expect_any": ["نوشهر"]},
|
||||
{"q": "گروه آرامش چه سالی تأسیس شده؟", "topic": "faqs", "expect_any": ["1381"]},
|
||||
{"q": "زمین دارم، ساخت را از کجا شروع کنم؟", "topic": "faqs", "expect_any": []},
|
||||
{"q": "شرایط مشارکت در ساخت چگونه است؟", "topic": "investment", "expect_any": []},
|
||||
{"q": "مدل صندوق سرمایهگذاری چطور کار میکند؟", "topic": "investment", "expect_any": ["24"]},
|
||||
{"q": "پیشخرید واحد یعنی چه؟", "topic": "investment", "expect_any": ["پرداخت", "شخصیسازی", "تحویل"]},
|
||||
{"q": "خدمات گروه آرامش چیست؟", "topic": "services", "expect_any": []},
|
||||
{"q": "نظرات مشتریان قبلی درباره شما چیست؟", "topic": "testimonials", "expect_any": []},
|
||||
{"q": "هزینه ساخت هر متر مربع چقدر است؟", "topic": "canary", "expect_fallback": true}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
"""ایندکس ترکیبی روی pgvector + BM25 در حافظه.
|
||||
|
||||
بردارها در pgvector (دیتابیس اختصاصی چتبات) بهصورت افزایشی همگام میشوند —
|
||||
فقط سطرهای جدید یا تغییر یافته امبد میشوند. BM25 چون سبک است در هر شروع
|
||||
از روی همان سطرها ساخته میشود و نیازی به کش دیسکی ندارد.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
from rank_bm25 import BM25Okapi
|
||||
|
||||
from . import content as content_mod
|
||||
from .config import settings
|
||||
from .persian import tokenize
|
||||
from . import vectorstore
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SiteIndex:
|
||||
"""حالت در حافظهٔ بازیابی — سندها (برای BM25) و وضعیت آماده بودن."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.docs: list[dict] = []
|
||||
self.bm25: BM25Okapi | None = None
|
||||
|
||||
@property
|
||||
def ready(self) -> bool:
|
||||
return self.bm25 is not None and bool(self.docs)
|
||||
|
||||
|
||||
INDEX = SiteIndex()
|
||||
|
||||
|
||||
def sync_index(force_rebuild: bool = False) -> dict:
|
||||
"""همگامسازی کامل: محتوا → قطعه → pgvector (افزایشی) → ساخت BM25.
|
||||
|
||||
خروجی: آمار همگامسازی. خطای اتصال به دیتابیس بالا فرستاده میشود.
|
||||
"""
|
||||
start = time.time()
|
||||
|
||||
vectorstore.ensure_schema()
|
||||
|
||||
docs = content_mod.fetch_site_documents(settings.database_url)
|
||||
chunks = content_mod.chunk_documents(docs)
|
||||
stats = vectorstore.sync_chunks(chunks, force=force_rebuild)
|
||||
|
||||
INDEX.docs = vectorstore.fetch_all_chunks()
|
||||
corpus_tokens = [tokenize(d["text"]) for d in INDEX.docs]
|
||||
INDEX.bm25 = BM25Okapi(corpus_tokens) if corpus_tokens else None
|
||||
|
||||
log.info("Index ready in %.1fs (%d vectors, %d docs, %s)",
|
||||
time.time() - start, len(INDEX.docs), len(chunks), stats)
|
||||
return stats
|
||||
@@ -0,0 +1,79 @@
|
||||
"""نرمالسازی متن فارسی و توکنسازی برای جستوجوی کلیدواژه (BM25).
|
||||
|
||||
بدون وابستگی سنگین — فقط استانداردسازی نویسهها، حذف اعراب و نیمفاصلههای
|
||||
مشکلی و شکستن کلمههای مرکب روی نیمفاصله برای بهبود بازیابی.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
# نویسههای عربی که در متن فارسی اشتباهاً استفاده میشوند
|
||||
_CHAR_MAP = {
|
||||
"\u064a": "\u06cc", # ي → ی
|
||||
"\u0643": "\u06a9", # ك → ک
|
||||
"\u0623": "\u0627", # أ → ا
|
||||
"\u0625": "\u0627", # إ → ا
|
||||
"\u0671": "\u0627", # ٱ → ا
|
||||
"\u0629": "\u0647", # ة → ه
|
||||
"\u0624": "\u0648", # ؤ → و
|
||||
"\u0626": "\u06cc", # ئ → ی
|
||||
"\u0640": "", # ـ (کشیده) حذف
|
||||
}
|
||||
|
||||
# اعراب و علامتهای اضافی
|
||||
_DIACRITICS = re.compile(r"[\u064b-\u0652\u0670\u0653-\u0655\u0640]")
|
||||
|
||||
# ارقام فارسی و عربی → ASCII
|
||||
_DIGITS = str.maketrans({
|
||||
"\u06f0": "0", "\u06f1": "1", "\u06f2": "2", "\u06f3": "3", "\u06f4": "4",
|
||||
"\u06f5": "5", "\u06f6": "6", "\u06f7": "7", "\u06f8": "8", "\u06f9": "9",
|
||||
"\u0660": "0", "\u0661": "1", "\u0662": "2", "\u0663": "3", "\u0664": "4",
|
||||
"\u0665": "5", "\u0666": "6", "\u0667": "7", "\u0668": "8", "\u0669": "9",
|
||||
})
|
||||
|
||||
# واژههای دستوری پرتکرار — در جستوجو بیمعنا هستند
|
||||
STOPWORDS = frozenset("""
|
||||
و در به از که با این آن است هست بود بودن شد شدن شود کرد کردن کرده کند کنی
|
||||
برای را های ها هایی هم نیز اما یا اگر تا بر روی زیر بین پس قبل بعد همه هر چه
|
||||
چیزی کس کسی کجا چرا چگونه چطور چند یکی دو سه ما شما آنها ایشان من تو او
|
||||
کدام کی چی چهقدر چقدر
|
||||
می نخواهد خواهد باشد باشند هستیم هستند بودم بودیم دارد دارند داشته داد دهد
|
||||
بله خیر آیا فقط نیز خیلی بسیار کمی دیگر دیگری همان همین وقتی زمانی وقتیکه
|
||||
اساساً لطفاً میشه میکنه هستن هستم
|
||||
""".split())
|
||||
|
||||
# علائم نگارشی فارسی/لاتین — قبل از توکنسازی حذف میشوند (نیمفاصله جزو اینها نیست)
|
||||
_PUNCT_RE = re.compile(r"[،؛؟!,;:\?\"'()\[\]{}«»….*#@&%+=/\\|~^$\u066d\u066c\u066b]+")
|
||||
|
||||
# توکن: حروف/ارقام فارسی و لاتین + نیمفاصله در میان کلمه
|
||||
_TOKEN_RE = re.compile(r"[\w\u0600-\u06ff\u200c]+")
|
||||
|
||||
|
||||
def normalize(text: str) -> str:
|
||||
"""نویسههای غیراستاندارد عربی/فارسی را به شکل یکدست فارسی میبرد."""
|
||||
if not text:
|
||||
return ""
|
||||
out = []
|
||||
for ch in text:
|
||||
out.append(_CHAR_MAP.get(ch, ch))
|
||||
text = "".join(out)
|
||||
text = _DIACRITICS.sub("", text)
|
||||
text = text.translate(_DIGITS)
|
||||
# فاصلههای تکراری را یکی کن — نیمفاصله عمداً حفظ میشود (میشود)
|
||||
text = re.sub(r"[ \t\r\n]+", " ", text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def tokenize(text: str) -> list[str]:
|
||||
"""توکنهای نرمالشده برای BM25 — کلمههای مرکب روی نیمفاصله هم جدا ایندکس میشوند."""
|
||||
text = _PUNCT_RE.sub(" ", normalize(text).lower())
|
||||
tokens = []
|
||||
for raw in _TOKEN_RE.findall(text):
|
||||
if raw in STOPWORDS or len(raw) < 2:
|
||||
continue
|
||||
tokens.append(raw)
|
||||
# «میشود» → می + شود (فراخوانی بیشتر برای بازیابی)
|
||||
if "\u200c" in raw:
|
||||
for part in raw.split("\u200c"):
|
||||
if len(part) >= 2 and part not in STOPWORDS:
|
||||
tokens.append(part)
|
||||
return tokens
|
||||
@@ -0,0 +1,191 @@
|
||||
"""گراف گفتگو (LangGraph) — پورت خط لوله v13 در سه گام:
|
||||
|
||||
۱) بازنویسی پرسش با تاریخچه (فقط وقتی تاریخچه هست — صرفهجویی در تأخیر)
|
||||
۲) بازیابی ترکیبی با چند نوعواژه (اختیاری)
|
||||
۳) تولید پاسخ فارسی با قواعد تکیه بر داده
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
import json as _json
|
||||
from typing import Annotated, List, Optional
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langgraph.checkpoint.memory import MemorySaver
|
||||
from langgraph.graph import END, StateGraph
|
||||
from langgraph.graph.message import add_messages
|
||||
|
||||
from . import content as content_mod
|
||||
from .config import settings
|
||||
from .retrieval import retrieve_final
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
FALLBACK_MESSAGE = (
|
||||
"متأسفانه اطلاعات دقیقی در این باره در سایت ثبت نشده است. "
|
||||
"برای راهنمایی بیشتر میتوانید از صفحه «تماس با ما» با ما در ارتباط باشید."
|
||||
)
|
||||
LLM_UNAVAILABLE = (
|
||||
"سرویس هوش مصنوعی هنوز پیکربندی نشده است. "
|
||||
"متغیرهای LLM_BASE_URL و LLM_MODEL را در تنظیمات سرویس چتبات تنظیم کنید."
|
||||
)
|
||||
|
||||
_llm = None
|
||||
|
||||
|
||||
def get_llm() -> ChatOpenAI | None:
|
||||
"""LLM تولید — اگر پیکربندی نشده باشد None برمیگرداند."""
|
||||
global _llm
|
||||
if _llm is None and settings.llm_base_url:
|
||||
_llm = ChatOpenAI(
|
||||
model=settings.llm_model,
|
||||
base_url=settings.llm_base_url,
|
||||
api_key=settings.llm_api_key or "not-needed",
|
||||
temperature=0,
|
||||
streaming=True,
|
||||
)
|
||||
return _llm
|
||||
|
||||
|
||||
class GraphState(TypedDict):
|
||||
messages: Annotated[List, add_messages]
|
||||
documents: List[str]
|
||||
contextualized_query: Optional[str]
|
||||
|
||||
|
||||
# --- گام ۱: بازنویسی پرسش با تاریخچه ---
|
||||
|
||||
def contextualize_query(question: str, history: list) -> str:
|
||||
"""ضمیرها و اشارههای پرسش را با تاریخچه گفتگو مشخص میکند («اون دومی» → موضوع واقعی)."""
|
||||
model = get_llm()
|
||||
if model is None or not history:
|
||||
return question
|
||||
try:
|
||||
history_text = "\n".join(
|
||||
f"{'کاربر' if isinstance(m, HumanMessage) else 'دستیار'}: {str(m.content)[:300]}"
|
||||
for m in history[-6:]
|
||||
)
|
||||
prompt = (
|
||||
"با توجه به تاریخچه گفتگو، پرسش کاربر را به یک پرسش مستقل و کامل فارسی بازنویسی کن.\n"
|
||||
"- ضمیرها و اشارهها (او، آن، همین، دومی، این یکی) را به موضوع واقعیِ ذکرشده در تاریخچه تبدیل کن.\n"
|
||||
"- اگر پرسش از قبل مستقل است، عیناً همان را برگردان.\n"
|
||||
"- فقط متن پرسش بازنویسیشده را برگردان؛ هیچ توضیحی ننویس.\n\n"
|
||||
f"تاریخچه گفتگو:\n{history_text}\n\n"
|
||||
f"پرسش کاربر: {question}\n\n"
|
||||
"پرسش مستقل:"
|
||||
)
|
||||
resp = model.invoke([HumanMessage(content=prompt)], config={"tags": ["utility"]})
|
||||
rewritten = (resp.content or "").strip() if isinstance(resp.content, str) else ""
|
||||
if not rewritten or len(rewritten) > len(question) * 4:
|
||||
return question
|
||||
if rewritten != question:
|
||||
log.info("Contextualized: '%s' → '%s'", question[:60], rewritten[:60])
|
||||
return rewritten
|
||||
except Exception as e:
|
||||
log.warning("Contextualization failed: %s", e)
|
||||
return question
|
||||
|
||||
|
||||
def expand_query(query: str) -> list[str]:
|
||||
"""گسترش پرسش به چند نوعواژه (اختیاری — پیشفرض خاموش برای پیکره کوچک)."""
|
||||
model = get_llm()
|
||||
if model is None:
|
||||
return [query]
|
||||
try:
|
||||
prompt = (
|
||||
"برای جستوجو در محتوای سایت یک گروه ساختمانی، ۳ نوعواژه جایگزین برای این پرسش بساز: "
|
||||
"بازنویسی معنایی، استخراج کلیدواژه، گسترش با مفاهیم مرتبط.\n"
|
||||
'فقط JSON برگردان: {"variants": ["۱", "۲", "۳"]}\n\n'
|
||||
f"پرسش: {query}"
|
||||
)
|
||||
resp = model.invoke([HumanMessage(content=prompt)], config={"tags": ["utility"]})
|
||||
text = resp.content if isinstance(resp.content, str) else ""
|
||||
match = re.search(r'\{.*"variants".*\}', text, re.DOTALL)
|
||||
if match:
|
||||
variants = [v for v in _json.loads(match.group()).get("variants", []) if v and v != query][:3]
|
||||
if variants:
|
||||
log.info("Query variants: %s", [query] + variants)
|
||||
return [query] + variants
|
||||
except Exception as e:
|
||||
log.warning("Query expansion failed: %s", e)
|
||||
return [query]
|
||||
|
||||
|
||||
# --- گام ۲: بازیابی ---
|
||||
|
||||
def retrieve_node(state: GraphState) -> dict:
|
||||
messages = state.get("messages", [])
|
||||
if not messages:
|
||||
return {"documents": []}
|
||||
question = messages[-1].content
|
||||
history = messages[:-1]
|
||||
|
||||
query = contextualize_query(question, history) if settings.contextualize_enabled else question
|
||||
variants = expand_query(query) if settings.query_expansion else [query]
|
||||
|
||||
docs = retrieve_final(query, variants)
|
||||
doc_texts = [f"{d['text']}\n(منبع: {d['title']} — {d['url']})" for d in docs]
|
||||
log.info("Retrieved %d documents for '%s'", len(doc_texts), question[:60])
|
||||
return {
|
||||
"documents": doc_texts,
|
||||
"contextualized_query": query if query != question else None,
|
||||
}
|
||||
|
||||
|
||||
# --- گام ۳: تولید پاسخ ---
|
||||
|
||||
def build_system_prompt(documents: list[str], contextualized_query: str | None) -> str:
|
||||
site_ctx = content_mod.fetch_site_context(settings.database_url, settings.site_context_ttl)
|
||||
docs_block = "\n\n———\n\n".join(documents) if documents else "(سند مرتبطی یافت نشد)"
|
||||
reminder = (
|
||||
f"\n--- یادآوری ---\nپرسش کاربر پس از بازنویسی این است: «{contextualized_query}»\n\n"
|
||||
if contextualized_query else ""
|
||||
)
|
||||
return (
|
||||
"تو دستیار گفتگوی هوشمند سایت «گروه ساختمانی آرامش» هستی و فقط به فارسی پاسخ میدهی.\n"
|
||||
"دانش تو اکیداً محدود به اطلاعات زیر است.\n\n"
|
||||
f"--- اطلاعات پایه سایت (همیشه معتبر) ---\n{site_ctx}\n\n"
|
||||
f"--- اسناد بازیابیشده مرتبط با پرسش ---\n{docs_block}\n"
|
||||
f"{reminder}"
|
||||
"--- قوانین پاسخ ---\n"
|
||||
"۱. فقط بر اساس اطلاعات بالا پاسخ بده؛ بههیچوجه از دانش بیرونی استفاده نکن و چیزی نساز.\n"
|
||||
"۲. پاسخ کوتاه، دقیق و مفید باشد (معمولاً ۲ تا ۵ جمله) و لحن حرفهای و محترمانه داشته باشد.\n"
|
||||
f"۳. اگر اطلاعات کافی در اسناد نیست، فقط همین جمله را بنویس: «{FALLBACK_MESSAGE}»\n"
|
||||
"۴. اگر سند مسیر صفحه مرتبط دارد، در پایان پاسخ آن را معرفی کن (مثلاً: جزئیات کامل در صفحه /blog/... ).\n"
|
||||
"۵. درباره قیمت، زمان دقیق یا هر تعهدی فقط چیزی را بگو که در دادهها آمده است."
|
||||
)
|
||||
|
||||
|
||||
def generate_node(state: GraphState) -> dict:
|
||||
messages = state.get("messages", [])
|
||||
question = messages[-1].content if messages else ""
|
||||
|
||||
model = get_llm()
|
||||
if model is None:
|
||||
return {"messages": [AIMessage(content=LLM_UNAVAILABLE)]}
|
||||
|
||||
documents = state.get("documents") or []
|
||||
system = build_system_prompt(documents, state.get("contextualized_query"))
|
||||
log.info("Generating answer with %d docs (system prompt %d chars)", len(documents), len(system))
|
||||
|
||||
history = messages[:-1]
|
||||
reply = model.invoke(
|
||||
[SystemMessage(content=system), *history, HumanMessage(content=question)],
|
||||
config={"tags": ["generate"]},
|
||||
)
|
||||
return {"messages": [reply]}
|
||||
|
||||
|
||||
# --- گراف ---
|
||||
|
||||
memory = MemorySaver()
|
||||
workflow = StateGraph(GraphState)
|
||||
workflow.add_node("retrieve", retrieve_node)
|
||||
workflow.add_node("generate", generate_node)
|
||||
workflow.set_entry_point("retrieve")
|
||||
workflow.add_edge("retrieve", "generate")
|
||||
workflow.add_edge("generate", END)
|
||||
graph = workflow.compile(checkpointer=memory)
|
||||
@@ -0,0 +1,20 @@
|
||||
# سرویس چتبات — بازیابی ترکیبی روی محتوای سایت
|
||||
fastapi>=0.115
|
||||
uvicorn[standard]>=0.30
|
||||
pydantic-settings>=2.3
|
||||
|
||||
# گراف گفتگو و LLM
|
||||
langgraph>=0.2.60
|
||||
langchain>=0.3
|
||||
langchain-openai>=0.2
|
||||
langchain-text-splitters>=0.3
|
||||
|
||||
# بازیابی — بردارها در pgvector میروند؛ BM25 و خوشهبندی در حافظه
|
||||
sentence-transformers>=3.0
|
||||
langchain-huggingface>=0.1
|
||||
rank-bm25>=0.2.2
|
||||
scikit-learn>=1.4
|
||||
numpy>=1.26
|
||||
|
||||
# دیتابیس (فقط خواندن)
|
||||
psycopg[binary]>=3.1
|
||||
@@ -0,0 +1,50 @@
|
||||
"""مدل ریرنکر BGE — با لود تنبل و امتیازدهی دستهای."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
from .config import settings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _CrossEncoder:
|
||||
"""غلاف سبک روی AutoModelForSequenceClassification — API شبیه rank_bm25."""
|
||||
def __init__(self) -> None:
|
||||
import torch
|
||||
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
||||
|
||||
os.makedirs(settings.hf_cache_dir, exist_ok=True)
|
||||
self._torch = torch
|
||||
self.tokenizer = AutoTokenizer.from_pretrained(settings.reranker_model, cache_dir=settings.hf_cache_dir)
|
||||
self.model = AutoModelForSequenceClassification.from_pretrained(
|
||||
settings.reranker_model, cache_dir=settings.hf_cache_dir
|
||||
)
|
||||
device = settings.reranker_device if settings.reranker_device == "cuda" and torch.cuda.is_available() else "cpu"
|
||||
self.model.to(device)
|
||||
self.model.eval()
|
||||
self.device = device
|
||||
log.info("Reranker loaded on %s", device)
|
||||
|
||||
def score(self, pairs: list[list[str]], batch_size: int = 16) -> list[float]:
|
||||
torch = self._torch
|
||||
out: list[float] = []
|
||||
with torch.no_grad():
|
||||
for i in range(0, len(pairs), batch_size):
|
||||
inputs = self.tokenizer(
|
||||
pairs[i:i + batch_size],
|
||||
padding=True,
|
||||
truncation=True,
|
||||
max_length=512,
|
||||
return_tensors="pt",
|
||||
).to(self.device)
|
||||
logits = self.model(**inputs).logits.squeeze(-1)
|
||||
out.extend(logits.cpu().tolist())
|
||||
return out
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def get_reranker() -> _CrossEncoder:
|
||||
return _CrossEncoder()
|
||||
@@ -0,0 +1,165 @@
|
||||
"""بازیابی ترکیبی — پورت خط لوله v13 با سه تغییر برای این سایت:
|
||||
|
||||
۱) پایگاه sparse بهجای SPLADE (انگلیسیمحور و بیفایده روی فارسی) از BM25
|
||||
با نرمالسازی فارسی استفاده میکند.
|
||||
۲) جستوجوی معنایی بهجای FAISS با pgvector و فاصله کسینوسی در SQL انجام
|
||||
میشود (همگامسازی افزایشی، فیلترپذیر، بدون فایل ایندکس جدا).
|
||||
۳) مسیریابی alpha با LLM حذف شده و وزن ثابت تنظیمپذیر است — برای پیکرهٔ
|
||||
کوچک سایت، هزینهٔ یک فراخوانی LLM اضافی بهازای هر پیام نمیارزد.
|
||||
بقیهٔ منطق (نرمالسازی نمره، فیوژن وزندار، برش خوشهبندی، ریرنک) عین v13 است.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
from . import vectorstore
|
||||
from .config import settings
|
||||
from .indexing import INDEX
|
||||
from .persian import tokenize
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def dense_retrieve(query: str, top_k: int) -> list[tuple[dict, float]]:
|
||||
"""جستوجوی معنایی pgvector — خروجی: (سند، شباهت کسینوسی)."""
|
||||
return vectorstore.dense_search(query, top_k)
|
||||
|
||||
|
||||
def keyword_retrieve(query: str, top_k: int) -> list[tuple[dict, float]]:
|
||||
"""جستوجوی کلیدواژه BM25 روی متن نرمالشده فارسی."""
|
||||
if INDEX.bm25 is None:
|
||||
return []
|
||||
try:
|
||||
tokens = tokenize(query)
|
||||
if not tokens:
|
||||
return []
|
||||
scores = INDEX.bm25.get_scores(tokens)
|
||||
ranked = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:top_k]
|
||||
return [(INDEX.docs[i], float(scores[i])) for i in ranked if scores[i] > 0]
|
||||
except Exception as e:
|
||||
log.error("BM25 retrieval failed: %s", e)
|
||||
return []
|
||||
|
||||
|
||||
def _minmax(scores: list[float]) -> list[float]:
|
||||
if not scores:
|
||||
return []
|
||||
lo, hi = min(scores), max(scores)
|
||||
if hi == lo:
|
||||
return [0.5] * len(scores)
|
||||
return [(s - lo) / (hi - lo) for s in scores]
|
||||
|
||||
|
||||
def hybrid_retrieve(query: str, alpha: float | None = None, top_k: int | None = None) -> list[tuple[dict, float]]:
|
||||
"""ترکیب وزندار نمره معنایی و کلیدواژه؛ خروجی مرتبشده بر اساس نمره ترکیبی."""
|
||||
alpha = settings.alpha_dense if alpha is None else alpha
|
||||
top_k = top_k or settings.retrieve_k
|
||||
|
||||
dense = dense_retrieve(query, top_k)
|
||||
keyword = keyword_retrieve(query, top_k)
|
||||
log.info("Retrieval '%s': dense=%d, keyword=%d", query[:60], len(dense), len(keyword))
|
||||
if not dense and not keyword:
|
||||
return []
|
||||
|
||||
dense_norm = _minmax([s for _, s in dense])
|
||||
keyword_norm = _minmax([s for _, s in keyword])
|
||||
|
||||
pool: dict = {} # doc_id → {doc, dense_max, kw_max}
|
||||
for (doc, _), norm in zip(dense, dense_norm):
|
||||
entry = pool.setdefault(doc["doc_id"], {"doc": doc, "dense_max": 0.0, "kw_max": 0.0})
|
||||
entry["dense_max"] = max(entry["dense_max"], norm)
|
||||
for (doc, _), norm in zip(keyword, keyword_norm):
|
||||
entry = pool.setdefault(doc["doc_id"], {"doc": doc, "dense_max": 0.0, "kw_max": 0.0})
|
||||
entry["kw_max"] = max(entry["kw_max"], norm)
|
||||
|
||||
combined = [
|
||||
(entry["doc"], alpha * entry["dense_max"] + (1 - alpha) * entry["kw_max"])
|
||||
for entry in pool.values()
|
||||
]
|
||||
combined.sort(key=lambda x: x[1], reverse=True)
|
||||
return combined
|
||||
|
||||
|
||||
def cluster_cutoff(scored: list[tuple[dict, float]], silhouette_threshold: float = 0.55) -> list[tuple[dict, float]]:
|
||||
"""برش خوشهای v13 — مرز طبیعی کیفیت بهجای top-k دلخواه.
|
||||
|
||||
روی نمرههای ۱بعدی K-Means با K=2 میزند؛ اگر جدایی خوشهها معنادار
|
||||
باشد (silhouette ≥ 0.55) فقط خوشهٔ بالا را نگه میدارد.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
n = len(scored)
|
||||
if n < 4:
|
||||
return scored
|
||||
try:
|
||||
from sklearn.cluster import KMeans
|
||||
from sklearn.metrics import silhouette_score
|
||||
|
||||
scores = np.array([s for _, s in scored], dtype=float).reshape(-1, 1)
|
||||
kmeans = KMeans(n_clusters=2, random_state=42, n_init=10)
|
||||
labels = kmeans.fit_predict(scores)
|
||||
sil = silhouette_score(scores, labels)
|
||||
if sil < silhouette_threshold:
|
||||
log.info("Clustering: silhouette=%.3f < %.2f — keeping all %d docs", sil, silhouette_threshold, n)
|
||||
return scored
|
||||
centers = kmeans.cluster_centers_.flatten()
|
||||
good_label = int(np.argmax(centers))
|
||||
cutoff = int(np.sum(labels == good_label))
|
||||
cutoff = max(cutoff, 1)
|
||||
log.info("Clustering: silhouette=%.3f — cutting at %d/%d docs", sil, cutoff, n)
|
||||
return scored[:cutoff]
|
||||
except Exception as e:
|
||||
log.warning("Clustering failed (%s) — keeping all docs", e)
|
||||
return scored
|
||||
|
||||
|
||||
def rerank(query: str, scored: list[tuple[dict, float]], top_k: int) -> list[tuple[dict, float]]:
|
||||
"""ریرنک کراسانکودر BGE — مرتبسازی نهایی بر اساس شباهت واقعی پرسش/سند."""
|
||||
if not scored:
|
||||
return []
|
||||
if not settings.reranker_enabled:
|
||||
return scored[:top_k]
|
||||
|
||||
try:
|
||||
from .reranker import get_reranker
|
||||
|
||||
start = time.time()
|
||||
pairs = [[query, doc["text"]] for doc, _ in scored]
|
||||
scores = get_reranker().score(pairs)
|
||||
rescored = sorted(
|
||||
((doc, float(s)) for (doc, _), s in zip(scored, scores)),
|
||||
key=lambda x: x[1],
|
||||
reverse=True,
|
||||
)
|
||||
log.info("Reranked %d docs in %.2fs — top scores: %s",
|
||||
len(scored), time.time() - start,
|
||||
[f"{s:.2f}" for _, s in rescored[:3]])
|
||||
return rescored[:top_k]
|
||||
except Exception as e:
|
||||
log.error("Reranking failed (%s) — falling back to fusion order", e)
|
||||
return scored[:top_k]
|
||||
|
||||
|
||||
def retrieve_final(query: str, query_variants: list[str] | None = None) -> list[dict]:
|
||||
"""خط کامل بازیابی برای یک پرسش: هر نوع → فیوژن → برش خوشه → ریرنک → K نهایی."""
|
||||
variants = query_variants or [query]
|
||||
|
||||
pool: dict = {}
|
||||
for variant in variants:
|
||||
for doc, score in hybrid_retrieve(variant):
|
||||
entry = pool.setdefault(doc["doc_id"], {"doc": doc, "score": 0.0})
|
||||
entry["score"] = max(entry["score"], score)
|
||||
|
||||
combined = sorted(((e["doc"], e["score"]) for e in pool.values()),
|
||||
key=lambda x: x[1], reverse=True)
|
||||
if not combined:
|
||||
return []
|
||||
|
||||
filtered = cluster_cutoff(combined)
|
||||
# ریرنک روی نتیجههای برشخورده (سقف retrieve_k تا تأخیر کنترل شود)
|
||||
rerank_candidates = filtered[: settings.retrieve_k]
|
||||
final = rerank(query, rerank_candidates, settings.best_of_k)
|
||||
|
||||
log.info("Final retrieval: %d docs (from %d candidates, %d variants)",
|
||||
len(final), len(combined), len(variants))
|
||||
return [doc for doc, _ in final]
|
||||
@@ -0,0 +1,82 @@
|
||||
"""تستهای خالص (بدون مدل/دیتابیس) برای ماژولهای چتبات — اجرا: python test_pure.py"""
|
||||
import sys
|
||||
import os
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
||||
|
||||
from chatbot.content import chunk_documents, tiptap_blocks, body_to_text
|
||||
from chatbot.vectorstore import chunk_content_hash, chatbot_dsn
|
||||
from chatbot.persian import normalize, tokenize
|
||||
|
||||
docs = [
|
||||
{"text": "پاراگراف کوتاه خدمت الف", "type": "service", "title": "الف", "url": "/services"},
|
||||
{"text": "سؤال اول؟", "type": "faq", "title": "س۱", "url": "/faq"},
|
||||
{"text": "سؤال دوم؟", "type": "faq", "title": "س۲", "url": "/faq"},
|
||||
{"text": "آ" * 2000, "type": "article", "title": "مقاله بلند", "url": "/blog/long"},
|
||||
]
|
||||
chunks = chunk_documents(docs)
|
||||
ids = [c["doc_id"] for c in chunks]
|
||||
assert len(ids) == len(set(ids)), f"duplicate ids: {ids}"
|
||||
|
||||
faq_ids = sorted(c["doc_id"] for c in chunks if c["type"] == "faq")
|
||||
assert faq_ids == ["faq:faq:0:1", "faq:faq:1:1"], faq_ids
|
||||
|
||||
# سندهایی که url یکتا دارند (پروژه/مقاله) نباید روی هم بیفتند — url بخشی از doc_id است
|
||||
two_projects = [
|
||||
{"text": "پروژه الف " + "ت" * 60, "type": "project", "title": "الف", "url": "/projects/alpha"},
|
||||
{"text": "پروژه ب " + "ت" * 60, "type": "project", "title": "ب", "url": "/projects/beta"},
|
||||
]
|
||||
pids = sorted(c["doc_id"] for c in chunk_documents(two_projects))
|
||||
assert pids == ["project:projects-alpha:0:1", "project:projects-beta:0:1"], pids
|
||||
|
||||
# تیتر سندهای تکقطعهای باید در متن امبدشده باشد تا جستوجو پیدایش کند
|
||||
faq_chunks = [c for c in chunks if c["type"] == "faq"]
|
||||
assert all(c["text"].startswith(c["title"]) for c in faq_chunks), [c["text"] for c in faq_chunks]
|
||||
|
||||
art = [c for c in chunks if c["type"] == "article"]
|
||||
assert len(art) >= 2 and art[1]["doc_id"] == "article:blog-long:0:2", [x["doc_id"] for x in art]
|
||||
assert "بخش 2 از" in art[1]["text"] and "بخش 1 از" in art[0]["text"]
|
||||
|
||||
c = chunks[0]
|
||||
assert c["content_hash"] == chunk_content_hash(c)
|
||||
c2 = dict(c, title="عنوان عوض شد")
|
||||
# hash فیلد کپیشده است — باید با محاسبه دوباره مقایسه شود، نه با فیلد قدیمی
|
||||
assert chunk_content_hash(c2) != c["content_hash"]
|
||||
|
||||
chunks2 = chunk_documents(docs)
|
||||
assert [x["doc_id"] for x in chunks2] == ids
|
||||
assert [x["content_hash"] for x in chunks2] == [x["content_hash"] for x in chunks]
|
||||
|
||||
settings_dsn = chatbot_dsn()
|
||||
assert settings_dsn.endswith("/aramesh_chatbot"), settings_dsn
|
||||
assert "+psycopg" not in settings_dsn
|
||||
|
||||
# نرمالسازی و توکنسازی فارسی
|
||||
assert normalize("كامل يك ۱۲۳") == "کامل یک 123"
|
||||
t = tokenize("کدام شرکت ساختمانی خوب در تهران؟")
|
||||
assert "شرکت" in t and "تهران" in t and "کدام" not in t, t
|
||||
assert "می\u200cسازیم" in tokenize("می\u200cسازیم") and "سازیم" in tokenize("می\u200cسازیم")
|
||||
|
||||
# استخراج متن TipTap و فرمت قدیمی
|
||||
tiptap_doc = {
|
||||
"type": "doc",
|
||||
"content": [
|
||||
{"type": "heading", "attrs": {"level": 2}, "content": [{"type": "text", "text": "معرفی پروژه"}]},
|
||||
{"type": "paragraph", "content": [
|
||||
{"type": "text", "text": "این برج در تهران "},
|
||||
{"type": "text", "marks": [{"type": "bold"}], "text": "ساخته شد"},
|
||||
{"type": "hardBreak"},
|
||||
{"type": "image", "attrs": {"alt": "نمای بیرونی"}},
|
||||
]},
|
||||
{"type": "bulletList", "content": [
|
||||
{"type": "listItem", "content": [{"type": "paragraph", "content": [{"type": "text", "text": "۲۴ طبقه"}]}]},
|
||||
]},
|
||||
{"type": "paragraph", "content": [{"type": "image", "attrs": {"alt": ""}}]},
|
||||
],
|
||||
}
|
||||
blocks = tiptap_blocks(tiptap_doc)
|
||||
assert blocks == ["معرفی پروژه", "این برج در تهران ساخته شد [تصویر: نمای بیرونی]", "۲۴ طبقه"], blocks
|
||||
assert body_to_text(["الف", "ب"]) == "الف\nب"
|
||||
assert body_to_text(None) == ""
|
||||
|
||||
print(f"ALL PURE TESTS OK — {len(chunks)} chunks from {len(docs)} docs")
|
||||
@@ -0,0 +1,288 @@
|
||||
"""ذخیرهساز برداری pgvector — جایگزین FAISS در مهاجرت به pgvector.
|
||||
|
||||
بردارها در یک دیتابیس جدا (aramesh_chatbot) روی همان نمونه Postgres سایت
|
||||
نگهداری میشوند تا دیتابیس سایت فقطخواندنی بماند. همگامسازی افزایشی است:
|
||||
فقط سطرهای جدید/تغییریافته امبد میشوند (کلید: doc_id پایدار + hash محتوا).
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
from .config import settings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _strip_driver(dsn: str) -> str:
|
||||
return dsn.replace("+psycopg", "").replace("+asyncpg", "")
|
||||
|
||||
|
||||
def chatbot_dsn() -> str:
|
||||
"""DSN دیتابیس اختصاصی چتبات — از DATABASE_URL با تعویض نام دیتابیس ساخته میشود."""
|
||||
parts = urlsplit(_strip_driver(settings.database_url))
|
||||
return urlunsplit(parts._replace(path=f"/{settings.chatbot_db_name}"))
|
||||
|
||||
|
||||
def _admin_dsn() -> str:
|
||||
"""DSN دیتابیس postgres برای ساخت دیتابیس چتبات (فقط یکبار)."""
|
||||
parts = urlsplit(_strip_driver(settings.database_url))
|
||||
return urlunsplit(parts._replace(path="/postgres"))
|
||||
|
||||
|
||||
def ensure_schema() -> None:
|
||||
"""ساخت دیتابیس و جدول بردارها — idempotent و در هر شروع اجرا میشود."""
|
||||
import psycopg
|
||||
from psycopg import errors as pg_errors
|
||||
|
||||
try:
|
||||
with psycopg.connect(_admin_dsn(), autocommit=True, connect_timeout=10) as conn:
|
||||
try:
|
||||
conn.execute(f'CREATE DATABASE "{settings.chatbot_db_name}"')
|
||||
log.info("Created chatbot database '%s'", settings.chatbot_db_name)
|
||||
except pg_errors.DuplicateDatabase:
|
||||
pass
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Cannot reach Postgres to ensure chatbot database: {e}") from e
|
||||
|
||||
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=10) as conn:
|
||||
conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
|
||||
conn.execute(
|
||||
f"""
|
||||
CREATE TABLE IF NOT EXISTS chatbot_chunks (
|
||||
doc_id TEXT PRIMARY KEY,
|
||||
content_hash TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
content JSONB NOT NULL,
|
||||
embedding vector({settings.embedding_dim}) NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS chatbot_chunks_embedding_hnsw
|
||||
ON chatbot_chunks USING hnsw (embedding vector_cosine_ops)
|
||||
"""
|
||||
)
|
||||
# گزارش گفتگوها — حلقه بازخورد برای کشف پرسشهای بیپاسخ
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS chat_logs (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
ts TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
thread_id TEXT NOT NULL,
|
||||
question TEXT NOT NULL,
|
||||
answer TEXT NOT NULL,
|
||||
n_docs INTEGER NOT NULL DEFAULT 0,
|
||||
is_fallback BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
latency_ms INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS chat_logs_ts_idx ON chat_logs (ts DESC)")
|
||||
|
||||
|
||||
def sync_chunks(chunks: list[dict], force: bool = False) -> dict:
|
||||
"""همگامسازی افزایشی قطعات با جدول pgvector.
|
||||
|
||||
- سطرهایی که دیگر وجود ندارند حذف میشوند
|
||||
- سطرهای جدید یا تغییر یافته (hash یا مدل امبدینگ عوض شده) امبد و upsert میشوند
|
||||
- force=True همه سطرها را از نو امبد میکند
|
||||
خروجی: آمار عملیات برای لاگ.
|
||||
"""
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .embeddings import get_embeddings
|
||||
|
||||
model = settings.embedding_model
|
||||
wanted = {c["doc_id"]: c for c in chunks}
|
||||
|
||||
# row_factory لازم است: پایینتر row["model"]/row["doc_id"] خوانده میشود و
|
||||
# پیشفرض psycopg3 تاپل برمیگرداند (خطای tuple indices must be integers).
|
||||
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=10,
|
||||
row_factory=dict_row) as conn:
|
||||
existing: dict[str, str] = {}
|
||||
if not force:
|
||||
for row in conn.execute("SELECT doc_id, content_hash, model FROM chatbot_chunks").fetchall():
|
||||
if row["model"] == model:
|
||||
existing[row["doc_id"]] = row["content_hash"]
|
||||
else:
|
||||
conn.execute("DELETE FROM chatbot_chunks")
|
||||
|
||||
to_delete = [doc_id for doc_id in existing if doc_id not in wanted]
|
||||
if to_delete:
|
||||
conn.execute(
|
||||
"DELETE FROM chatbot_chunks WHERE doc_id = ANY(%s)",
|
||||
[to_delete],
|
||||
)
|
||||
|
||||
to_upsert = [
|
||||
c for c in chunks
|
||||
if existing.get(c["doc_id"]) != c["content_hash"]
|
||||
]
|
||||
inserted = updated = 0
|
||||
|
||||
if to_upsert:
|
||||
vectors = get_embeddings().embed_documents([c["text"] for c in to_upsert])
|
||||
for chunk, vec in zip(to_upsert, vectors):
|
||||
literal = "[" + ",".join(f"{x:.7f}" for x in vec) + "]"
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO chatbot_chunks (doc_id, content_hash, model, content, embedding)
|
||||
VALUES (%s, %s, %s, %s, %s::vector)
|
||||
ON CONFLICT (doc_id) DO UPDATE SET
|
||||
content_hash = EXCLUDED.content_hash,
|
||||
model = EXCLUDED.model,
|
||||
content = EXCLUDED.content,
|
||||
embedding = EXCLUDED.embedding
|
||||
""",
|
||||
(chunk["doc_id"], chunk["content_hash"], model, Jsonb(chunk), literal),
|
||||
)
|
||||
if chunk["doc_id"] in existing:
|
||||
updated += 1
|
||||
else:
|
||||
inserted += 1
|
||||
|
||||
stats = {"inserted": inserted, "updated": updated, "deleted": len(to_delete),
|
||||
"unchanged": len(wanted) - len(to_upsert)}
|
||||
log.info("Vector sync: %s", stats)
|
||||
return stats
|
||||
|
||||
|
||||
def fetch_all_chunks() -> list[dict]:
|
||||
"""همه قطعات ذخیرهشده (برای ساخت BM25 در حافظه)."""
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=10,
|
||||
row_factory=dict_row) as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT doc_id, content_hash, content FROM chatbot_chunks ORDER BY doc_id"
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"doc_id": r["doc_id"],
|
||||
"content_hash": r["content_hash"],
|
||||
**(r["content"] if isinstance(r["content"], dict) else json.loads(r["content"])),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def vector_count() -> int:
|
||||
"""تعداد بردارهای ذخیرهشده — برای healthz (خطا → ۰)."""
|
||||
try:
|
||||
import psycopg
|
||||
|
||||
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=5) as conn:
|
||||
return int(conn.execute("SELECT count(*) FROM chatbot_chunks").fetchone()[0])
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
def log_chat(thread_id: str, question: str, answer: str, n_docs: int,
|
||||
is_fallback: bool, latency_ms: int) -> None:
|
||||
"""ثبت یک گفتگو در chat_logs — هرگز خطا نمیدهد (لاگ نباید جریان پاسخ را بشکند)."""
|
||||
try:
|
||||
import psycopg
|
||||
|
||||
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=5) as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO chat_logs (thread_id, question, answer, n_docs, is_fallback, latency_ms)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
""",
|
||||
(thread_id, question, answer[:4000], n_docs, is_fallback, latency_ms),
|
||||
)
|
||||
except Exception as e:
|
||||
log.warning("chat_logs insert failed: %s", e)
|
||||
|
||||
|
||||
def chat_stats(days: int = 7) -> dict:
|
||||
"""آمار تجمعی گفتگوها — بدون متن پرسشها (متنها فقط با توکن در /chat/stats)."""
|
||||
try:
|
||||
import psycopg
|
||||
|
||||
with psycopg.connect(chatbot_dsn(), autocommit=True, connect_timeout=5) as conn:
|
||||
total = int(conn.execute("SELECT count(*) FROM chat_logs").fetchone()[0])
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT count(*), count(*) FILTER (WHERE is_fallback)
|
||||
FROM chat_logs WHERE ts > now() - (%s || ' days')::interval
|
||||
""",
|
||||
(str(days),),
|
||||
).fetchone()
|
||||
recent_fallbacks: list[str] = []
|
||||
if row and row[1]:
|
||||
recent_fallbacks = [
|
||||
r[0] for r in conn.execute(
|
||||
"""
|
||||
SELECT question FROM chat_logs
|
||||
WHERE is_fallback AND ts > now() - (%s || ' days')::interval
|
||||
ORDER BY ts DESC LIMIT 20
|
||||
""",
|
||||
(str(days),),
|
||||
).fetchall()
|
||||
]
|
||||
return {
|
||||
"total_logged": total,
|
||||
"last_7d": int(row[0]) if row else 0,
|
||||
"fallback_7d": int(row[1]) if row else 0,
|
||||
"recent_fallback_questions": recent_fallbacks,
|
||||
}
|
||||
except Exception as e:
|
||||
log.warning("chat_stats failed: %s", e)
|
||||
return {"total_logged": 0, "last_7d": 0, "fallback_7d": 0, "recent_fallback_questions": []}
|
||||
|
||||
|
||||
def dense_search(query: str, top_k: int) -> list[tuple[dict, float]]:
|
||||
"""جستوجوی معنایی SQL با فاصله کسینوسی — خروجی: (سند، شباهت).
|
||||
|
||||
خطا (مثلاً دیتابیس هنوز آماده نیست) → فهرست خالی تا بازیابی فقط با BM25 ادامه یابد.
|
||||
"""
|
||||
try:
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row as _dict_row
|
||||
|
||||
from .embeddings import get_embeddings
|
||||
|
||||
vec = get_embeddings().embed_query(query)
|
||||
literal = "[" + ",".join(f"{x:.7f}" for x in vec) + "]"
|
||||
with psycopg.connect(chatbot_dsn(), row_factory=_dict_row, connect_timeout=10) as conn:
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT doc_id, content, 1 - (embedding <=> %s::vector) AS sim
|
||||
FROM chatbot_chunks
|
||||
ORDER BY embedding <=> %s::vector
|
||||
LIMIT %s
|
||||
""",
|
||||
(literal, literal, top_k),
|
||||
).fetchall()
|
||||
return [(_row_to_doc(r), float(r["sim"])) for r in rows]
|
||||
except Exception as e:
|
||||
log.warning("Dense search failed (%s) — falling back to keyword only", e)
|
||||
return []
|
||||
|
||||
|
||||
def _row_to_doc(row: Any) -> dict:
|
||||
content = row["content"] if isinstance(row["content"], dict) else json.loads(row["content"])
|
||||
return {
|
||||
"doc_id": row["doc_id"],
|
||||
"text": content.get("text", ""),
|
||||
"type": content.get("type", ""),
|
||||
"title": content.get("title", ""),
|
||||
"url": content.get("url", ""),
|
||||
}
|
||||
|
||||
|
||||
def chunk_content_hash(chunk: dict) -> str:
|
||||
"""هش محتوای قطعه — تغییر متن یا متادیتا یعنی سطر باید بهروز شود."""
|
||||
payload = json.dumps(
|
||||
{k: chunk[k] for k in ("text", "type", "title", "url")},
|
||||
ensure_ascii=False, sort_keys=True,
|
||||
)
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
|
||||
@@ -0,0 +1,189 @@
|
||||
# لایه مانیتورینگ — Prometheus، Grafana، Loki، Alertmanager و صادرکنندهها
|
||||
#
|
||||
# توسعه: docker compose -f docker-compose.yml -f docker-compose.monitoring.yml up -d
|
||||
# تولید: سه فایل با هم: base + monitoring + prod (بخش مانیتورینگ README)
|
||||
#
|
||||
# داشبورد: grafana.localhost (توسعه) — رمز از GRAFANA_ADMIN_PASSWORD در .env
|
||||
# هشدارها: Prometheus → Alertmanager → تلگرام (ALERT_TELEGRAM_* در .env)
|
||||
# منابع: مجموعاً حدود ۱ تا ۱.۵ گیگابایت RAM — با حذف هر سرویس، بقیه سرپا میمانند.
|
||||
|
||||
x-default-logging: &default-logging
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
services:
|
||||
prometheus:
|
||||
image: prom/prometheus:v2.53.0
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --storage.tsdb.retention.time=15d
|
||||
- --storage.tsdb.retention.size=2GB
|
||||
volumes:
|
||||
- ./monitoring/prometheus:/etc/prometheus:ro
|
||||
- prometheus_data:/prometheus
|
||||
networks: [monitoring, edge]
|
||||
environment:
|
||||
# پروب عمومی — در تولید SITE_URL در .env تنظیم میشود (مثل https://aramesh.example)
|
||||
SITE_URL: ${SITE_URL:-http://frontend/}
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "--spider", "http://localhost:9090/-/healthy"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 15s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 768M
|
||||
|
||||
alertmanager:
|
||||
image: prom/alertmanager:v0.27.0
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
command:
|
||||
- --config.file=/etc/alertmanager/alertmanager.rendered.yml
|
||||
- --storage.path=/alertmanager
|
||||
# فایل رندرشدهٔ alertmanager.rendered.yml را scripts/stack.sh از قالب
|
||||
# alertmanager.yml با مقادیر .env (ALERT_BOT_TOKEN/ALERT_CHAT_ID) میسازد —
|
||||
# Alertmanager خودش متغیر محیطی را در کانفیگ جایگزین نمیکند
|
||||
volumes:
|
||||
- ./monitoring/alertmanager:/etc/alertmanager:ro
|
||||
- alertmanager_data:/alertmanager
|
||||
networks: [monitoring]
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 128M
|
||||
|
||||
# منابع هر کانتینر — روی Linux سرور کامل کار میکند؛ روی Docker Desktop ویندوز
|
||||
# ممکن است محدود باشد (حذفش بقیه استک را نمیشکند)
|
||||
cadvisor:
|
||||
image: gcr.io/cadvisor/cadvisor:v0.49.1
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
privileged: true
|
||||
volumes:
|
||||
- /:/rootfs:ro
|
||||
- /var/run:/var/run:ro
|
||||
- /sys:/sys:ro
|
||||
- /var/lib/docker/:/var/lib/docker:ro
|
||||
networks: [monitoring]
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 192M
|
||||
|
||||
# منابع میزبان + سنجهٔ تازگی پشتیبان (backups/*.prom نوشتهٔ scripts/backup.sh)
|
||||
node-exporter:
|
||||
image: quay.io/prometheus/node-exporter:v1.8.2
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
command:
|
||||
- --path.rootfs=/host
|
||||
- --collector.textfile.directory=/textfile
|
||||
volumes:
|
||||
- /:/host:ro
|
||||
- ./backups:/textfile:ro
|
||||
networks: [monitoring]
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 64M
|
||||
|
||||
postgres-exporter:
|
||||
image: quay.io/prometheuscommunity/postgres-exporter:v0.16.0
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
environment:
|
||||
DATA_SOURCE_NAME: postgresql://aramesh:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD را در .env تنظیم کنید}@db:5432/arameshplaza?sslmode=disable
|
||||
networks: [internal, monitoring]
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 64M
|
||||
|
||||
blackbox-exporter:
|
||||
image: prom/blackbox-exporter:v0.25.0
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
# edge برای رسیدن به سرویسهایی که پروب میشوند (frontend/minio/umami/chatbot/backend)
|
||||
networks: [monitoring, edge]
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 64M
|
||||
|
||||
# لاگ همهٔ کانتینرها — جستوجو در Grafana؛ خطاهای بکاند از همینجا دیده میشوند
|
||||
loki:
|
||||
image: grafana/loki:3.1.1
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
command: -config.file=/etc/loki/loki-config.yml
|
||||
volumes:
|
||||
- ./monitoring/loki:/etc/loki:ro
|
||||
- loki_data:/loki
|
||||
networks: [monitoring]
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 512M
|
||||
|
||||
promtail:
|
||||
image: grafana/promtail:3.1.1
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
command: -config.file=/etc/promtail/promtail-config.yml
|
||||
volumes:
|
||||
- ./monitoring/promtail:/etc/promtail:ro
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
- promtail_positions:/positions
|
||||
networks: [monitoring]
|
||||
depends_on: [loki]
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 128M
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:11.1.0
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER:-admin}
|
||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?GRAFANA_ADMIN_PASSWORD را در .env تنظیم کنید}
|
||||
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||
volumes:
|
||||
- grafana_data:/var/lib/grafana
|
||||
- ./monitoring/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./monitoring/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
networks: [monitoring, edge]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -sf http://localhost:3000/api/health || wget -q --spider http://localhost:3000/api/health"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.grafana.rule=Host(`grafana.localhost`)
|
||||
- traefik.http.routers.grafana.entrypoints=web
|
||||
- traefik.http.services.grafana.loadbalancer.server.port=3000
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 384M
|
||||
|
||||
networks:
|
||||
monitoring:
|
||||
|
||||
volumes:
|
||||
prometheus_data:
|
||||
alertmanager_data:
|
||||
loki_data:
|
||||
grafana_data:
|
||||
promtail_positions:
|
||||
@@ -0,0 +1,141 @@
|
||||
# لایه تولید — TLS با Let's Encrypt و انتشار روی پورتهای استاندارد ۸۰/۴۳.
|
||||
# پیشنیاز: متغیرهای DOMAIN و ACME_EMAIL در .env؛ بهعلاوه رکورد DNS دامنه به این سرور.
|
||||
#
|
||||
# bash scripts/stack.sh deploy-prod
|
||||
# (معادل: docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d --build)
|
||||
#
|
||||
# همه درخواستهای HTTP به HTTPS هدایت میشوند و مسیریابیها فقط روی دامنه DOMAIN پاسخ میدهند.
|
||||
# برای داشبوردها: analytics.DOMAIN (آنالیتیکس) و grafana.DOMAIN (مانیتورینگ، با فایل monitoring).
|
||||
#
|
||||
# ---- پیشنمایش خصوصی و انتشار (scripts/preview-mode.sh) ----
|
||||
# در حالت پیشنمایش (PREVIEW_MODE=on) کل سایت پشت Basic Auth است و noindex میگیرد:
|
||||
# تیم با یک نام کاربری/رمز مشترک وارد میشود، محتوا را ویرایش میکند و هیچکس دیگری —
|
||||
# از جمله گوگل — به سایت دسترسی ندارد. برای انتشار عمومی:
|
||||
# bash scripts/preview-mode.sh off → deploy مجدد → ثبت sitemap در Search Console.
|
||||
#
|
||||
# DOMAIN دامنه اصلی است و DOMAIN_ALIAS دامنه دوم (هر دو مسیر و گواهی میگیرند).
|
||||
# در زمان انتشار، برای جلوگیری از محتوای تکراری، دامنه دوم را به اصلی ریدایرکت کنید:
|
||||
# ALIAS_REDIRECT=on (در .env) — ریدایرکت ۳۰۱ دائمی به دامنه اصلی.
|
||||
|
||||
services:
|
||||
traefik:
|
||||
command: !override
|
||||
- --providers.docker=true
|
||||
- --providers.docker.exposedbydefault=false
|
||||
- --providers.docker.constraints=Label(`com.docker.compose.project`, `aramesh-backend`)
|
||||
- --entrypoints.web.address=:80
|
||||
- --entrypoints.web.http.redirections.entrypoint.to=websecure
|
||||
- --entrypoints.web.http.redirections.entrypoint.scheme=https
|
||||
- --entrypoints.websecure.address=:443
|
||||
- --certificatesresolvers.le.acme.email=${ACME_EMAIL:?ACME_EMAIL را در .env تنظیم کنید}
|
||||
- --certificatesresolvers.le.acme.storage=/letsencrypt/acme.json
|
||||
- --certificatesresolvers.le.acme.httpchallenge=true
|
||||
- --certificatesresolvers.le.acme.httpchallenge.entrypoint=web
|
||||
- --ping=true
|
||||
- --accesslog=true
|
||||
- --metrics.prometheus=true
|
||||
ports: !override
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes: !override
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
- letsencrypt_data:/letsencrypt
|
||||
|
||||
# MinIO کنسول (رمز root) و API مستقیمش فقط از localhost سرور در دسترس باشند —
|
||||
# از راه دور با تونل SSH: ssh -L 9001:127.0.0.1:9001 server
|
||||
minio:
|
||||
ports: !override
|
||||
- "127.0.0.1:9001:9001"
|
||||
- "127.0.0.1:19000:9000"
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.media.rule=Host(`${DOMAIN}`) && PathPrefix(`/media`)
|
||||
- traefik.http.routers.media.entrypoints=websecure
|
||||
- traefik.http.routers.media.tls.certresolver=le
|
||||
- traefik.http.routers.media.priority=100
|
||||
- traefik.http.routers.media.middlewares=${PREVIEW_MIDDLEWARES:+$PREVIEW_MIDDLEWARES,}media-rewrite,sec-headers
|
||||
- traefik.http.middlewares.media-rewrite.replacepathregex.regex=^/media/(.*)
|
||||
- traefik.http.middlewares.media-rewrite.replacepathregex.replacement=/aramesh-media/$$1
|
||||
- traefik.http.services.media.loadbalancer.server.port=9000
|
||||
|
||||
backend:
|
||||
environment:
|
||||
# سایت هممبدأ است — CORS لازم نیست
|
||||
CORS_ORIGINS: '[]'
|
||||
SITE_URL: https://${DOMAIN:?DOMAIN را در .env تنظیم کنید}
|
||||
# پیشنمایش خصوصی — هدر noindex + robots مسدودکننده (لایه دوم؛ لایه اول گیت Traefik)
|
||||
PREVIEW_MODE: ${PREVIEW_MODE:-off}
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.api.rule=Host(`${DOMAIN}`) && PathPrefix(`/api`)
|
||||
- traefik.http.routers.api.entrypoints=websecure
|
||||
- traefik.http.routers.api.tls.certresolver=le
|
||||
- traefik.http.routers.api.middlewares=${PREVIEW_MIDDLEWARES:+$PREVIEW_MIDDLEWARES,}api-flood,sec-headers
|
||||
# سئو: همهٔ صفحات عمومی از بکاند سرو میشوند تا متا در HTML اولیه تزریق شود —
|
||||
# مسیرهای استاتیک دقیقاند (Path) تا assets/ فونتها از Caddy سرو شوند
|
||||
- traefik.http.routers.seo.rule=Host(`${DOMAIN}`) && (Path(`/`) || Path(`/about`) || Path(`/services`) || Path(`/investment`) || Path(`/faq`) || Path(`/contact`) || PathPrefix(`/blog/`) || Path(`/blog`) || PathPrefix(`/projects/`) || Path(`/projects`) || Path(`/en`) || PathPrefix(`/en/`) || PathPrefix(`/robots.txt`) || PathPrefix(`/sitemap.xml`) || PathPrefix(`/llms.txt`))
|
||||
- traefik.http.routers.seo.entrypoints=websecure
|
||||
- traefik.http.routers.seo.tls.certresolver=le
|
||||
- traefik.http.routers.seo.middlewares=${PREVIEW_MIDDLEWARES:+$PREVIEW_MIDDLEWARES,}sec-headers
|
||||
|
||||
frontend:
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.web.rule=Host(`${DOMAIN}`) && PathPrefix(`/`)
|
||||
- traefik.http.routers.web.entrypoints=websecure
|
||||
- traefik.http.routers.web.tls.certresolver=le
|
||||
- traefik.http.routers.web.middlewares=${PREVIEW_MIDDLEWARES:+$PREVIEW_MIDDLEWARES,}sec-headers
|
||||
# تعریف یکبارهٔ میانافزار هدرهای امنیتی — روی همهٔ روترهای websecure استفاده میشود
|
||||
- traefik.http.middlewares.sec-headers.headers.stsSeconds=31536000
|
||||
- traefik.http.middlewares.sec-headers.headers.stsIncludeSubdomains=true
|
||||
- traefik.http.middlewares.sec-headers.headers.stsPreload=true
|
||||
- traefik.http.middlewares.sec-headers.headers.contentTypeNosniff=true
|
||||
# ---- گیت پیشنمایش خصوصی ----
|
||||
# ورود با نام کاربری/رمز مشترک (htpasswd) — تا وقتی PREVIEW_MIDDLEWARES تنظیم است فعال میشود
|
||||
- traefik.http.middlewares.preview-auth.basicauth.users=${PREVIEW_AUTH_USERS:-disabled:nope}
|
||||
- traefik.http.middlewares.preview-auth.basicauth.realm=Aramesh private preview
|
||||
# لایه دوم جلوگیری از ایندکس — حتی اگر گیت حذف شد، گوگل چیزی ذخیره نکند
|
||||
- traefik.http.middlewares.preview-noindex.headers.customresponseheaders.X-Robots-Tag=noindex, nofollow, noarchive
|
||||
# ---- ریدایرکت دامنه دوم به اصلی (زمان انتشار: ALIAS_REDIRECT=on) ----
|
||||
- traefik.http.middlewares.to-primary.redirectregex.regex=^https?://[^/]+(.*)
|
||||
- traefik.http.middlewares.to-primary.redirectregex.replacement=https://${DOMAIN}$$1
|
||||
- traefik.http.middlewares.to-primary.redirectregex.permanent=true
|
||||
- traefik.http.routers.alias-redirect.rule=Host(`${DOMAIN_ALIAS:-invalid.invalid}`)
|
||||
- traefik.http.routers.alias-redirect.entrypoints=websecure
|
||||
- traefik.http.routers.alias-redirect.tls.certresolver=le
|
||||
- traefik.http.routers.alias-redirect.priority=1000
|
||||
- traefik.http.routers.alias-redirect.middlewares=${ALIAS_REDIRECT_MIDDLEWARES:-sec-headers}
|
||||
- traefik.http.routers.alias-redirect.service=web
|
||||
|
||||
chatbot:
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.chat.rule=Host(`${DOMAIN}`) && PathPrefix(`/chat`)
|
||||
- traefik.http.routers.chat.entrypoints=websecure
|
||||
- traefik.http.routers.chat.tls.certresolver=le
|
||||
- traefik.http.routers.chat.priority=100
|
||||
- traefik.http.routers.chat.middlewares=${PREVIEW_MIDDLEWARES:+$PREVIEW_MIDDLEWARES,}api-flood,sec-headers
|
||||
|
||||
umami:
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.analytics.rule=Host(`analytics.${DOMAIN}`)
|
||||
- traefik.http.routers.analytics.entrypoints=websecure
|
||||
- traefik.http.routers.analytics.tls.certresolver=le
|
||||
- traefik.http.routers.analytics.middlewares=sec-headers
|
||||
- traefik.http.services.analytics.loadbalancer.server.port=3000
|
||||
|
||||
# داشبورد Grafana (docker-compose.monitoring.yml) در تولید با TLS نیاز به روتر
|
||||
# Host(`grafana.DOMAIN`) دارد — چون آن سرویس فقط با فایل monitoring بالا میآید،
|
||||
# برچسبهایش را در override سرور بگذارید (README، بخش مانیتورینگ):
|
||||
# docker-compose.override.yml روی سرور:
|
||||
# services:
|
||||
# grafana:
|
||||
# labels:
|
||||
# - traefik.http.routers.grafana.rule=Host(`grafana.YOURDOMAIN`)
|
||||
# - traefik.http.routers.grafana.entrypoints=websecure
|
||||
# - traefik.http.routers.grafana.tls.certresolver=le
|
||||
# - traefik.http.services.grafana.loadbalancer.server.port=3000
|
||||
|
||||
volumes:
|
||||
letsencrypt_data:
|
||||
@@ -1,44 +1,375 @@
|
||||
# مقادیر محرمانه از فایل .env ریشه خوانده میشوند — از .env.example کپی کنید:
|
||||
# cp .env.example .env (یا: bash scripts/gen-env.sh)
|
||||
# برای انتشار با TLS، روی این فایل docker-compose.prod.yml هم سوار شود (README):
|
||||
# bash scripts/stack.sh deploy-prod
|
||||
#
|
||||
# لایههای اختیاری:
|
||||
# docker-compose.monitoring.yml — Prometheus/Grafana/Loki (پروفایل زیرساخت)
|
||||
# پروفایل ops — پشتیبان ساعتی دیتابیس
|
||||
# پروفایل tools — ابزار mc برای پشتیبانگیری دستی
|
||||
|
||||
x-default-logging: &default-logging
|
||||
# بدون این، لاگ json-file بیمرز رشد میکند و دیسک سرور را پر میکند
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:17-alpine
|
||||
# نقطه ورود واحد — مسیریابی / (سایت استاتیک)، /api (بکاند)، /media (MinIO)،
|
||||
# /chat (چتبات)، / (آنالیتیکس روی analytics.localhost — پایین همین فایل)
|
||||
traefik:
|
||||
# v3.3+ قدیمیترین کلاینت داکر را دارد که با Engineهای جدید (API 1.5x) مشکل دارد —
|
||||
# با v3.6 پین شده است
|
||||
image: traefik:v3.6
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
command:
|
||||
- --providers.docker=true
|
||||
- --providers.docker.exposedbydefault=false
|
||||
# فقط کانتینرهای همین استک — با استکهای دیگر هممیزبان تداخل نام روتر پیش نمیآید
|
||||
- --providers.docker.constraints=Label(`com.docker.compose.project`, `aramesh-backend`)
|
||||
- --entrypoints.web.address=:80
|
||||
# healthcheck داخلی + متریکها برای Prometheus + لاگ دسترسی
|
||||
- --ping=true
|
||||
- --accesslog=true
|
||||
- --metrics.prometheus=true
|
||||
ports:
|
||||
- "${TRAEFIK_HTTP_PORT:-5173}:80"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
networks: [edge]
|
||||
healthcheck:
|
||||
test: ["CMD", "traefik", "healthcheck", "--ping"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 256M
|
||||
|
||||
db:
|
||||
# pgvector/pgvector:pg17 = همان PostgreSQL 17 + افزونهٔ vector برای چتبات
|
||||
image: pgvector/pgvector:pg17
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
environment:
|
||||
POSTGRES_USER: aramesh
|
||||
POSTGRES_PASSWORD: aramesh
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD را در .env تنظیم کنید}
|
||||
POSTGRES_DB: arameshplaza
|
||||
volumes:
|
||||
- db_data:/var/lib/postgresql/data
|
||||
shm_size: 256m
|
||||
networks: [internal]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U aramesh -d arameshplaza"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 10s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 512M
|
||||
|
||||
minio:
|
||||
image: minio/minio:RELEASE.2025-04-22T22-12-26Z
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
command: server /data --console-address ":9001"
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-aramesh}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?MINIO_ROOT_PASSWORD را در .env تنظیم کنید}
|
||||
volumes:
|
||||
- minio_data:/data
|
||||
networks: [edge, internal]
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 10s
|
||||
ports:
|
||||
# در تولید، docker-compose.prod.yml اینها را فقط روی 127.0.0.1 میبندد —
|
||||
# کنسول رمز root دارد و نباید به اینترنت باز باشد
|
||||
- "9001:9001"
|
||||
- "19000:9000"
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
# Traefik باید IP لبه را بگیرد — سرویس روی دو شبکه است
|
||||
- traefik.docker.network=aramesh-backend_edge
|
||||
- traefik.http.routers.media.rule=PathPrefix(`/media`)
|
||||
- traefik.http.routers.media.entrypoints=web
|
||||
- traefik.http.routers.media.priority=100
|
||||
- traefik.http.middlewares.media-rewrite.replacepathregex.regex=^/media/(.*)
|
||||
- traefik.http.middlewares.media-rewrite.replacepathregex.replacement=/aramesh-media/$$1
|
||||
- traefik.http.routers.media.middlewares=media-rewrite
|
||||
- traefik.http.services.media.loadbalancer.server.port=9000
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 512M
|
||||
|
||||
# یکبار اجرا میشود: ساخت باکت، بازگذاشتن خواندن عمومی و پیشبارگذاری تصویرهای seed
|
||||
# فقط وقتی باکت خالی است — تا هر deploy، کپی تکراری تصویرها را تکرار نکند.
|
||||
minio-setup:
|
||||
image: minio/mc:RELEASE.2025-04-08T15-39-49Z
|
||||
depends_on:
|
||||
minio:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-aramesh}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?MINIO_ROOT_PASSWORD را در .env تنظیم کنید}
|
||||
MINIO_BUCKET: aramesh-media
|
||||
volumes:
|
||||
- ./seed-media:/seed-media:ro
|
||||
restart: "no"
|
||||
networks: [internal]
|
||||
logging: *default-logging
|
||||
entrypoint: >
|
||||
/bin/sh -c "
|
||||
mc alias set local http://minio:9000 $$MINIO_ROOT_USER $$MINIO_ROOT_PASSWORD &&
|
||||
mc mb --ignore-existing local/$$MINIO_BUCKET &&
|
||||
mc anonymous set download local/$$MINIO_BUCKET &&
|
||||
COUNT=$$(mc ls --recursive local/$$MINIO_BUCKET | wc -l) &&
|
||||
if [ \"$$COUNT\" -eq 0 ]; then
|
||||
echo 'minio-setup: bucket ready — mirroring seed media';
|
||||
mc mirror --overwrite /seed-media local/$$MINIO_BUCKET/;
|
||||
else
|
||||
echo \"minio-setup: bucket ready — $$COUNT object(s) already present, seed mirror skipped\";
|
||||
fi
|
||||
"
|
||||
|
||||
# یکبار اجرا میشود: دیتابیسهای جانبی روی همان نمونهٔ Postgres
|
||||
# (umami برای آنالیتیکس، aramesh_chatbot برای بردارهای چتبات)
|
||||
db-init:
|
||||
image: postgres:17-alpine
|
||||
restart: "no"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
PGHOST: db
|
||||
PGUSER: aramesh
|
||||
PGPASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD را در .env تنظیم کنید}
|
||||
networks: [internal]
|
||||
logging: *default-logging
|
||||
entrypoint: >
|
||||
/bin/sh -c "
|
||||
set -e;
|
||||
for DBN in umami aramesh_chatbot; do
|
||||
if ! psql -d arameshplaza -tAc \"SELECT 1 FROM pg_database WHERE datname='$$DBN'\" | grep -q 1; then
|
||||
psql -d arameshplaza -c \"CREATE DATABASE $$DBN\";
|
||||
fi;
|
||||
echo \"db-init: $$DBN ready\";
|
||||
done
|
||||
"
|
||||
|
||||
backend:
|
||||
build: ./backend
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
environment:
|
||||
DATABASE_URL: postgresql+psycopg://aramesh:aramesh@db:5432/arameshplaza
|
||||
SECRET_KEY: change-me-to-a-long-random-string
|
||||
CORS_ORIGINS: '["http://localhost:5173","http://127.0.0.1:5173"]'
|
||||
ADMIN_USERNAME: admin
|
||||
ADMIN_PASSWORD: aramesh123
|
||||
DATABASE_URL: postgresql+psycopg://aramesh:${POSTGRES_PASSWORD}@db:5432/arameshplaza
|
||||
SECRET_KEY: ${SECRET_KEY:?SECRET_KEY را در .env تنظیم کنید}
|
||||
CORS_ORIGINS: ${CORS_ORIGINS:-["http://localhost:5173","http://127.0.0.1:5173"]}
|
||||
ADMIN_USERNAME: ${ADMIN_USERNAME:-admin}
|
||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?ADMIN_PASSWORD را در .env تنظیم کنید}
|
||||
S3_ENDPOINT: http://minio:9000
|
||||
S3_ACCESS_KEY: ${MINIO_ROOT_USER:-aramesh}
|
||||
S3_SECRET_KEY: ${MINIO_ROOT_PASSWORD:?MINIO_ROOT_PASSWORD را در .env تنظیم کنید}
|
||||
S3_BUCKET: aramesh-media
|
||||
MEDIA_PUBLIC_BASE: /media
|
||||
# نشانی عمومی سایت — برای sitemap و آدرس مطلق OG (مثل https://aramesh.example)
|
||||
SITE_URL: ${SITE_URL:-}
|
||||
# بیلد فرانتاند برای تزریق متای سئو در صفحات /blog و /projects
|
||||
FRONTEND_DIST: /srv/frontend
|
||||
volumes:
|
||||
- ./frontend/dist:/srv/frontend:ro
|
||||
networks: [edge, internal]
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "8000:8000"
|
||||
minio:
|
||||
condition: service_healthy
|
||||
db-init:
|
||||
condition: service_completed_successfully
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/api/health')"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 20s
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
# Traefik باید IP لبه را بگیرد — سرویس روی دو شبکه است
|
||||
- traefik.docker.network=aramesh-backend_edge
|
||||
- traefik.http.routers.api.rule=PathPrefix(`/api`)
|
||||
- traefik.http.routers.api.entrypoints=web
|
||||
- traefik.http.routers.api.priority=100
|
||||
# لایه دوم محافظت از فرمها — سیلاب درخواست را پیش از رسیدن به بکاند میبُرد؛
|
||||
# محدودسازی دقیق هر فرم در خود بکاند است (rate_limit.py)
|
||||
- traefik.http.routers.api.middlewares=api-flood
|
||||
- traefik.http.middlewares.api-flood.ratelimit.average=50
|
||||
- traefik.http.middlewares.api-flood.ratelimit.period=1s
|
||||
- traefik.http.middlewares.api-flood.ratelimit.burst=150
|
||||
- traefik.http.services.api.loadbalancer.server.port=8000
|
||||
# robots.txt و sitemap.xml و صفحات وبلاگ/پروژه با متای سئو — اولویت بالاتر از SPA
|
||||
# مسیرهای /en/... هم همه به بکاند میروند تا متای سئوی انگلیسی و html انگلیسی تزریق شود
|
||||
- traefik.http.routers.seo.rule=PathPrefix(`/blog/`) || Path(`/blog`) || PathPrefix(`/projects/`) || Path(`/projects`) || Path(`/en`) || PathPrefix(`/en/`) || PathPrefix(`/robots.txt`) || PathPrefix(`/sitemap.xml`)
|
||||
- traefik.http.routers.seo.entrypoints=web
|
||||
- traefik.http.routers.seo.priority=50
|
||||
- traefik.http.routers.seo.service=api
|
||||
# /metrics فقط برای Prometheus — روتری تعریف نمیشود، از بیرون در دسترس نیست
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 768M
|
||||
|
||||
# فقط سرو فایلهای استاتیک SPA — بیلد روی هاست (npm run build) انجام شده است
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
args:
|
||||
VITE_API_URL: ""
|
||||
build: ./frontend
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
depends_on:
|
||||
- backend
|
||||
ports:
|
||||
- "5173:80"
|
||||
backend:
|
||||
condition: service_healthy
|
||||
networks: [edge]
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "--spider", "http://localhost/"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 5s
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.web.rule=PathPrefix(`/`)
|
||||
- traefik.http.routers.web.entrypoints=web
|
||||
- traefik.http.routers.web.priority=1
|
||||
- traefik.http.services.web.loadbalancer.server.port=80
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 64M
|
||||
|
||||
# دستیار هوشمند — RAG روی محتوای سایت با pgvector
|
||||
# اولین اجرا مدلها را دانلود میکند (~۵۰۰MB روی حجم chatbot_hf) — کند است، طبیعی است
|
||||
chatbot:
|
||||
build: ./chatbot
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
environment:
|
||||
DATABASE_URL: postgresql+psycopg://aramesh:${POSTGRES_PASSWORD}@db:5432/arameshplaza
|
||||
LLM_BASE_URL: ${LLM_BASE_URL:-}
|
||||
LLM_API_KEY: ${LLM_API_KEY:-}
|
||||
LLM_MODEL: ${LLM_MODEL:-openai/gpt-oss-120b}
|
||||
CHAT_REINDEX_TOKEN: ${CHAT_REINDEX_TOKEN:-}
|
||||
volumes:
|
||||
- chatbot_hf:/data
|
||||
networks: [edge, internal]
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
db-init:
|
||||
condition: service_completed_successfully
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
# Traefik باید IP لبه را بگیرد — سرویس روی دو شبکه است
|
||||
- traefik.docker.network=aramesh-backend_edge
|
||||
- traefik.http.routers.chat.rule=PathPrefix(`/chat`)
|
||||
- traefik.http.routers.chat.entrypoints=web
|
||||
- traefik.http.routers.chat.priority=100
|
||||
- traefik.http.routers.chat.middlewares=api-flood
|
||||
- traefik.http.services.chat.loadbalancer.server.port=8000
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 2G
|
||||
|
||||
# آنالیتیکس محصول (Umami) — بازدید، ارجاع، رخدادهای سفارشی (فرم/تلفن/چتبات)
|
||||
# داشبورد: analytics.localhost (توسعه) یا analytics.DOMAIN (تولید)
|
||||
umami:
|
||||
image: ghcr.io/umami-software/umami:postgresql-v2.17.0
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
environment:
|
||||
DATABASE_URL: postgresql://aramesh:${POSTGRES_PASSWORD}@db:5432/umami
|
||||
# اسکریپت ردیاب به ارجاعدهندهٔ واقعی نیاز دارد — پشت Traefik
|
||||
CLIENT_IP_HEADER: x-forwarded-for
|
||||
DISABLE_TELEMETRY: 1
|
||||
networks: [edge, internal]
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
db-init:
|
||||
condition: service_completed_successfully
|
||||
healthcheck:
|
||||
# 127.0.0.1 نه localhost — «localhost» به ::1 حل میشود و umami فقط IPv4 گوش میدهد
|
||||
test: ["CMD-SHELL", "wget -q --spider http://127.0.0.1:3000/api/heartbeat || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 60s
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
# Traefik باید IP لبه را بگیرد — سرویس روی دو شبکه است
|
||||
- traefik.docker.network=aramesh-backend_edge
|
||||
- traefik.http.routers.analytics.rule=Host(`analytics.localhost`)
|
||||
- traefik.http.routers.analytics.entrypoints=web
|
||||
- traefik.http.services.analytics.loadbalancer.server.port=3000
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 512M
|
||||
|
||||
# ابزار پشتیبانگیری — فقط با پروفایل tools اجرا میشود (scripts/backup.sh این کار را میکند)
|
||||
mc:
|
||||
image: minio/mc:RELEASE.2025-04-08T15-39-49Z
|
||||
profiles: ["tools"]
|
||||
depends_on:
|
||||
minio:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-aramesh}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?MINIO_ROOT_PASSWORD را در .env تنظیم کنید}
|
||||
networks: [internal]
|
||||
|
||||
# پشتیبان ساعتی خودکار دیتابیس — بدون نیاز به cron میزبان؛ فقط با پروفایل ops
|
||||
# docker compose --profile ops up -d db-backup
|
||||
# RPO را از ۲۴ ساعت (cron شبانه) به ۱ ساعت میرساند؛ scripts/backup.sh برای
|
||||
# پشتیبان کامل (دیتابیس + تصاویر MinIO) سر جایش است.
|
||||
db-backup:
|
||||
image: prodrigestivill/postgres-backup-local:17
|
||||
profiles: ["ops"]
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
POSTGRES_HOST: db
|
||||
POSTGRES_DB: arameshplaza
|
||||
POSTGRES_USER: aramesh
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD را در .env تنظیم کنید}
|
||||
SCHEDULE: "@hourly"
|
||||
BACKUP_NUM_KEEP: "48"
|
||||
BACKUP_DIR: /backups
|
||||
volumes:
|
||||
- backups:/backups
|
||||
networks: [internal]
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 128M
|
||||
|
||||
networks:
|
||||
edge: # سرویسهایی که Traefik به آنها مسیریابی میکند
|
||||
internal: # دیتابیس و ذخیرهسازی — فرانتاند راهی به این شبکه ندارد
|
||||
|
||||
volumes:
|
||||
db_data:
|
||||
minio_data:
|
||||
chatbot_hf:
|
||||
backups:
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# فقط Caddyfile و dist/ به کانتکست بیلد میروند — node_modules و سورس عظیماند و لازم نیستند
|
||||
*
|
||||
!Caddyfile
|
||||
!dist
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
# پنل مدیریت Caddy لازم نیست — سطح حمله کمتر
|
||||
admin off
|
||||
}
|
||||
|
||||
:80 {
|
||||
root * /srv
|
||||
encode zstd gzip
|
||||
|
||||
# فایلهای هشدار بیلد: کش بلندمدت بیرحم — ولی هرگز fallback به index.html نداشته باشند؛
|
||||
# پاسخ 200ٔ HTML برای یک مسیر /assets/* نبوده (مثلاً هنگام پنجرهٔ تعویض کانتینر در استقرار)
|
||||
# توسط CDN (WCDN، سیاست SMART) با همین هدر immutable یک سال کش میشود و اسکریپت ماژول
|
||||
# را برای همه بازدیدکنندهها میشکند. فایل ناموجود در assets باید 404 بدهد، نه HTML.
|
||||
@assets path /assets/*
|
||||
handle @assets {
|
||||
file_server
|
||||
}
|
||||
|
||||
# مسیریابی SPA — مسیرهای ناشناختهٔ غیرasset به index.html برمیگردند
|
||||
handle {
|
||||
try_files {path} /index.html
|
||||
file_server
|
||||
}
|
||||
|
||||
# بقیه (از جمله index.html و fallback اسپا): بدون کش مرورگر تا هر استقرار فوری دیده شود
|
||||
@notassets not path /assets/*
|
||||
header @notassets Cache-Control "no-cache"
|
||||
header @assets Cache-Control "public, immutable, max-age=31536000"
|
||||
}
|
||||
@@ -1,23 +1,20 @@
|
||||
# ---------- مرحله ساخت ----------
|
||||
FROM node:22-alpine AS build
|
||||
# ---------- فرانتاند فقط سرو میکند ----------
|
||||
# بیلد روی هاست انجام میشود (npm install && npm run build) و خروجی dist/
|
||||
# داخل ایمیج کپی میشود — شبکه کانتینر بیلد برای npm قابلاعتماد نیست.
|
||||
|
||||
WORKDIR /app
|
||||
FROM caddy:2-alpine
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
# نسخهٔ alpine کاربر caddy ندارد — اینجا ساخته میشود؛ /config و /data مسیرهای
|
||||
# storage سیدی هستند و باید برای کاربر نوشتنی باشند
|
||||
RUN addgroup -S caddy \
|
||||
&& adduser -S -G caddy -s /sbin/nologin caddy \
|
||||
&& mkdir -p /config /data \
|
||||
&& chown -R caddy:caddy /config /data
|
||||
|
||||
COPY . .
|
||||
COPY Caddyfile /etc/caddy/Caddyfile
|
||||
COPY --chown=caddy:caddy dist /srv
|
||||
|
||||
# آدرس API در زمان بیلد؛ پیشفرض خالی یعنی درخواستهای نسبی (/api) که nginx آنها را به بکاند پروکسی میکند
|
||||
ARG VITE_API_URL=""
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
|
||||
RUN npm run build
|
||||
|
||||
# ---------- مرحله سرو ----------
|
||||
FROM nginx:alpine
|
||||
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
# بدون root — فقط فایلهای استاتیک سرو میشوند و TLS را Traefik تمام میکند
|
||||
USER caddy
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
@@ -1,8 +1,76 @@
|
||||
# Magic Patterns - Vite Template
|
||||
|
||||
This code was generated by [Magic Patterns](https://magicpatterns.com) for this design: [Source Design](https://www.magicpatterns.com/c/ka4i8ikygtakmdobhws6nu)
|
||||
# Aramesh Construction Group — Frontend
|
||||
|
||||
## Getting Started
|
||||
A modern React + Vite + TypeScript frontend application with a luxurious dark theme (Background: `#27221c`, Accent: `#d5874c`). All text content and assets are fetched dynamically from the backend API (`GET /api/site`).
|
||||
|
||||
## Typography & Smart Bidi Text
|
||||
The **Pinar** font is installed and served locally. The application no longer relies on any external servers or CDNs for font rendering, and the UI is fully localized for Persian (Farsi) users.
|
||||
|
||||
**Smart Bidi Typography:** To maintain perfect visual weight and baseline alignment when mixing English words within Persian text, we utilize a dynamic CSS calculation for Latin characters: `calc(1em - 2px)`. This ensures that English text automatically scales down slightly to match the natural density and baseline of the Persian font, preventing any visual imbalance in mixed-language sentences.
|
||||
|
||||
## Recent UI/UX Improvements
|
||||
* **Projects Map Restoration**: Successfully re-integrated and mounted the interactive project overview map directly at the top of the Projects page to display all project markers.
|
||||
* **Project Details Update**: Revamped and updated the presentation of project details for better clarity and structure.
|
||||
* **Stats Section Relocation**: Moved the statistics (metrics) section higher up in the page layout for better visibility and impact.
|
||||
* **FAQ Section Redesign**: Refactored the FAQ layout into a centered vertical stack with full RTL/LTR responsiveness, featuring an integrated centered header block (title, description, and accent line) and direction-aware (`text-start`) accordion content.
|
||||
* **Newsletter Section Polish**: Updated the newsletter container to a clean solid `bg-copper` background while introducing high-contrast button styling (`bg-ink` default transitioning to white on hover) preserving site-wide kinetic animation logic.
|
||||
* **Article Cards Spacing**: Refined vertical layout spacing and responsive gaps between title, excerpt, and footer blocks without impacting typography scales.
|
||||
* **Tiptap Editor Fixes**:
|
||||
* Resolved the initialization bug where the editor body remained empty during edit mode.
|
||||
* Fixed Tiptap block boundaries so formatting a new line (e.g., changing it to H2) no longer alters the formatting of the previous line.
|
||||
* **Dynamic TOC & Layout**:
|
||||
* The Table of Contents (TOC) is now strictly `position: sticky` and extracts all H2/H3 tags flawlessly.
|
||||
* The entire article layout (including Author, Read Time, and TOC) dynamically flips RTL/LTR based on the article's primary language.
|
||||
|
||||
## CMS, SEO & Editor Features
|
||||
|
||||
The project includes a robust, custom-built Digital Twin (Admin Panel) with advanced content management capabilities, emphasizing a premium UI/UX:
|
||||
|
||||
* **Advanced SEO & Featured Media:** Dynamic `meta_description` fields (150-160 characters). The Featured Image component features a compact layout with smart data-binding: the `Alt` text auto-fills based on the title (e.g., `[Title] - تصویر شاخص`) as a smart fallback to ensure SEO compliance, while still allowing **full manual overrides** for precise custom keyword targeting.
|
||||
* **Precise Category Management:** A flawlessly integrated, single-select category dropdown using `react-select` (Creatable) and `react-hook-form`. It allows creating new categories on the fly while retaining them in the global list, seamlessly matching the strict single-category backend schema.
|
||||
* **Article Metadata & Reading Time:** A beautifully designed metadata component displaying the author's avatar, name, publication date, and an auto-calculated dynamic reading time (displayed dynamically with Persian numerals, e.g., "۵ دقیقه مطالعه") directly below the H1 title.
|
||||
* **Dynamic Table of Contents (TOC):** Auto-generates a clickable TOC from `h2` and `h3` tags within the article, using a custom Persian-supported `slugify` logic for anchor links.
|
||||
* **Custom Tiptap WYSIWYG Editor:**
|
||||
* **Fixed Toolbar & Typography:** Dedicated LTR/RTL toggles (`data-dir="ltr|rtl"`) mapped to a fixed toolbar that ensures layout stability.
|
||||
* **Advanced Image & Caption Nodes:** Built via `ReactNodeViewRenderer`, rendering HTML wrapped in `<figure><figcaption>`. Features strictly isolated UI deletion controls.
|
||||
* **Animated Link Modal:** A premium, auto-opening modal with smooth fade/scale transition effects. Includes seamless checkbox toggles for "Open in new tab" (`target="_blank" rel="noopener noreferrer"`) and SEO link attributes (`nofollow/dofollow`).
|
||||
* **Full Jalali (Shamsi) Calendar Integration:**
|
||||
* Admin panel utilizes `react-multi-date-picker` for a visual Persian date selection experience.
|
||||
* Frontend and text displays rely on native `Intl.DateTimeFormat` to render dates and numerals perfectly in Persian.
|
||||
|
||||
## Development Setup
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev
|
||||
|
||||
```
|
||||
|
||||
In development mode, Vite proxies `/api` and `/media` requests to Traefik (port 5173). Therefore, the Docker stack must be running.
|
||||
The backend API URL is read from the `VITE_API_URL` environment variable in `src/config.ts`; an empty default implies same-origin requests.
|
||||
|
||||
## Build & Production
|
||||
|
||||
The build process runs on the host machine. The Docker container only serves the generated static files in the `dist/` directory using Caddy:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
|
||||
```
|
||||
|
||||
> **Note:** The backend reads the `dist/` directory (mounted at `/srv/frontend` in Docker Compose) to inject SEO metadata into the `/blog` and `/projects` pages. After making any frontend changes, running `npm run build` and restarting the backend is sufficient.
|
||||
|
||||
## Key Modules & Architecture
|
||||
|
||||
* `src/api.tsx` — Handles site data loading and draft article merging for the admin view.
|
||||
* `src/admin/` — Live editing layer (Digital Twin): includes the admin toolbar, entity drawers, and the article editor.
|
||||
* `src/seo.ts` — Manages page-level SEO tags (Title, Description, Open Graph, Canonical, JSON-LD).
|
||||
* `src/data/site.ts` — Shared TypeScript data models and interfaces.
|
||||
|
||||
```
|
||||
|
||||
حالا اگر بخواهید این تغییرات جدید را هم در پیام کامیت خود بیاورید، میتوانید از این کامیت یکخطی استفاده کنید:
|
||||
|
||||
```bash
|
||||
git commit -m "docs: update README with project details revamp, stats section relocation, FAQ layout, and map restoration"
|
||||
|
||||
1. Run `npm install`
|
||||
2. Run `npm run dev`
|
||||
|
||||
@@ -1,13 +1,43 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<html lang="fa" dir="rtl">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Aramesh Building Group Luxury Website</title>
|
||||
<!-- پیشبارگذاری فونتهای اصلی — بدون این، swap فونت با تأخیر میآید (LCP) -->
|
||||
<link rel="preload" href="/fonts/pinar/Pinar-Light.woff2" as="font" type="font/woff2" crossorigin />
|
||||
<link rel="preload" href="/fonts/pinar/Pinar-Regular.woff2" as="font" type="font/woff2" crossorigin />
|
||||
<link rel="preload" href="/fonts/pinar/Pinar-Bold.woff2" as="font" type="font/woff2" crossorigin />
|
||||
<title>گروه ساختمانی آرامش</title>
|
||||
<meta name="description" content="گروه ساختمانی آرامش — طراحی، اجرا و مدیریت پروژههای ساختمانی؛ خدمات مهندسی، پیمانکاری و سرمایهگذاری ساختوساز." />
|
||||
<meta property="og:site_name" content="گروه ساختمانی آرامش" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:locale" content="fa_IR" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<script type="application/ld+json">
|
||||
{"@context":"https://schema.org","@type":"Organization","name":"گروه ساختمانی آرامش","inLanguage":"fa"}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script>
|
||||
// زبان و جهت سند پیش از اولین رندر، از خود مسیر — /en/... انگلیسی و LTR است
|
||||
// تا جهت صفحه از نخستین فریم درست باشد (نسخه انگلیسی سمت سرور هم همین را تزریق میکند)
|
||||
if (location.pathname === '/en' || location.pathname.startsWith('/en/')) {
|
||||
document.documentElement.setAttribute('lang', 'en');
|
||||
document.documentElement.setAttribute('dir', 'ltr');
|
||||
}
|
||||
</script>
|
||||
<script type="module">
|
||||
// تحلیل رفتار (Umami) — در زمان بیلد تزریق میشود؛ VITE_UMAMI_SRC خالی یعنی خاموش
|
||||
if (import.meta.env.VITE_UMAMI_SRC) {
|
||||
const s = document.createElement('script');
|
||||
s.defer = true;
|
||||
s.src = import.meta.env.VITE_UMAMI_SRC;
|
||||
s.setAttribute('data-website-id', import.meta.env.VITE_UMAMI_WEBSITE_ID ?? '');
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
</script>
|
||||
<script type="module" src="/src/index.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# مسیریابی SPA — همه مسیرها به index.html برمیگردند
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# پروکسی درخواستهای API به سرویس بکاند
|
||||
location /api/ {
|
||||
proxy_pass http://backend:8000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# کش استاتیک
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|svg|woff2?)$ {
|
||||
expires 30d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
}
|
||||
@@ -6,16 +6,34 @@
|
||||
"scripts": {
|
||||
"dev": "npx vite",
|
||||
"build": "npx vite build",
|
||||
"build:map-worker": "esbuild src/map/pmtiles.worker.ts --bundle --format=esm --outfile=public/map/pmtiles-worker.mjs",
|
||||
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
|
||||
"preview": "npx vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.13.3",
|
||||
"@tiptap/extension-image": "^3.31.3",
|
||||
"@tiptap/extension-link": "^3.31.3",
|
||||
"@tiptap/extension-table": "^3.31.3",
|
||||
"@tiptap/extension-table-cell": "^3.31.3",
|
||||
"@tiptap/extension-table-header": "^3.31.3",
|
||||
"@tiptap/extension-table-row": "^3.31.3",
|
||||
"@tiptap/pm": "^3.31.3",
|
||||
"@tiptap/react": "^3.31.3",
|
||||
"@tiptap/starter-kit": "^3.31.3",
|
||||
"@tiptap/static-renderer": "^3.31.3",
|
||||
"framer-motion": "^11.5.4",
|
||||
"lucide-react": "0.522.0",
|
||||
"maplibre-gl": "^6.10.0",
|
||||
"pmtiles": "^4.5.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-hook-form": "^7.88.0",
|
||||
"react-icons": "^5.7.0",
|
||||
"react-multi-date-picker": "^4.5.2",
|
||||
"react-router-dom": "^6.26.2",
|
||||
"react-select": "^5.10.2",
|
||||
"slugify": "^1.6.9",
|
||||
"sweetalert2": "^11.26.25"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,836 @@
|
||||
// node_modules/fflate/esm/browser.js
|
||||
var u8 = Uint8Array;
|
||||
var u16 = Uint16Array;
|
||||
var i32 = Int32Array;
|
||||
var fleb = new u8([
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
3,
|
||||
3,
|
||||
3,
|
||||
3,
|
||||
4,
|
||||
4,
|
||||
4,
|
||||
4,
|
||||
5,
|
||||
5,
|
||||
5,
|
||||
5,
|
||||
0,
|
||||
/* unused */
|
||||
0,
|
||||
0,
|
||||
/* impossible */
|
||||
0
|
||||
]);
|
||||
var fdeb = new u8([
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
2,
|
||||
2,
|
||||
3,
|
||||
3,
|
||||
4,
|
||||
4,
|
||||
5,
|
||||
5,
|
||||
6,
|
||||
6,
|
||||
7,
|
||||
7,
|
||||
8,
|
||||
8,
|
||||
9,
|
||||
9,
|
||||
10,
|
||||
10,
|
||||
11,
|
||||
11,
|
||||
12,
|
||||
12,
|
||||
13,
|
||||
13,
|
||||
/* unused */
|
||||
0,
|
||||
0
|
||||
]);
|
||||
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
|
||||
var freb = function(eb, start) {
|
||||
var b2 = new u16(31);
|
||||
for (var i = 0; i < 31; ++i) {
|
||||
b2[i] = start += 1 << eb[i - 1];
|
||||
}
|
||||
var r = new i32(b2[30]);
|
||||
for (var i = 1; i < 30; ++i) {
|
||||
for (var j2 = b2[i]; j2 < b2[i + 1]; ++j2) {
|
||||
r[j2] = j2 - b2[i] << 5 | i;
|
||||
}
|
||||
}
|
||||
return { b: b2, r };
|
||||
};
|
||||
var _a = freb(fleb, 2);
|
||||
var fl = _a.b;
|
||||
var revfl = _a.r;
|
||||
fl[28] = 258, revfl[258] = 28;
|
||||
var _b = freb(fdeb, 0);
|
||||
var fd = _b.b;
|
||||
var revfd = _b.r;
|
||||
var rev = new u16(32768);
|
||||
for (i = 0; i < 32768; ++i) {
|
||||
x2 = (i & 43690) >> 1 | (i & 21845) << 1;
|
||||
x2 = (x2 & 52428) >> 2 | (x2 & 13107) << 2;
|
||||
x2 = (x2 & 61680) >> 4 | (x2 & 3855) << 4;
|
||||
rev[i] = ((x2 & 65280) >> 8 | (x2 & 255) << 8) >> 1;
|
||||
}
|
||||
var x2;
|
||||
var i;
|
||||
var hMap = function(cd, mb, r) {
|
||||
var s = cd.length;
|
||||
var i = 0;
|
||||
var l = new u16(mb);
|
||||
for (; i < s; ++i) {
|
||||
if (cd[i])
|
||||
++l[cd[i] - 1];
|
||||
}
|
||||
var le = new u16(mb);
|
||||
for (i = 1; i < mb; ++i) {
|
||||
le[i] = le[i - 1] + l[i - 1] << 1;
|
||||
}
|
||||
var co;
|
||||
if (r) {
|
||||
co = new u16(1 << mb);
|
||||
var rvb = 15 - mb;
|
||||
for (i = 0; i < s; ++i) {
|
||||
if (cd[i]) {
|
||||
var sv = i << 4 | cd[i];
|
||||
var r_1 = mb - cd[i];
|
||||
var v2 = le[cd[i] - 1]++ << r_1;
|
||||
for (var m = v2 | (1 << r_1) - 1; v2 <= m; ++v2) {
|
||||
co[rev[v2] >> rvb] = sv;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
co = new u16(s);
|
||||
for (i = 0; i < s; ++i) {
|
||||
if (cd[i]) {
|
||||
co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
return co;
|
||||
};
|
||||
var flt = new u8(288);
|
||||
for (i = 0; i < 144; ++i)
|
||||
flt[i] = 8;
|
||||
var i;
|
||||
for (i = 144; i < 256; ++i)
|
||||
flt[i] = 9;
|
||||
var i;
|
||||
for (i = 256; i < 280; ++i)
|
||||
flt[i] = 7;
|
||||
var i;
|
||||
for (i = 280; i < 288; ++i)
|
||||
flt[i] = 8;
|
||||
var i;
|
||||
var fdt = new u8(32);
|
||||
for (i = 0; i < 32; ++i)
|
||||
fdt[i] = 5;
|
||||
var i;
|
||||
var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
|
||||
var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
|
||||
var max = function(a) {
|
||||
var m = a[0];
|
||||
for (var i = 1; i < a.length; ++i) {
|
||||
if (a[i] > m)
|
||||
m = a[i];
|
||||
}
|
||||
return m;
|
||||
};
|
||||
var bits = function(d2, p, m) {
|
||||
var o = p / 8 | 0;
|
||||
return (d2[o] | d2[o + 1] << 8) >> (p & 7) & m;
|
||||
};
|
||||
var bits16 = function(d2, p) {
|
||||
var o = p / 8 | 0;
|
||||
return (d2[o] | d2[o + 1] << 8 | d2[o + 2] << 16) >> (p & 7);
|
||||
};
|
||||
var shft = function(p) {
|
||||
return (p + 7) / 8 | 0;
|
||||
};
|
||||
var slc = function(v2, s, e) {
|
||||
if (s == null || s < 0)
|
||||
s = 0;
|
||||
if (e == null || e > v2.length)
|
||||
e = v2.length;
|
||||
return new u8(v2.subarray(s, e));
|
||||
};
|
||||
var ec = [
|
||||
"unexpected EOF",
|
||||
"invalid block type",
|
||||
"invalid length/literal",
|
||||
"invalid distance",
|
||||
"stream finished",
|
||||
"no stream handler",
|
||||
,
|
||||
// determined by compression function
|
||||
"no callback",
|
||||
"invalid UTF-8 data",
|
||||
"extra field too long",
|
||||
"date not in range 1980-2099",
|
||||
"filename too long",
|
||||
"stream finishing",
|
||||
"invalid zip data"
|
||||
// determined by unknown compression method
|
||||
];
|
||||
var err = function(ind, msg, nt) {
|
||||
var e = new Error(msg || ec[ind]);
|
||||
e.code = ind;
|
||||
if (Error.captureStackTrace)
|
||||
Error.captureStackTrace(e, err);
|
||||
if (!nt)
|
||||
throw e;
|
||||
return e;
|
||||
};
|
||||
var inflt = function(dat, st, buf, dict) {
|
||||
var sl = dat.length, dl = dict ? dict.length : 0;
|
||||
if (!sl || st.f && !st.l)
|
||||
return buf || new u8(0);
|
||||
var noBuf = !buf;
|
||||
var resize = noBuf || st.i != 2;
|
||||
var noSt = st.i;
|
||||
if (noBuf)
|
||||
buf = new u8(sl * 3);
|
||||
var cbuf = function(l2) {
|
||||
var bl = buf.length;
|
||||
if (l2 > bl) {
|
||||
var nbuf = new u8(Math.max(bl * 2, l2));
|
||||
nbuf.set(buf);
|
||||
buf = nbuf;
|
||||
}
|
||||
};
|
||||
var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
|
||||
var tbts = sl * 8;
|
||||
do {
|
||||
if (!lm) {
|
||||
final = bits(dat, pos, 1);
|
||||
var type = bits(dat, pos + 1, 3);
|
||||
pos += 3;
|
||||
if (!type) {
|
||||
var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
|
||||
if (t > sl) {
|
||||
if (noSt)
|
||||
err(0);
|
||||
break;
|
||||
}
|
||||
if (resize)
|
||||
cbuf(bt + l);
|
||||
buf.set(dat.subarray(s, t), bt);
|
||||
st.b = bt += l, st.p = pos = t * 8, st.f = final;
|
||||
continue;
|
||||
} else if (type == 1)
|
||||
lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
|
||||
else if (type == 2) {
|
||||
var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
|
||||
var tl = hLit + bits(dat, pos + 5, 31) + 1;
|
||||
pos += 14;
|
||||
var ldt = new u8(tl);
|
||||
var clt = new u8(19);
|
||||
for (var i = 0; i < hcLen; ++i) {
|
||||
clt[clim[i]] = bits(dat, pos + i * 3, 7);
|
||||
}
|
||||
pos += hcLen * 3;
|
||||
var clb = max(clt), clbmsk = (1 << clb) - 1;
|
||||
var clm = hMap(clt, clb, 1);
|
||||
for (var i = 0; i < tl; ) {
|
||||
var r = clm[bits(dat, pos, clbmsk)];
|
||||
pos += r & 15;
|
||||
var s = r >> 4;
|
||||
if (s < 16) {
|
||||
ldt[i++] = s;
|
||||
} else {
|
||||
var c = 0, n = 0;
|
||||
if (s == 16)
|
||||
n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
|
||||
else if (s == 17)
|
||||
n = 3 + bits(dat, pos, 7), pos += 3;
|
||||
else if (s == 18)
|
||||
n = 11 + bits(dat, pos, 127), pos += 7;
|
||||
while (n--)
|
||||
ldt[i++] = c;
|
||||
}
|
||||
}
|
||||
var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
|
||||
lbt = max(lt);
|
||||
dbt = max(dt);
|
||||
lm = hMap(lt, lbt, 1);
|
||||
dm = hMap(dt, dbt, 1);
|
||||
} else
|
||||
err(1);
|
||||
if (pos > tbts) {
|
||||
if (noSt)
|
||||
err(0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (resize)
|
||||
cbuf(bt + 131072);
|
||||
var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
|
||||
var lpos = pos;
|
||||
for (; ; lpos = pos) {
|
||||
var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
|
||||
pos += c & 15;
|
||||
if (pos > tbts) {
|
||||
if (noSt)
|
||||
err(0);
|
||||
break;
|
||||
}
|
||||
if (!c)
|
||||
err(2);
|
||||
if (sym < 256)
|
||||
buf[bt++] = sym;
|
||||
else if (sym == 256) {
|
||||
lpos = pos, lm = null;
|
||||
break;
|
||||
} else {
|
||||
var add = sym - 254;
|
||||
if (sym > 264) {
|
||||
var i = sym - 257, b2 = fleb[i];
|
||||
add = bits(dat, pos, (1 << b2) - 1) + fl[i];
|
||||
pos += b2;
|
||||
}
|
||||
var d2 = dm[bits16(dat, pos) & dms], dsym = d2 >> 4;
|
||||
if (!d2)
|
||||
err(3);
|
||||
pos += d2 & 15;
|
||||
var dt = fd[dsym];
|
||||
if (dsym > 3) {
|
||||
var b2 = fdeb[dsym];
|
||||
dt += bits16(dat, pos) & (1 << b2) - 1, pos += b2;
|
||||
}
|
||||
if (pos > tbts) {
|
||||
if (noSt)
|
||||
err(0);
|
||||
break;
|
||||
}
|
||||
if (resize)
|
||||
cbuf(bt + 131072);
|
||||
var end = bt + add;
|
||||
if (bt < dt) {
|
||||
var shift = dl - dt, dend = Math.min(dt, end);
|
||||
if (shift + bt < 0)
|
||||
err(3);
|
||||
for (; bt < dend; ++bt)
|
||||
buf[bt] = dict[shift + bt];
|
||||
}
|
||||
for (; bt < end; ++bt)
|
||||
buf[bt] = buf[bt - dt];
|
||||
}
|
||||
}
|
||||
st.l = lm, st.p = lpos, st.b = bt, st.f = final;
|
||||
if (lm)
|
||||
final = 1, st.m = lbt, st.d = dm, st.n = dbt;
|
||||
} while (!final);
|
||||
return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
|
||||
};
|
||||
var et = /* @__PURE__ */ new u8(0);
|
||||
var gzs = function(d2) {
|
||||
if (d2[0] != 31 || d2[1] != 139 || d2[2] != 8)
|
||||
err(6, "invalid gzip data");
|
||||
var flg = d2[3];
|
||||
var st = 10;
|
||||
if (flg & 4)
|
||||
st += (d2[10] | d2[11] << 8) + 2;
|
||||
for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d2[st++])
|
||||
;
|
||||
return st + (flg & 2);
|
||||
};
|
||||
var gzl = function(d2) {
|
||||
var l = d2.length;
|
||||
return (d2[l - 4] | d2[l - 3] << 8 | d2[l - 2] << 16 | d2[l - 1] << 24) >>> 0;
|
||||
};
|
||||
var zls = function(d2, dict) {
|
||||
if ((d2[0] & 15) != 8 || d2[0] >> 4 > 7 || (d2[0] << 8 | d2[1]) % 31)
|
||||
err(6, "invalid zlib data");
|
||||
if ((d2[1] >> 5 & 1) == +!dict)
|
||||
err(6, "invalid zlib data: " + (d2[1] & 32 ? "need" : "unexpected") + " dictionary");
|
||||
return (d2[1] >> 3 & 4) + 2;
|
||||
};
|
||||
function inflateSync(data, opts) {
|
||||
return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
|
||||
}
|
||||
function gunzipSync(data, opts) {
|
||||
var st = gzs(data);
|
||||
if (st + 8 > data.length)
|
||||
err(6, "invalid gzip data");
|
||||
return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);
|
||||
}
|
||||
function unzlibSync(data, opts) {
|
||||
return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);
|
||||
}
|
||||
function decompressSync(data, opts) {
|
||||
return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzipSync(data, opts) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflateSync(data, opts) : unzlibSync(data, opts);
|
||||
}
|
||||
var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
|
||||
var tds = 0;
|
||||
try {
|
||||
td.decode(et, { stream: true });
|
||||
tds = 1;
|
||||
} catch (e) {
|
||||
}
|
||||
|
||||
// node_modules/pmtiles/dist/esm/index.js
|
||||
var j = Object.defineProperty;
|
||||
var S = Math.pow;
|
||||
var d = (o, t) => j(o, "name", { value: t, configurable: true });
|
||||
var h = (o, t, e) => new Promise((r, n) => {
|
||||
var s = (c) => {
|
||||
try {
|
||||
a(e.next(c));
|
||||
} catch (l) {
|
||||
n(l);
|
||||
}
|
||||
}, i = (c) => {
|
||||
try {
|
||||
a(e.throw(c));
|
||||
} catch (l) {
|
||||
n(l);
|
||||
}
|
||||
}, a = (c) => c.done ? r(c.value) : Promise.resolve(c.value).then(s, i);
|
||||
a((e = e.apply(o, t)).next());
|
||||
});
|
||||
var re = d((o, t) => {
|
||||
let e = false, r = "", n = L.GridLayer.extend({ createTile: d((s, i) => {
|
||||
let a = document.createElement("img"), c = new AbortController(), l = c.signal;
|
||||
return a.cancel = () => {
|
||||
c.abort();
|
||||
}, e || (o.getHeader().then((u) => {
|
||||
u.tileType === 1 || u.tileType === 6 ? console.error("Error: archive contains vector tiles, but leafletRasterLayer is for displaying raster tiles. See https://github.com/protomaps/PMTiles/tree/main/js for details.") : u.tileType === 2 ? r = "image/png" : u.tileType === 3 ? r = "image/jpeg" : u.tileType === 4 ? r = "image/webp" : u.tileType === 5 && (r = "image/avif");
|
||||
}), e = true), o.getZxy(s.z, s.x, s.y, l).then((u) => {
|
||||
if (u) {
|
||||
let m = new Blob([u.data], { type: r }), g = window.URL.createObjectURL(m);
|
||||
a.src = g;
|
||||
} else a.style.display = "none";
|
||||
a.cancel = void 0, i(void 0, a);
|
||||
}).catch((u) => {
|
||||
if (u.name !== "AbortError") throw u;
|
||||
}), a;
|
||||
}, "createTile"), _removeTile: d(function(s) {
|
||||
let i = this._tiles[s];
|
||||
i && (i.el.cancel && i.el.cancel(), i.el.src && window.URL.revokeObjectURL(i.el.src), i.el.width = 0, i.el.height = 0, i.el.deleted = true, L.DomUtil.remove(i.el), delete this._tiles[s], this.fire("tileunload", { tile: i.el, coords: this._keyToTileCoords(s) }));
|
||||
}, "_removeTile") });
|
||||
return new n(t);
|
||||
}, "leafletRasterLayer");
|
||||
var z = d((o) => (t, e) => {
|
||||
if (e instanceof AbortController) return o(t, e);
|
||||
let r = new AbortController();
|
||||
return o(t, r).then((n) => e(void 0, n.data, n.cacheControl || "", n.expires || ""), (n) => e(n)).catch((n) => e(n)), { cancel: d(() => r.abort(), "cancel") };
|
||||
}, "v3compat");
|
||||
var A = class A2 {
|
||||
constructor(t) {
|
||||
this.tilev4 = d((t2, e) => h(this, null, function* () {
|
||||
if (t2.type === "json") {
|
||||
let g = t2.url.substr(10), p = this.tiles.get(g);
|
||||
if (p || (p = new w(g), this.tiles.set(g, p)), this.metadata) {
|
||||
let K = yield p.getTileJson(t2.url);
|
||||
return e.signal.throwIfAborted(), { data: K };
|
||||
}
|
||||
let f = yield p.getHeader();
|
||||
return e.signal.throwIfAborted(), (f.minLon >= f.maxLon || f.minLat >= f.maxLat) && console.error(`Bounds of PMTiles archive ${f.minLon},${f.minLat},${f.maxLon},${f.maxLat} are not valid.`), { data: { tiles: [`${t2.url}/{z}/{x}/{y}`], minzoom: f.minZoom, maxzoom: f.maxZoom, bounds: [f.minLon, f.minLat, f.maxLon, f.maxLat] } };
|
||||
}
|
||||
let r = new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/), n = t2.url.match(r);
|
||||
if (!n) throw new Error("Invalid PMTiles protocol URL");
|
||||
let s = n[1], i = this.tiles.get(s);
|
||||
i || (i = new w(s), this.tiles.set(s, i));
|
||||
let a = n[2], c = n[3], l = n[4], u = yield i == null ? void 0 : i.getZxy(+a, +c, +l, e.signal);
|
||||
if (e.signal.throwIfAborted(), u) return { data: new Uint8Array(u.data), cacheControl: u.cacheControl, expires: u.expires };
|
||||
let m = yield i.getHeader();
|
||||
if (m.tileType === 1 || m.tileType === 6) {
|
||||
if (this.errorOnMissingTile) throw new Error("Tile not found.");
|
||||
return { data: new Uint8Array() };
|
||||
}
|
||||
return { data: null };
|
||||
}), "tilev4");
|
||||
this.tile = z(this.tilev4);
|
||||
this.tiles = /* @__PURE__ */ new Map(), this.metadata = (t == null ? void 0 : t.metadata) || false, this.errorOnMissingTile = (t == null ? void 0 : t.errorOnMissingTile) || false;
|
||||
}
|
||||
add(t) {
|
||||
this.tiles.set(t.source.getKey(), t);
|
||||
}
|
||||
get(t) {
|
||||
return this.tiles.get(t);
|
||||
}
|
||||
};
|
||||
d(A, "Protocol");
|
||||
var B = A;
|
||||
function b(o, t) {
|
||||
return (t >>> 0) * 4294967296 + (o >>> 0);
|
||||
}
|
||||
d(b, "toNum");
|
||||
function N(o, t) {
|
||||
let e = t.buf, r = e[t.pos++], n = (r & 112) >> 4;
|
||||
if (r < 128 || (r = e[t.pos++], n |= (r & 127) << 3, r < 128) || (r = e[t.pos++], n |= (r & 127) << 10, r < 128) || (r = e[t.pos++], n |= (r & 127) << 17, r < 128) || (r = e[t.pos++], n |= (r & 127) << 24, r < 128) || (r = e[t.pos++], n |= (r & 1) << 31, r < 128)) return b(o, n);
|
||||
throw new Error("Expected varint not more than 10 bytes");
|
||||
}
|
||||
d(N, "readVarintRemainder");
|
||||
function x(o) {
|
||||
let t = o.buf, e = t[o.pos++], r = e & 127;
|
||||
return e < 128 || (e = t[o.pos++], r |= (e & 127) << 7, e < 128) || (e = t[o.pos++], r |= (e & 127) << 14, e < 128) || (e = t[o.pos++], r |= (e & 127) << 21, e < 128) ? r : (e = t[o.pos], r |= (e & 15) << 28, N(r, o));
|
||||
}
|
||||
d(x, "readVarint");
|
||||
function I(o, t, e, r, n) {
|
||||
return n === 0 ? r !== 0 ? [o - 1 - e, o - 1 - t] : [e, t] : [t, e];
|
||||
}
|
||||
d(I, "rotate");
|
||||
function q(o, t, e) {
|
||||
if (o > 26) throw new Error("Tile zoom level exceeds max safe number limit (26)");
|
||||
if (t >= 1 << o || e >= 1 << o) throw new Error("tile x/y outside zoom level bounds");
|
||||
let r = ((1 << o) * (1 << o) - 1) / 3, n = o - 1, [s, i] = [t, e];
|
||||
for (let a = 1 << n; a > 0; a >>= 1) {
|
||||
let c = s & a, l = i & a;
|
||||
r += (3 * c ^ l) * (1 << n), [s, i] = I(a, s, i, c, l), n--;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
d(q, "zxyToTileId");
|
||||
function G(o) {
|
||||
let t = 3 * o + 1;
|
||||
return t < 4294967296 ? 31 - Math.clz32(t) : 63 - Math.clz32(t / 4294967296);
|
||||
}
|
||||
d(G, "tileIdToZ");
|
||||
function ie(o) {
|
||||
let t = G(o) >> 1;
|
||||
if (t > 26) throw new Error("Tile zoom level exceeds max safe number limit (26)");
|
||||
let e = ((1 << t) * (1 << t) - 1) / 3, r = o - e, n = 0, s = 0, i = 1 << t;
|
||||
for (let a = 1; a < i; a <<= 1) {
|
||||
let c = a & r / 2, l = a & (r ^ c);
|
||||
[n, s] = I(a, n, s, c, l), r = r / 2, n += c, s += l;
|
||||
}
|
||||
return [t, n, s];
|
||||
}
|
||||
d(ie, "tileIdToZxy");
|
||||
var J = ((s) => (s[s.Unknown = 0] = "Unknown", s[s.None = 1] = "None", s[s.Gzip = 2] = "Gzip", s[s.Brotli = 3] = "Brotli", s[s.Zstd = 4] = "Zstd", s))(J || {});
|
||||
function P(o, t) {
|
||||
return h(this, null, function* () {
|
||||
if (t === 1 || t === 0) return o;
|
||||
if (t === 2) {
|
||||
if (typeof globalThis.DecompressionStream == "undefined") return decompressSync(new Uint8Array(o));
|
||||
let e = new Response(o).body;
|
||||
if (!e) throw new Error("Failed to read response stream");
|
||||
let r = e.pipeThrough(new globalThis.DecompressionStream("gzip"));
|
||||
return new Response(r).arrayBuffer();
|
||||
}
|
||||
throw new Error("Compression method not supported");
|
||||
});
|
||||
}
|
||||
d(P, "defaultDecompress");
|
||||
var O = ((a) => (a[a.Unknown = 0] = "Unknown", a[a.Mvt = 1] = "Mvt", a[a.Png = 2] = "Png", a[a.Jpeg = 3] = "Jpeg", a[a.Webp = 4] = "Webp", a[a.Avif = 5] = "Avif", a[a.Mlt = 6] = "Mlt", a))(O || {});
|
||||
function _(o) {
|
||||
return o === 1 ? ".mvt" : o === 2 ? ".png" : o === 3 ? ".jpg" : o === 4 ? ".webp" : o === 5 ? ".avif" : o === 6 ? ".mlt" : "";
|
||||
}
|
||||
d(_, "tileTypeExt");
|
||||
var Y = 127;
|
||||
function Q(o, t) {
|
||||
let e = 0, r = o.length - 1;
|
||||
for (; e <= r; ) {
|
||||
let n = r + e >> 1, s = t - o[n].tileId;
|
||||
if (s > 0) e = n + 1;
|
||||
else if (s < 0) r = n - 1;
|
||||
else return o[n];
|
||||
}
|
||||
return r >= 0 && (o[r].runLength === 0 || t - o[r].tileId < o[r].runLength) ? o[r] : null;
|
||||
}
|
||||
d(Q, "findTile");
|
||||
var T = class T2 {
|
||||
constructor(t) {
|
||||
this.file = t;
|
||||
}
|
||||
getKey() {
|
||||
return this.file.name;
|
||||
}
|
||||
getBytes(t, e) {
|
||||
return h(this, null, function* () {
|
||||
return { data: yield this.file.slice(t, t + e).arrayBuffer() };
|
||||
});
|
||||
}
|
||||
};
|
||||
d(T, "FileSource");
|
||||
var D = class D2 {
|
||||
constructor(t, e = new Headers(), r = void 0) {
|
||||
var a, c;
|
||||
this.url = t, this.customHeaders = e, this.credentials = r, this.mustReload = false;
|
||||
let n = "";
|
||||
"navigator" in globalThis && (n = (c = (a = globalThis.navigator) == null ? void 0 : a.userAgent) != null ? c : "");
|
||||
let s = n.indexOf("Windows") > -1, i = /Chrome|Chromium|Edg|OPR|Brave/.test(n);
|
||||
this.chromeWindowsNoCache = false, s && i && (this.chromeWindowsNoCache = true);
|
||||
}
|
||||
getKey() {
|
||||
return this.url;
|
||||
}
|
||||
setHeaders(t) {
|
||||
this.customHeaders = t;
|
||||
}
|
||||
getBytes(t, e, r, n) {
|
||||
return h(this, null, function* () {
|
||||
let s, i;
|
||||
r ? i = r : (s = new AbortController(), i = s.signal);
|
||||
let a = new Headers(this.customHeaders);
|
||||
a.set("range", `bytes=${t}-${t + e - 1}`);
|
||||
let c;
|
||||
this.mustReload ? c = "reload" : this.chromeWindowsNoCache && (c = "no-store");
|
||||
let l = yield fetch(this.url, { signal: i, cache: c, headers: a, credentials: this.credentials });
|
||||
if (t === 0 && l.status === 416) {
|
||||
let p = l.headers.get("Content-Range");
|
||||
if (!p || !p.startsWith("bytes */")) throw new Error("Missing content-length on 416 response");
|
||||
let f = +p.substr(8);
|
||||
a.set("range", `bytes=0-${f - 1}`), l = yield fetch(this.url, { signal: i, cache: "reload", headers: a, credentials: this.credentials });
|
||||
}
|
||||
let u = l.headers.get("Etag");
|
||||
if (u != null && u.startsWith("W/") && (u = null), l.status === 416 || n && u && u !== n) throw this.mustReload = true, new v(`Server returned non-matching ETag ${n} after one retry. Check browser extensions and servers for issues that may affect correct ETag headers.`);
|
||||
if (l.status >= 300) throw new Error(`Bad response code: ${l.status}`);
|
||||
let m = l.headers.get("Content-Length");
|
||||
if (l.status === 200 && (!m || +m > e)) throw s && s.abort(), new Error("Server returned no content-length header or content-length exceeding request. Check that your storage backend supports HTTP Byte Serving.");
|
||||
return { data: yield l.arrayBuffer(), etag: u || void 0, cacheControl: l.headers.get("Cache-Control") || void 0, expires: l.headers.get("Expires") || void 0 };
|
||||
});
|
||||
}
|
||||
};
|
||||
d(D, "FetchSource");
|
||||
var E = D;
|
||||
function y(o, t) {
|
||||
let e = o.getUint32(t + 4, true), r = o.getUint32(t + 0, true);
|
||||
return e * S(2, 32) + r;
|
||||
}
|
||||
d(y, "getUint64");
|
||||
function X(o, t) {
|
||||
let e = new DataView(o), r = e.getUint8(7);
|
||||
if (r > 3) throw new Error(`Archive is spec version ${r} but this library supports up to spec version 3`);
|
||||
return { specVersion: r, rootDirectoryOffset: y(e, 8), rootDirectoryLength: y(e, 16), jsonMetadataOffset: y(e, 24), jsonMetadataLength: y(e, 32), leafDirectoryOffset: y(e, 40), leafDirectoryLength: y(e, 48), tileDataOffset: y(e, 56), tileDataLength: y(e, 64), numAddressedTiles: y(e, 72), numTileEntries: y(e, 80), numTileContents: y(e, 88), clustered: e.getUint8(96) === 1, internalCompression: e.getUint8(97), tileCompression: e.getUint8(98), tileType: e.getUint8(99), minZoom: e.getUint8(100), maxZoom: e.getUint8(101), minLon: e.getInt32(102, true) / 1e7, minLat: e.getInt32(106, true) / 1e7, maxLon: e.getInt32(110, true) / 1e7, maxLat: e.getInt32(114, true) / 1e7, centerZoom: e.getUint8(118), centerLon: e.getInt32(119, true) / 1e7, centerLat: e.getInt32(123, true) / 1e7, etag: t };
|
||||
}
|
||||
d(X, "bytesToHeader");
|
||||
function Z(o) {
|
||||
let t = { buf: new Uint8Array(o), pos: 0 }, e = x(t), r = [], n = 0;
|
||||
for (let s = 0; s < e; s++) {
|
||||
let i = x(t);
|
||||
r.push({ tileId: n + i, offset: 0, length: 0, runLength: 1 }), n += i;
|
||||
}
|
||||
for (let s = 0; s < e; s++) r[s].runLength = x(t);
|
||||
for (let s = 0; s < e; s++) r[s].length = x(t);
|
||||
for (let s = 0; s < e; s++) {
|
||||
let i = x(t);
|
||||
i === 0 && s > 0 ? r[s].offset = r[s - 1].offset + r[s - 1].length : r[s].offset = i - 1;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
d(Z, "deserializeIndex");
|
||||
var R = class R2 extends Error {
|
||||
};
|
||||
d(R, "EtagMismatch");
|
||||
var v = R;
|
||||
function V(o, t) {
|
||||
return h(this, null, function* () {
|
||||
let e = yield o.getBytes(0, 16384);
|
||||
if (new DataView(e.data).getUint16(0, true) !== 19792) throw new Error("Wrong magic number for PMTiles archive");
|
||||
let n = e.data.slice(0, Y), s = X(n, e.etag), i = e.data.slice(s.rootDirectoryOffset, s.rootDirectoryOffset + s.rootDirectoryLength), a = `${o.getKey()}|${s.etag || ""}|${s.rootDirectoryOffset}|${s.rootDirectoryLength}`, c = Z(yield t(i, s.internalCompression));
|
||||
return [s, [a, c.length, c]];
|
||||
});
|
||||
}
|
||||
d(V, "getHeaderAndRoot");
|
||||
function F(o, t, e, r, n, s) {
|
||||
return h(this, null, function* () {
|
||||
let i = yield o.getBytes(e, r, s, n.etag), a = yield t(i.data, n.internalCompression), c = Z(a);
|
||||
if (c.length === 0) throw new Error("Empty directory is invalid");
|
||||
return c;
|
||||
});
|
||||
}
|
||||
d(F, "getDirectory");
|
||||
var U = class U2 {
|
||||
constructor(t = 100, e = true, r = P) {
|
||||
this.cache = /* @__PURE__ */ new Map(), this.maxCacheEntries = t, this.counter = 1, this.decompress = r;
|
||||
}
|
||||
getHeader(t) {
|
||||
return h(this, null, function* () {
|
||||
let e = t.getKey(), r = this.cache.get(e);
|
||||
if (r) return r.lastUsed = this.counter++, r.data;
|
||||
let n = yield V(t, this.decompress);
|
||||
return n[1] && this.cache.set(n[1][0], { lastUsed: this.counter++, data: n[1][2] }), this.cache.set(e, { lastUsed: this.counter++, data: n[0] }), this.prune(), n[0];
|
||||
});
|
||||
}
|
||||
getDirectory(t, e, r, n, s) {
|
||||
return h(this, null, function* () {
|
||||
let i = `${t.getKey()}|${n.etag || ""}|${e}|${r}`, a = this.cache.get(i);
|
||||
if (a) return a.lastUsed = this.counter++, a.data;
|
||||
let c = yield F(t, this.decompress, e, r, n, s);
|
||||
return this.cache.set(i, { lastUsed: this.counter++, data: c }), this.prune(), c;
|
||||
});
|
||||
}
|
||||
prune() {
|
||||
if (this.cache.size > this.maxCacheEntries) {
|
||||
let t = 1 / 0, e;
|
||||
this.cache.forEach((r, n) => {
|
||||
r.lastUsed < t && (t = r.lastUsed, e = n);
|
||||
}), e && this.cache.delete(e);
|
||||
}
|
||||
}
|
||||
invalidate(t) {
|
||||
return h(this, null, function* () {
|
||||
this.cache.delete(t.getKey());
|
||||
});
|
||||
}
|
||||
};
|
||||
d(U, "ResolvedValueCache");
|
||||
var M = class M2 {
|
||||
constructor(t = 100, e = true, r = P) {
|
||||
this.cache = /* @__PURE__ */ new Map(), this.invalidations = /* @__PURE__ */ new Map(), this.pendingFetches = /* @__PURE__ */ new Map(), this.maxCacheEntries = t, this.counter = 1, this.decompress = r;
|
||||
}
|
||||
getHeader(t) {
|
||||
return h(this, null, function* () {
|
||||
let e = t.getKey(), r = this.cache.get(e);
|
||||
if (r) return r.lastUsed = this.counter++, yield r.data;
|
||||
let n = new Promise((s, i) => {
|
||||
V(t, this.decompress).then((a) => {
|
||||
a[1] && this.cache.set(a[1][0], { lastUsed: this.counter++, data: Promise.resolve(a[1][2]) }), s(a[0]), this.prune();
|
||||
}).catch((a) => {
|
||||
i(a);
|
||||
});
|
||||
});
|
||||
return this.cache.set(e, { lastUsed: this.counter++, data: n }), n;
|
||||
});
|
||||
}
|
||||
trackSignal(t, e, r) {
|
||||
e.refs++, r.addEventListener("abort", () => {
|
||||
--e.refs <= 0 && this.pendingFetches.get(t) === e && (e.controller.abort(), this.cache.delete(t), this.pendingFetches.delete(t));
|
||||
}, { once: true });
|
||||
}
|
||||
getDirectory(t, e, r, n, s) {
|
||||
return h(this, null, function* () {
|
||||
let i = `${t.getKey()}|${n.etag || ""}|${e}|${r}`, a = this.cache.get(i);
|
||||
if (a) {
|
||||
a.lastUsed = this.counter++;
|
||||
let m = this.pendingFetches.get(i);
|
||||
return m && this.trackSignal(i, m, s != null ? s : new AbortController().signal), yield a.data;
|
||||
}
|
||||
let c = new AbortController(), l = { controller: c, refs: 0 };
|
||||
this.trackSignal(i, l, s != null ? s : new AbortController().signal), this.pendingFetches.set(i, l);
|
||||
let u = new Promise((m, g) => {
|
||||
F(t, this.decompress, e, r, n, c.signal).then((p) => {
|
||||
this.pendingFetches.delete(i), m(p), this.prune();
|
||||
}).catch((p) => {
|
||||
g(p);
|
||||
});
|
||||
});
|
||||
return this.cache.set(i, { lastUsed: this.counter++, data: u }), u;
|
||||
});
|
||||
}
|
||||
prune() {
|
||||
if (this.cache.size >= this.maxCacheEntries) {
|
||||
let t = 1 / 0, e;
|
||||
this.cache.forEach((r, n) => {
|
||||
r.lastUsed < t && (t = r.lastUsed, e = n);
|
||||
}), e && this.cache.delete(e);
|
||||
}
|
||||
}
|
||||
invalidate(t) {
|
||||
return h(this, null, function* () {
|
||||
let e = t.getKey();
|
||||
if (this.invalidations.get(e)) return yield this.invalidations.get(e);
|
||||
this.cache.delete(t.getKey());
|
||||
let r = new Promise((n, s) => {
|
||||
this.getHeader(t).then((i) => {
|
||||
n(), this.invalidations.delete(e);
|
||||
}).catch((i) => {
|
||||
s(i);
|
||||
});
|
||||
});
|
||||
this.invalidations.set(e, r);
|
||||
});
|
||||
}
|
||||
};
|
||||
d(M, "SharedPromiseCache");
|
||||
var C = M;
|
||||
var H = class H2 {
|
||||
constructor(t, e, r) {
|
||||
typeof t == "string" ? this.source = new E(t) : this.source = t, r ? this.decompress = r : this.decompress = P, e ? this.cache = e : this.cache = new C();
|
||||
}
|
||||
getHeader() {
|
||||
return h(this, null, function* () {
|
||||
return yield this.cache.getHeader(this.source);
|
||||
});
|
||||
}
|
||||
getZxyAttempt(t, e, r, n) {
|
||||
return h(this, null, function* () {
|
||||
let s = q(t, e, r), i = yield this.cache.getHeader(this.source);
|
||||
if (n == null || n.throwIfAborted(), t < i.minZoom || t > i.maxZoom) return;
|
||||
let a = i.rootDirectoryOffset, c = i.rootDirectoryLength;
|
||||
for (let l = 0; l <= 3; l++) {
|
||||
let u = yield this.cache.getDirectory(this.source, a, c, i, n);
|
||||
n == null || n.throwIfAborted();
|
||||
let m = Q(u, s);
|
||||
if (m) {
|
||||
if (m.runLength > 0) {
|
||||
let g = yield this.source.getBytes(i.tileDataOffset + m.offset, m.length, n, i.etag);
|
||||
return { data: yield this.decompress(g.data, i.tileCompression), cacheControl: g.cacheControl, expires: g.expires };
|
||||
}
|
||||
a = i.leafDirectoryOffset + m.offset, c = m.length;
|
||||
} else return;
|
||||
}
|
||||
throw new Error("Maximum directory depth exceeded");
|
||||
});
|
||||
}
|
||||
getZxy(t, e, r, n) {
|
||||
return h(this, null, function* () {
|
||||
try {
|
||||
return yield this.getZxyAttempt(t, e, r, n);
|
||||
} catch (s) {
|
||||
if (s instanceof v) return this.cache.invalidate(this.source), yield this.getZxyAttempt(t, e, r, n);
|
||||
throw s;
|
||||
}
|
||||
});
|
||||
}
|
||||
getMetadataAttempt() {
|
||||
return h(this, null, function* () {
|
||||
let t = yield this.cache.getHeader(this.source), e = yield this.source.getBytes(t.jsonMetadataOffset, t.jsonMetadataLength, void 0, t.etag), r = yield this.decompress(e.data, t.internalCompression), n = new TextDecoder("utf-8");
|
||||
return JSON.parse(n.decode(r));
|
||||
});
|
||||
}
|
||||
getMetadata() {
|
||||
return h(this, null, function* () {
|
||||
try {
|
||||
return yield this.getMetadataAttempt();
|
||||
} catch (t) {
|
||||
if (t instanceof v) return this.cache.invalidate(this.source), yield this.getMetadataAttempt();
|
||||
throw t;
|
||||
}
|
||||
});
|
||||
}
|
||||
getTileJson(t) {
|
||||
return h(this, null, function* () {
|
||||
let e = yield this.getHeader(), r = yield this.getMetadata(), n = _(e.tileType);
|
||||
return { tilejson: "3.0.0", scheme: "xyz", tiles: [`${t}/{z}/{x}/{y}${n}`], vector_layers: r.vector_layers, attribution: r.attribution, description: r.description, name: r.name, version: r.version, bounds: [e.minLon, e.minLat, e.maxLon, e.maxLat], center: [e.centerLon, e.centerLat, e.centerZoom], minzoom: e.minZoom, maxzoom: e.maxZoom };
|
||||
});
|
||||
}
|
||||
};
|
||||
d(H, "PMTiles");
|
||||
var w = H;
|
||||
|
||||
// src/map/pmtiles.worker.ts
|
||||
var workerScope = self;
|
||||
workerScope.addProtocol("pmtiles", new B().tile);
|
||||
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 2.0 MiB |
|
After Width: | Height: | Size: 2.1 MiB |
|
After Width: | Height: | Size: 2.3 MiB |
|
After Width: | Height: | Size: 2.3 MiB |
|
After Width: | Height: | Size: 2.1 MiB |
|
After Width: | Height: | Size: 2.0 MiB |
|
After Width: | Height: | Size: 302 KiB |
|
After Width: | Height: | Size: 283 KiB |
@@ -0,0 +1,584 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* بهروزرسانی یکبارهٔ پالت `style.json` نقشهٔ آفلاین روی MinIO.
|
||||
*
|
||||
* ترتیب کار (مهم): اول نسخهٔ فعلی خوانده و «پشتیبان» میشود — هم روی دیسک
|
||||
* (style.backup.json) و هم روی MinIO (maps/style.backup.json) — و تنها پس از
|
||||
* موفقیت پشتیبان، پالت تازه نوشته و آپلود میشود.
|
||||
*
|
||||
* چرا از S3 API و نه فایل روی دیسک؟ شیءهای MinIO با فرمت داخلی xl.meta ذخیره
|
||||
* میشوند، نه JSON خام؛ پس تنها راه درست بهروزرسانی، PUT روی همان API است.
|
||||
*
|
||||
* اجرا (از پوشهٔ frontend) — هر کار با پرچم مشخص، پیشفرض هیچ تغییری نمیدهد:
|
||||
* node --experimental-strip-types scripts/update-map-palette.ts --fix-glyphs
|
||||
* node --experimental-strip-types scripts/update-map-palette.ts --palette
|
||||
* node --experimental-strip-types scripts/update-map-palette.ts --restore
|
||||
* ... [--dry-run] برای دیدن گزارش بدون نوشتن روی MinIO
|
||||
*
|
||||
* در همهٔ حالتها (جز restore) ترتیب امن رعایت میشود: خواندن و اعتبارسنجی →
|
||||
* پشتیبان روی دیسک و MinIO → تغییر → اعتبارسنجی دوباره → آپلود.
|
||||
*
|
||||
* کلیدهای MinIO از فایل .env ریشهٔ پروژه خوانده میشوند (MINIO_ROOT_USER /
|
||||
* MINIO_ROOT_PASSWORD) و در نبودشان از متغیرهای محیطی همان نامها.
|
||||
*/
|
||||
|
||||
import { createHash, createHmac } from 'node:crypto'
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* پالت تازه */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** نگاشت دستهها به رنگهای تازهٔ برند — تنها منبع حقیقت این اسکریپت */
|
||||
const PALETTE = {
|
||||
background: '#181512',
|
||||
urban: '#27221c',
|
||||
highway: '#6a5544',
|
||||
street: '#4a3a2d',
|
||||
alley: '#352c25',
|
||||
water: '#172c32',
|
||||
parks: '#20312b',
|
||||
nature: '#314238',
|
||||
mainText: '#ead9c6',
|
||||
subText: '#a99584',
|
||||
borders: '#3e362e',
|
||||
} as const
|
||||
|
||||
type Category = keyof typeof PALETTE
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* قواعد دستهبندی لایهها */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
type Layer = {
|
||||
id: string
|
||||
type: string
|
||||
'source-layer'?: string
|
||||
paint?: Record<string, unknown>
|
||||
layout?: Record<string, unknown>
|
||||
}
|
||||
type StyleDocument = {
|
||||
version?: number
|
||||
layers?: Layer[]
|
||||
sources?: Record<string, unknown>
|
||||
/** الگوی نشانی گلیفها — باید به پوشهٔ v2.0 باکت اشاره کند */
|
||||
glyphs?: string
|
||||
}
|
||||
|
||||
/** پوشهٔ فونتهای آفلاین در باکت MinIO */
|
||||
const GLYPHS_FOLDER = 'v2.0'
|
||||
/** الگوی استاندارد گلیف — جانگهدارها دستنخورده میمانند */
|
||||
const GLYPH_TEMPLATE = '{fontstack}/{range}.pbf'
|
||||
|
||||
/**
|
||||
* اصلاح مسیر گلیفها: هر شکل نشانی (خالی، نسبی، یا با پوشهٔ اشتباه) به
|
||||
* «v2.0/{fontstack}/{range}.pbf» تبدیل میشود تا با ساختار پوشههای باکت
|
||||
* بخواند. تابع خالص و idempotent است؛ اگر مسیر از قبل درست باشد چیز تغییر نمیکند.
|
||||
*/
|
||||
function fixGlyphsPath(style: StyleDocument): { from: string; to: string } | null {
|
||||
const current = (style.glyphs ?? '').trim()
|
||||
const marker = current.indexOf('{fontstack}')
|
||||
const next = `${GLYPHS_FOLDER}/${marker >= 0 ? current.slice(marker) : GLYPH_TEMPLATE}`
|
||||
if (next === current) return null
|
||||
style.glyphs = next
|
||||
return { from: current || '(خالی)', to: next }
|
||||
}
|
||||
|
||||
/** آیا مقدار text-field به یک فیلد «نام» اشاره میکند؟ (name، name_en، name:latin و…) */
|
||||
const NAME_REFERENCE = /name(:[a-z-]+)?/i
|
||||
|
||||
/**
|
||||
* فونتهای محلی با پوشش فارسی — با اجرای «--audit-fonts» قابل بازبینی است.
|
||||
* تنها پوشههای Noto Sans در باکت گلیف عربی/فارسی دارند؛ Metropolis و بقیه
|
||||
* فقط لاتیناند.
|
||||
*/
|
||||
const PERSIAN_CAPABLE_FONTS = ['Noto Sans Regular', 'Noto Sans Italic', 'Noto Sans Bold']
|
||||
|
||||
/**
|
||||
* بازگردانی متن برچسبها به قالب دوزبانهٔ اصلی، بهتفکیک لایه.
|
||||
* (لاتین خط اول، فارسی خط دوم — یا کنار هم برای نام راهها)
|
||||
*/
|
||||
const TEXT_FIELD_RESTORE: Record<string, string> = {
|
||||
water_name: '{name:latin}\n{name:nonlatin}',
|
||||
place_other: '{name:latin}\n{name:nonlatin}',
|
||||
place_suburb: '{name:latin}\n{name:nonlatin}',
|
||||
place_village: '{name:latin}\n{name:nonlatin}',
|
||||
place_town: '{name:latin}\n{name:nonlatin}',
|
||||
place_city: '{name:latin}\n{name:nonlatin}',
|
||||
place_city_large: '{name:latin}\n{name:nonlatin}',
|
||||
place_state: '{name:latin}\n{name:nonlatin}',
|
||||
highway_name_other: '{name:latin} {name:nonlatin}',
|
||||
place_country_other: '{name:latin}',
|
||||
place_country_minor: '{name:latin}',
|
||||
place_country_major: '{name:latin}',
|
||||
}
|
||||
|
||||
/** قالب پیشفرض برای هر لایهٔ برچسبِ دیگری که بعداً اضافه شود */
|
||||
const DEFAULT_BILINGUAL_FIELD = '{name:latin}\n{name:nonlatin}'
|
||||
|
||||
function referencesName(value: unknown): boolean {
|
||||
if (typeof value === 'string') return NAME_REFERENCE.test(value)
|
||||
if (Array.isArray(value)) return value.some(referencesName)
|
||||
if (value && typeof value === 'object') return Object.values(value).some(referencesName)
|
||||
return false
|
||||
}
|
||||
|
||||
/** فونت فارسی متناسب با پشتهٔ همان لایه — ایتالیک بماند ایتالیک */
|
||||
function persianFontFor(stack: string[]): string {
|
||||
const local = stack.find((font) => PERSIAN_CAPABLE_FONTS.includes(font))
|
||||
if (local) return local
|
||||
return stack.some((font) => /italic/i.test(font)) ? 'Noto Sans Italic' : 'Noto Sans Regular'
|
||||
}
|
||||
|
||||
type LabelChange = { id: string; field?: { from: string; to: string }; font: { from: string; to: string } }
|
||||
|
||||
/**
|
||||
* آمادهسازی برچسبها برای فارسی:
|
||||
* ۱) متن به قالب دوزبانهٔ اصلی برمیگردد (لاتین + nonlatin که برای دادهٔ ایران فارسی است).
|
||||
* ۲) پشتهٔ فونت بازچینی میشود تا فونت دارای گلیف فارسی (Noto Sans محلی) اول بیفتد؛
|
||||
* چون مپلیبر برای هر پشته فقط یک فایل گلیف میگیرد، همان فونت اول باید هر دو خط
|
||||
* را پوشش دهد و Noto Sans لاتین را هم دارد.
|
||||
*/
|
||||
function fixLabels(style: StyleDocument): { changed: LabelChange[]; skipped: string[] } {
|
||||
const changed: LabelChange[] = []
|
||||
const skipped: string[] = []
|
||||
|
||||
for (const layer of style.layers ?? []) {
|
||||
const layout = layer.layout
|
||||
if (layer.type !== 'symbol' || !layout) continue
|
||||
|
||||
const stack = Array.isArray(layout['text-font']) ? (layout['text-font'] as unknown[]).map(String) : []
|
||||
if (!stack.length) continue
|
||||
|
||||
const persianFont = persianFontFor(stack)
|
||||
const restacked = [persianFont, ...stack.filter((font) => font !== persianFont)]
|
||||
const fontChange = { from: stack.join(', '), to: restacked.join(', ') }
|
||||
|
||||
if (!('text-field' in layout)) {
|
||||
// لایهٔ برچسب بدون فیلد نام (مثل شمارهٔ راه) — فقط پشتهٔ فونت اصلاح میشود
|
||||
layout['text-font'] = restacked
|
||||
changed.push({ id: layer.id, font: fontChange })
|
||||
continue
|
||||
}
|
||||
|
||||
if (!referencesName(layout['text-field'])) {
|
||||
layout['text-font'] = restacked
|
||||
skipped.push(layer.id)
|
||||
continue
|
||||
}
|
||||
|
||||
const from = JSON.stringify(layout['text-field']).slice(0, 48)
|
||||
const to = TEXT_FIELD_RESTORE[layer.id] ?? DEFAULT_BILINGUAL_FIELD
|
||||
layout['text-field'] = to
|
||||
layout['text-font'] = restacked
|
||||
changed.push({ id: layer.id, field: { from, to }, font: fontChange })
|
||||
}
|
||||
|
||||
return { changed, skipped }
|
||||
}
|
||||
|
||||
/**
|
||||
* بررسی فونتها: هر فونتی که در text-font لایههای برچسب استفاده شده باید در
|
||||
* پوشهٔ v2.0 باکت موجود باشد — هیچ نشانی بیرونی و هیچ فونت غایبی مجاز نیست.
|
||||
*/
|
||||
async function verifyFonts(style: StyleDocument): Promise<void> {
|
||||
const fonts = new Set<string>()
|
||||
for (const layer of style.layers ?? []) {
|
||||
if (layer.type !== 'symbol') continue
|
||||
const stack = layer.layout?.['text-font']
|
||||
if (Array.isArray(stack)) for (const font of stack) if (typeof font === 'string') fonts.add(font)
|
||||
}
|
||||
|
||||
if (!fonts.size) {
|
||||
console.log('• فونتی در لایههای برچسب پیدا نشد')
|
||||
return
|
||||
}
|
||||
|
||||
console.log(`\nبررسی ${fonts.size} فونت در پوشهٔ ${GLYPHS_FOLDER}:`)
|
||||
const missing: string[] = []
|
||||
for (const font of [...fonts].sort()) {
|
||||
const url = new URL(`/maps/${GLYPHS_FOLDER}/${encodeURIComponent(font)}/0-255.pbf`, ENDPOINT)
|
||||
const ok = (await fetch(url, { method: 'HEAD' })).ok
|
||||
if (!ok) missing.push(font)
|
||||
console.log(` ${ok ? '✓' : '✗'} ${font}`)
|
||||
}
|
||||
|
||||
console.log(
|
||||
missing.length
|
||||
? `✗ فونتهای ناموجود در ${GLYPHS_FOLDER}: ${missing.join(', ')}`
|
||||
: `✓ همهٔ فونتها در ${GLYPHS_FOLDER} باکت موجودند`,
|
||||
)
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* بررسی پوشش فونتهای محلی (کدام فونت فارسی را رندر میکند؟) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** بازههای کلیدی گلیف: لاتین پایه، عربی/فارسی، فرمهای نمایشی عربی */
|
||||
const COVERAGE_RANGES = [
|
||||
{ label: 'لاتین', range: '0-255' },
|
||||
{ label: 'فارسی', range: '1536-1791' },
|
||||
{ label: 'فرم فارسی', range: '65024-65279' },
|
||||
] as const
|
||||
|
||||
/** فهرست پوشههای فونت داخل v2.0 باکت */
|
||||
async function listFontFolders(): Promise<string[]> {
|
||||
const response = await fetch(
|
||||
new URL(`/maps/?list-type=2&prefix=${GLYPHS_FOLDER}/&delimiter=/&max-keys=1000`, ENDPOINT),
|
||||
)
|
||||
const xml = await response.text()
|
||||
const pattern = new RegExp(`<Prefix>${GLYPHS_FOLDER}/([^<]+)/</Prefix>`, 'g')
|
||||
return [...xml.matchAll(pattern)].map((match) => match[1])
|
||||
}
|
||||
|
||||
/** وضعیت یک بازهٔ گلیف برای یک فونت: «نیست» / «خالی» / حجم واقعی */
|
||||
async function rangeCoverage(font: string, range: string): Promise<string> {
|
||||
const url = new URL(`/maps/${GLYPHS_FOLDER}/${encodeURIComponent(font)}/${range}.pbf`, ENDPOINT)
|
||||
const response = await fetch(url, { method: 'HEAD' })
|
||||
if (!response.ok) return 'نیست'
|
||||
const bytes = Number(response.headers.get('content-length') ?? 0)
|
||||
// بازهٔ بدون گلیف فقط سرصفحهٔ پروتوباف است (چند ده بایت)
|
||||
return bytes > 2000 ? `${Math.round(bytes / 1024)}KB` : 'خالی'
|
||||
}
|
||||
|
||||
/** گزارش پوشش خطها برای همهٔ فونتهای باکت — ورودی تصمیم انتخاب فونت برچسبها */
|
||||
async function auditFonts(): Promise<void> {
|
||||
const fonts = await listFontFolders()
|
||||
console.log(`${fonts.length} پوشهٔ فونت در ${GLYPHS_FOLDER}:\n`)
|
||||
for (const font of fonts) {
|
||||
const cells: string[] = []
|
||||
for (const { label, range } of COVERAGE_RANGES) cells.push(`${label}=${await rangeCoverage(font, range)}`)
|
||||
console.log(` ${font.padEnd(26)} ${cells.join(' ')}`)
|
||||
}
|
||||
console.log('\nفونتی که «فارسی» و «فرم فارسی» آن خالی/نیست نباشد، برچسب فارسی را رندر میکند.')
|
||||
}
|
||||
|
||||
/**
|
||||
* اعتبارسنجی ساختار سبک — پیش و پس از تغییر اجرا میشود تا مطمئن شویم سند
|
||||
* سالم است و اسکیمای سبک (نسخه، لایهها، منابع) نشکسته است.
|
||||
*/
|
||||
function validateStyle(style: StyleDocument, label: string): void {
|
||||
const problems: string[] = []
|
||||
if (style.version !== 8) problems.push(`version باید ۸ باشد (مقدار فعلی: ${String(style.version)})`)
|
||||
if (!Array.isArray(style.layers) || style.layers.length === 0) problems.push('layers باید آرایهٔ ناتهی باشد')
|
||||
else {
|
||||
const broken = style.layers.filter((layer) => !layer || typeof layer.id !== 'string' || typeof layer.type !== 'string')
|
||||
if (broken.length) problems.push(`${broken.length} لایه بدون id/type`)
|
||||
}
|
||||
if (!style.sources || typeof style.sources !== 'object' || Array.isArray(style.sources)) {
|
||||
problems.push('sources باید یک شیء باشد')
|
||||
}
|
||||
|
||||
console.log(
|
||||
problems.length
|
||||
? `✗ اعتبارسنجی ${label}: ${problems.join(' | ')}`
|
||||
: `✓ اعتبارسنجی ${label}: ساختار سالم است (${style.layers?.length ?? 0} لایه، ${Object.keys(style.sources ?? {}).length} منبع)`,
|
||||
)
|
||||
if (problems.length) throw new Error(`ساختار سبک نامعتبر است (${label})`)
|
||||
}
|
||||
|
||||
type Rule = {
|
||||
category: Category
|
||||
/** با این الگو روی شناسهٔ لایه تطبیق داده میشود */
|
||||
test: RegExp
|
||||
/** کدام ویژگیهای paint رنگآمیزی شوند */
|
||||
properties: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* جدول قواعد — به ترتیب بررسی میشود و نخستین تطبیق برنده است.
|
||||
* رنگهای داخل عبارتها (interpolate/match) هم بازنویسی میشوند تا پالت
|
||||
* یکدست بماند.
|
||||
*/
|
||||
const RULES: Rule[] = [
|
||||
{ category: 'background', test: /^background$/, properties: ['background-color'] },
|
||||
|
||||
// آب: خود لایههای آب و راههای آبی (برچسبها قاعدهٔ جدا دارند)
|
||||
{ category: 'water', test: /^(water|waterway)(_|$)/, properties: ['fill-color', 'line-color'] },
|
||||
|
||||
// پارکها پیش از طبیعت بررسی میشوند تا چمن/پارک زیر «طبیعت» نرود
|
||||
{ category: 'parks', test: /^(park|landcover_grass|landuse_(park|cemetery|pitch|grass))/, properties: ['fill-color', 'line-color'] },
|
||||
|
||||
// طبیعت: پوشش زمینِ جنگلی/علفزارِ بیرون از شهر
|
||||
{ category: 'nature', test: /^landcover_/, properties: ['fill-color', 'line-color'] },
|
||||
|
||||
// کاربری شهری و ساختمانها
|
||||
{ category: 'urban', test: /^landuse_/, properties: ['fill-color', 'line-color'] },
|
||||
{ category: 'urban', test: /^building/, properties: ['fill-color'] },
|
||||
|
||||
// سه ردهٔ راه — بزرگراه، خیابان، کوچه/ریل/باند فرودگاه
|
||||
{ category: 'highway', test: /^highway_motorway/, properties: ['line-color', 'fill-color'] },
|
||||
{ category: 'street', test: /^(highway_(major|minor)|road_)/, properties: ['line-color', 'fill-color'] },
|
||||
{ category: 'alley', test: /^(highway_(path|track)|railway|aeroway)/, properties: ['line-color', 'fill-color'] },
|
||||
|
||||
{ category: 'borders', test: /^boundary/, properties: ['line-color', 'fill-color'] },
|
||||
|
||||
// برچسبهای اصلی: شهر/شهرک و نام بزرگراهها
|
||||
{ category: 'mainText', test: /^(place_(city|town)|highway_name_motorway)/, properties: ['text-color'] },
|
||||
|
||||
// بقیهٔ برچسبها (روستا، محله، نام خیابان، نام آب، نقاط) — متن فرعی
|
||||
{ category: 'subText', test: /(_name|^place_|_label)/, properties: ['text-color'] },
|
||||
]
|
||||
|
||||
/** ویژگیهای فرعی که همیشه با رنگ پسزمینه هماهنگ میشوند تا خوانایی بماند */
|
||||
const HALO_PROPERTIES = ['text-halo-color', 'icon-halo-color']
|
||||
/** ویژگیهای آیکون برچسبها که با متن همرنگ میشوند */
|
||||
const ICON_PROPERTIES = ['icon-color']
|
||||
|
||||
const COLOR_PATTERN = /^(#|rgb|hsl)/i
|
||||
const isColor = (value: unknown): value is string => typeof value === 'string' && COLOR_PATTERN.test(value.trim())
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* بازنویسی رنگها (توابع خالص) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** هر رشتهٔ رنگی داخل یک مقدار paint — حتی داخل عبارتها — را با رنگ تازه عوض میکند */
|
||||
function paintColor(value: unknown, color: string, stats: { replaced: number; seen: Set<string> }): unknown {
|
||||
if (isColor(value)) {
|
||||
stats.seen.add(value.trim())
|
||||
stats.replaced += 1
|
||||
return color
|
||||
}
|
||||
if (Array.isArray(value)) return value.map((item) => paintColor(item, color, stats))
|
||||
if (value && typeof value === 'object') {
|
||||
const result: Record<string, unknown> = {}
|
||||
for (const [key, inner] of Object.entries(value)) result[key] = paintColor(inner, color, stats)
|
||||
return result
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
type LayerReport = { id: string; category: Category | null; replaced: number; colors: string[] }
|
||||
|
||||
/** یک لایه را بر پایهٔ قواعد رنگآمیزی میکند و گزارش تغییرها را برمیگرداند */
|
||||
function recolorLayer(layer: Layer): LayerReport {
|
||||
const rule = RULES.find((candidate) => candidate.test.test(layer.id))
|
||||
const stats = { replaced: 0, seen: new Set<string>() }
|
||||
|
||||
if (!layer.paint) return { id: layer.id, category: rule?.category ?? null, replaced: 0, colors: [] }
|
||||
|
||||
if (rule) {
|
||||
for (const property of rule.properties) {
|
||||
if (!(property in layer.paint)) continue
|
||||
layer.paint[property] = paintColor(layer.paint[property], PALETTE[rule.category], stats)
|
||||
}
|
||||
}
|
||||
|
||||
// لایههای برچسب: هاله و آیکونها با پالت هماهنگ میشوند
|
||||
if (layer.type === 'symbol') {
|
||||
const textColor = rule?.category === 'mainText' || rule?.category === 'subText'
|
||||
? PALETTE[rule.category]
|
||||
: PALETTE.subText
|
||||
if (rule?.category !== 'mainText' && rule?.category !== 'subText' && 'text-color' in layer.paint) {
|
||||
layer.paint['text-color'] = paintColor(layer.paint['text-color'], textColor, stats)
|
||||
}
|
||||
for (const property of [...HALO_PROPERTIES, ...ICON_PROPERTIES]) {
|
||||
if (!(property in layer.paint)) continue
|
||||
const target = property === 'icon-color' ? textColor : PALETTE.background
|
||||
layer.paint[property] = paintColor(layer.paint[property], target, stats)
|
||||
}
|
||||
}
|
||||
|
||||
// لبهٔ ساختمانها با رنگ مرزها همخانواده میشود
|
||||
if (layer.paint['fill-outline-color'] && /^building/.test(layer.id)) {
|
||||
layer.paint['fill-outline-color'] = paintColor(layer.paint['fill-outline-color'], PALETTE.borders, stats)
|
||||
}
|
||||
|
||||
return { id: layer.id, category: rule?.category ?? null, replaced: stats.replaced, colors: [...stats.seen] }
|
||||
}
|
||||
|
||||
/** کل سند سبک را بازنویسی میکند (بدون دستزدن به ساختار و ویژگیهای غیررنگی) */
|
||||
function recolorStyle(style: StyleDocument): LayerReport[] {
|
||||
const layers = style.layers ?? []
|
||||
return layers.map(recolorLayer)
|
||||
}
|
||||
|
||||
/** گزارش فشردهٔ تغییرهای پالت — بهتفکیک دسته و لایههای دستنخورده */
|
||||
function reportPalette(reports: LayerReport[]): void {
|
||||
const byCategory = new Map<string, number>()
|
||||
for (const report of reports) {
|
||||
if (!report.replaced) continue
|
||||
const category = report.category ?? 'بدوندسته'
|
||||
byCategory.set(category, (byCategory.get(category) ?? 0) + report.replaced)
|
||||
}
|
||||
|
||||
console.log('\nگزارش تغییرها:')
|
||||
for (const [category, count] of [...byCategory].sort((a, b) => b[1] - a[1])) {
|
||||
console.log(` ${category.padEnd(12)} ${String(count).padStart(3)} مقدار رنگ`)
|
||||
}
|
||||
|
||||
const untouched = reports.filter((report) => !report.replaced)
|
||||
if (untouched.length) {
|
||||
console.log(`\nلایههای بدون تغییر (${untouched.length}): ${untouched.map((report) => report.id).join(', ')}`)
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* دسترسی به MinIO (S3 Signature V4 — بدون وابستگی تازه) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
type Credentials = { user: string; secret: string }
|
||||
|
||||
async function readCredentials(): Promise<Credentials> {
|
||||
const envPath = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '.env')
|
||||
const fromFile: Record<string, string> = {}
|
||||
try {
|
||||
for (const line of (await readFile(envPath, 'utf8')).split(/\r?\n/)) {
|
||||
const match = line.match(/^([A-Z0-9_]+)=(.*)$/)
|
||||
if (match) fromFile[match[1]] = match[2].trim()
|
||||
}
|
||||
} catch {
|
||||
/* فایل .env اختیاری است — متغیرهای محیطی جایگزین میشوند */
|
||||
}
|
||||
|
||||
const user = process.env.MINIO_ROOT_USER || fromFile.MINIO_ROOT_USER || 'aramesh'
|
||||
const secret = process.env.MINIO_ROOT_PASSWORD || fromFile.MINIO_ROOT_PASSWORD
|
||||
if (!secret) throw new Error('MINIO_ROOT_PASSWORD پیدا نشد (نه در .env و نه در متغیرهای محیطی)')
|
||||
return { user, secret }
|
||||
}
|
||||
|
||||
const sha256 = (value: string | Buffer) => createHash('sha256').update(value).digest('hex')
|
||||
const hmac = (key: string | Buffer, value: string) => createHmac('sha256', key).update(value).digest()
|
||||
const hmacHex = (key: Buffer, value: string) => createHmac('sha256', key).update(value).digest('hex')
|
||||
|
||||
/** PUT امضاشدهٔ S3 — همان چیزی که کنسول MinIO و پنل ادمین هم انجام میدهند */
|
||||
async function putObject(endpoint: string, objectPath: string, body: string, credentials: Credentials): Promise<void> {
|
||||
const url = new URL(objectPath, endpoint)
|
||||
const amzDate = new Date().toISOString().replace(/[:-]|\.\d{3}/g, '')
|
||||
const dateStamp = amzDate.slice(0, 8)
|
||||
const payloadHash = sha256(body)
|
||||
const canonicalHeaders = `host:${url.host}\nx-amz-content-sha256:${payloadHash}\nx-amz-date:${amzDate}\n`
|
||||
const signedHeaders = 'host;x-amz-content-sha256;x-amz-date'
|
||||
const canonicalRequest = ['PUT', url.pathname, '', canonicalHeaders, signedHeaders, payloadHash].join('\n')
|
||||
const scope = `${dateStamp}/us-east-1/s3/aws4_request`
|
||||
const stringToSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256(canonicalRequest)].join('\n')
|
||||
const signingKey = hmac(hmac(hmac(hmac(`AWS4${credentials.secret}`, dateStamp), 'us-east-1'), 's3'), 'aws4_request')
|
||||
const authorization =
|
||||
`AWS4-HMAC-SHA256 Credential=${credentials.user}/${scope}, ` +
|
||||
`SignedHeaders=${signedHeaders}, Signature=${hmacHex(signingKey, stringToSign)}`
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
Authorization: authorization,
|
||||
'x-amz-content-sha256': payloadHash,
|
||||
'x-amz-date': amzDate,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body,
|
||||
})
|
||||
if (!response.ok) throw new Error(`PUT ${objectPath} → HTTP ${response.status} ${await response.text()}`)
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* اجرا */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const ENDPOINT = process.env.MAP_ENDPOINT ?? 'http://localhost:19000'
|
||||
const STYLE_PATH = '/maps/style.json'
|
||||
const BACKUP_PATH = '/maps/style.backup.json'
|
||||
const OUTPUT_DIR = join(dirname(fileURLToPath(import.meta.url)), 'map-palette')
|
||||
const LOCAL_BACKUP = join(OUTPUT_DIR, 'style.backup.json')
|
||||
|
||||
/** بازگردانی: پشتیبان دقیقاً بهجای style.json نوشته میشود */
|
||||
async function restore(): Promise<void> {
|
||||
const backup = await readFile(LOCAL_BACKUP, 'utf8')
|
||||
validateStyle(JSON.parse(backup) as StyleDocument, 'نسخهٔ پشتیبان')
|
||||
await putObject(ENDPOINT, STYLE_PATH, backup, await readCredentials())
|
||||
|
||||
const restored = await (await fetch(new URL(STYLE_PATH, ENDPOINT))).text()
|
||||
console.log(
|
||||
restored === backup
|
||||
? '✓ style.json دقیقاً به نسخهٔ پشتیبان برگشت'
|
||||
: '✗ محتوای بازگرداندهشده با پشتیبان یکسان نیست — دستی بررسی کنید',
|
||||
)
|
||||
}
|
||||
|
||||
const ACTIONS = ['--audit-fonts', '--fix-labels', '--fix-glyphs', '--palette', '--restore'] as const
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const dryRun = process.argv.includes('--dry-run')
|
||||
const action = ACTIONS.find((flag) => process.argv.includes(flag))
|
||||
|
||||
// پیشفرض امن: بدون پرچم هیچ نوشتنی انجام نمیشود
|
||||
if (!action) {
|
||||
console.log(
|
||||
'کاری انجام نشد — یکی از پرچمها را بدهید:\n' +
|
||||
' --audit-fonts گزارش پوشش خطهای هر فونت در v2.0 (فقط خواندن)\n' +
|
||||
' --fix-labels برچسبهای دوزبانه + پشتهٔ فونت محلی\n' +
|
||||
' --fix-glyphs اصلاح مسیر گلیفها به v2.0\n' +
|
||||
' --palette اعمال پالت تازه\n' +
|
||||
' --restore بازگردانی از پشتیبان\n' +
|
||||
' [--dry-run] فقط گزارش، بدون نوشتن روی MinIO',
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (action === '--audit-fonts') {
|
||||
await auditFonts()
|
||||
return
|
||||
}
|
||||
|
||||
if (action === '--restore') {
|
||||
await restore()
|
||||
return
|
||||
}
|
||||
|
||||
// ۱) خواندن سبک فعلی
|
||||
const response = await fetch(new URL(STYLE_PATH, ENDPOINT))
|
||||
if (!response.ok) throw new Error(`GET ${STYLE_PATH} → HTTP ${response.status}`)
|
||||
const original = await response.text()
|
||||
const style = JSON.parse(original) as StyleDocument
|
||||
console.log(`سبک فعلی خوانده شد — ${(original.length / 1024).toFixed(1)} کیلوبایت`)
|
||||
validateStyle(style, 'نسخهٔ فعلی')
|
||||
|
||||
// ۲) پشتیبانگیری، پیش از هر تغییر
|
||||
await mkdir(OUTPUT_DIR, { recursive: true })
|
||||
await writeFile(LOCAL_BACKUP, original, 'utf8')
|
||||
console.log(`پشتیبان روی دیسک: scripts/map-palette/style.backup.json`)
|
||||
if (!dryRun) {
|
||||
await putObject(ENDPOINT, BACKUP_PATH, original, await readCredentials())
|
||||
console.log(`پشتیبان روی MinIO: ${BACKUP_PATH}`)
|
||||
}
|
||||
|
||||
// ۳) تغییر درخواستی، سپس اعتبارسنجی دوباره
|
||||
if (action === '--fix-labels') {
|
||||
const { changed, skipped } = fixLabels(style)
|
||||
console.log(`\nلایههای برچسب اصلاحشده (${changed.length}):`)
|
||||
for (const layer of changed) {
|
||||
if (layer.field) console.log(` ${layer.id}\n متن: ${layer.field.from} → ${JSON.stringify(layer.field.to)}`)
|
||||
console.log(` فونت: ${layer.font.from} → ${layer.font.to}`)
|
||||
}
|
||||
if (skipped.length) {
|
||||
console.log(`\nلایههای بدون فیلد نام (فقط فونت اصلاح شد): ${skipped.join(', ')}`)
|
||||
}
|
||||
await verifyFonts(style)
|
||||
} else if (action === '--fix-glyphs') {
|
||||
const change = fixGlyphsPath(style)
|
||||
console.log(
|
||||
change ? `\nمسیر گلیفها: ${change.from} → ${change.to}` : '\nمسیر گلیفها از قبل به v2.0 اشاره میکند',
|
||||
)
|
||||
await verifyFonts(style)
|
||||
} else {
|
||||
reportPalette(recolorStyle(style))
|
||||
}
|
||||
validateStyle(style, 'نسخهٔ تازه')
|
||||
|
||||
// ۴) نوشتن و آپلود نسخهٔ تازه
|
||||
const updated = JSON.stringify(style, null, 2)
|
||||
await writeFile(join(OUTPUT_DIR, 'style.json'), updated, 'utf8')
|
||||
if (dryRun) {
|
||||
console.log('\nحالت آزمایشی — هیچ چیزی روی MinIO نوشته نشد.')
|
||||
return
|
||||
}
|
||||
|
||||
await putObject(ENDPOINT, STYLE_PATH, updated, await readCredentials())
|
||||
console.log(`\nسبک تازه روی MinIO نوشته شد: ${STYLE_PATH}`)
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
console.error('\nخطا:', error instanceof Error ? error.message : error)
|
||||
process.exitCode = 1
|
||||
})
|
||||
@@ -5,6 +5,8 @@ import { Preloader } from './components/Preloader';
|
||||
import { Header } from './components/Header';
|
||||
import { Footer } from './components/Footer';
|
||||
import { FloatingContact } from './components/FloatingContact';
|
||||
// چتبات موقتاً خاموش است — برای روشنکردن، این ایمپورت و خط رندر پایین را برگردانید
|
||||
// import { ChatWidget } from './components/ChatWidget';
|
||||
import { Home } from './pages/Home';
|
||||
import { About } from './pages/About';
|
||||
import { ServicesPage } from './pages/ServicesPage';
|
||||
@@ -15,7 +17,36 @@ import { Blog } from './pages/Blog';
|
||||
import { ArticleDetail } from './pages/ArticleDetail';
|
||||
import { FaqPage } from './pages/FaqPage';
|
||||
import { ContactPage } from './pages/ContactPage';
|
||||
import { SiteProvider, useSiteData } from './api';
|
||||
import { SiteProvider, useSiteData, useSite } from './api';
|
||||
import { applySeo, seoKeyForPath } from './seo';
|
||||
import { AdminProvider, useAdmin } from './admin/AdminContext';
|
||||
import { AdminBar } from './admin/AdminBar';
|
||||
import { AdminLoginPage } from './admin/AdminLoginPage';
|
||||
import { ArticleWritePage } from './admin/ArticleWritePage';
|
||||
import { ProjectWritePage } from './admin/ProjectWritePage';
|
||||
import { LangProvider, useLang } from './i18n/lang';
|
||||
|
||||
// مسیرهای عمومی یک بار تعریف میشوند و دو بار سرو میشوند: ریشه فارسی و /en انگلیسی
|
||||
const PUBLIC_ROUTES: { path: string; element: React.ReactElement }[] = [
|
||||
{ path: '/', element: <Home /> },
|
||||
{ path: '/about', element: <About /> },
|
||||
{ path: '/services', element: <ServicesPage /> },
|
||||
{ path: '/projects', element: <Projects /> },
|
||||
{ path: '/projects/:slug', element: <ProjectDetail /> },
|
||||
{ path: '/investment', element: <Investment /> },
|
||||
{ path: '/blog', element: <Blog /> },
|
||||
{ path: '/blog/:slug', element: <ArticleDetail /> },
|
||||
{ path: '/faq', element: <FaqPage /> },
|
||||
{ path: '/contact', element: <ContactPage /> },
|
||||
];
|
||||
|
||||
// فرزند مستقیم <Routes> باید <Route> باشد — آرایههای Route بهجای کامپوننت واسط
|
||||
const FA_ROUTES = PUBLIC_ROUTES.map(({ path, element }) => (
|
||||
<Route key={path} path={path} element={element} />
|
||||
));
|
||||
const EN_ROUTES = PUBLIC_ROUTES.map(({ path, element }) => (
|
||||
<Route key={`en-${path}`} path={path === '/' ? '/en' : `/en${path}`} element={element} />
|
||||
));
|
||||
|
||||
function ScrollToTop() {
|
||||
const { pathname } = useLocation();
|
||||
@@ -35,67 +66,104 @@ function AnimatedRoutes() {
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.28, ease: [0.23, 1, 0.32, 1] }}>
|
||||
|
||||
|
||||
<Routes location={location}>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/about" element={<About />} />
|
||||
<Route path="/services" element={<ServicesPage />} />
|
||||
<Route path="/projects" element={<Projects />} />
|
||||
<Route path="/projects/:slug" element={<ProjectDetail />} />
|
||||
<Route path="/investment" element={<Investment />} />
|
||||
<Route path="/blog" element={<Blog />} />
|
||||
<Route path="/blog/:slug" element={<ArticleDetail />} />
|
||||
<Route path="/faq" element={<FaqPage />} />
|
||||
<Route path="/contact" element={<ContactPage />} />
|
||||
<Route path="/admin/login" element={<AdminLoginPage />} />
|
||||
<Route path="/admin/write" element={<ArticleWritePage />} />
|
||||
<Route path="/admin/write/:id" element={<ArticleWritePage />} />
|
||||
<Route path="/admin/projects/new" element={<ProjectWritePage />} />
|
||||
<Route path="/admin/projects/:id" element={<ProjectWritePage />} />
|
||||
{FA_ROUTES}
|
||||
<Route path="*" element={<Home />} />
|
||||
{EN_ROUTES}
|
||||
</Routes>
|
||||
</motion.main>
|
||||
</AnimatePresence>);
|
||||
|
||||
}
|
||||
|
||||
function AppShell() {
|
||||
const { data, error, reload } = useSiteData();
|
||||
function AppChrome() {
|
||||
const { pathname } = useLocation();
|
||||
const { isAuthenticated } = useAdmin();
|
||||
const data = useSite();
|
||||
const { lang } = useLang();
|
||||
const isAdminPage = pathname.startsWith('/admin');
|
||||
|
||||
// عنوان و توضیح متای هر صفحه از دیتابیس (سئو) — جز صفحههای جزئیات که خودشان ست میکنند
|
||||
useEffect(() => {
|
||||
if (isAdminPage) return;
|
||||
const key = seoKeyForPath(pathname);
|
||||
if (!key) return;
|
||||
const meta = data.seo_meta?.find((s) => s.page_key === key);
|
||||
const brand = data.brand.name;
|
||||
const navLabel = data.nav.find((n) => n.href === `/${key}`)?.label;
|
||||
// alternate انگلیسی فقط وقتی اعلام میشود که متای انگلیسی واقعاً ثبت شده باشد
|
||||
const hasEn = !!(meta && ((meta.title_en ?? '').trim() || (meta.description_en ?? '').trim()));
|
||||
applySeo({
|
||||
title: meta?.title || (key === 'home' ? brand : navLabel ? `${navLabel} | ${brand}` : brand),
|
||||
description: meta?.description ?? '',
|
||||
path: pathname,
|
||||
lang,
|
||||
hasEn,
|
||||
});
|
||||
}, [pathname, data, isAdminPage, lang]);
|
||||
|
||||
return (
|
||||
<div dir="rtl" lang="fa" className="min-h-screen w-full overflow-x-hidden bg-ink font-pinar text-ivory">
|
||||
<>
|
||||
{!isAdminPage && <Header />}
|
||||
<AnimatedRoutes />
|
||||
{!isAdminPage && <Footer />}
|
||||
{!isAdminPage && <FloatingContact />}
|
||||
{/* چتبات موقتاً خاموش است — برای روشنکردن، این خط را از حالت کامنت خارج کنید */}
|
||||
{/* {!isAdminPage && <ChatWidget />} */}
|
||||
{isAuthenticated && !isAdminPage && <AdminBar />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AppShell() {
|
||||
const { data, error, reload } = useSiteData();
|
||||
const { t, dir, lang } = useLang();
|
||||
|
||||
// overflow-x-clip جای overflow-x-hidden: اسکرولافزار نمیسازد، پس position: sticky
|
||||
// (فهرست مطالب مقاله) به صفحه میچسبد و با محتوا پایین نمیرود؛ برش افقی هم حفظ میشود.
|
||||
return (
|
||||
<div dir={dir} lang={lang} className="min-h-screen w-full overflow-x-clip bg-ink font-pinar text-ivory">
|
||||
<Preloader />
|
||||
{error ? (
|
||||
<div className="flex min-h-screen flex-col items-center justify-center px-6 text-center">
|
||||
<h1 className="text-2xl font-bold text-ivory">اتصال به سرور برقرار نشد</h1>
|
||||
<h1 className="text-2xl font-bold text-ivory">{t('errorTitle')}</h1>
|
||||
<p className="mt-4 max-w-md text-sm font-light leading-8 text-ivory/70">
|
||||
محتوای سایت از سرور بارگذاری میشود؛ لطفاً اتصال اینترنت یا وضعیت سرور را بررسی کنید.
|
||||
{t('errorText')}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={reload}
|
||||
className="mt-8 bg-copper px-10 py-3 text-sm font-bold text-char transition-transform duration-300 hover:scale-105"
|
||||
>
|
||||
تلاش دوباره
|
||||
{t('retry')}
|
||||
</button>
|
||||
</div>
|
||||
) : data ? (
|
||||
<BrowserRouter>
|
||||
<>
|
||||
<ScrollToTop />
|
||||
<Header />
|
||||
<AnimatedRoutes />
|
||||
<Footer />
|
||||
<FloatingContact />
|
||||
</BrowserRouter>
|
||||
<AppChrome />
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
useEffect(() => {
|
||||
document.documentElement.setAttribute('dir', 'rtl');
|
||||
document.documentElement.setAttribute('lang', 'fa');
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SiteProvider>
|
||||
<AppShell />
|
||||
<AdminProvider>
|
||||
<BrowserRouter>
|
||||
<LangProvider>
|
||||
<AppShell />
|
||||
</LangProvider>
|
||||
</BrowserRouter>
|
||||
</AdminProvider>
|
||||
</SiteProvider>
|
||||
);
|
||||
}
|
||||
|
||||