chore(init): initialize automated dashboard & wiki git repository for ehsan

This commit is contained in:
ehsan 2026-11-08 04:50:36 +00:00
commit 52d8641f8b
898 changed files with 589383 additions and 0 deletions

30
.gitignore vendored Normal file
View file

@ -0,0 +1,30 @@
# Ignore large archives, media, databases, caches & backups
.curator_backups/
spillover/
node_modules/
.venv/
venv/
__pycache__/
*.pyc
*.tar.gz
*.tgz
*.zip
*.rar
*.7z
*.mp4
*.mov
*.mkv
*.avi
*.mp3
*.wav
*.db
*.sqlite
*.sqlite3
*.sqlite-wal
*.sqlite-shm
*.dump
*.bak*
*.log
.env
.env.*
!.env.example

View file

@ -0,0 +1,21 @@
# Application Settings
PROJECT_NAME="NetVibe Telegram Content Automation"
# Database Configuration (PostgreSQL in production, SQLite for local testing)
DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/netvibe_vpn
# DATABASE_URL=sqlite+aiosqlite:///./vpn_pipeline.db
# Telegram Bot API Configuration
TELEGRAM_BOT_TOKEN=123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ
TARGET_CHANNEL=@NetVibe_VPN
# OpenAI API Configuration (for Agent B Curation & Active Learning)
OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
OPENAI_MODEL=gpt-4o
# Scheduler Intervals
SCRAPE_INTERVAL_HOURS=6
PUBLISH_CHECK_INTERVAL_SECONDS=60
# Frontend Next.js
NEXT_PUBLIC_API_URL=http://localhost:8000

View file

@ -0,0 +1,138 @@
# NetVibe VPN - Telegram Content Aggregation & Automated Publishing Pipeline
سیستم جامع و چندعاملی (Multi-Agent) برای رصد خودکار کانال‌های مرجع تلگرام در حوزه فیلترشکن، پروکسی و هوش مصنوعی، بازنویسی هوشمند و جذاب با لحن عامیانه ایرانی، داشبورد نظارت و ویرایش سردبیر تحت Next.js و دیسپچر انتشار خودکار به کانال رسمی `@NetVibe_VPN`.
---
## 🏗️ معماری سیستم و ایجنت‌ها
```
┌────────────────────────────────────────────────────────┐
│ Telegram Public Web │
│ (Channels: VPN, Proxy, Bypass, AI Tools) │
└───────────────────────────┬────────────────────────────┘
│
▼
┌───────────────────────────┐
│ Agent A: Web Scraper │ (httpx + BeautifulSoup)
│ (No Bot / No Ban Risk) │
└─────────────┬─────────────┘
│ Saves to raw_posts
▼
┌───────────────────────────┐
│ PostgreSQL / SQLAlchemy │ (Persistent storage & DDL)
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Agent B: LLM Curator │ (Persian Copywriting + Active Learning)
│ (GPT-4o + Few-shot Diff) │
└─────────────┬─────────────┘
│ Generates content_drafts
▼
┌───────────────────────────┐
│ Next.js Curation Panel │ (Review, Edit, Inline Diff, Tooltips)
│ (Editor / Human Gate) │
└─────────────┬─────────────┘
│ Approves into publish_queue
▼
┌───────────────────────────┐
│ Agent C: Auto Publisher │ (python-telegram-bot / Telegram Bot API)
│ (Scheduled Worker) │
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Official Telegram Channel │
│ @NetVibe_VPN │
└───────────────────────────┘
```
---
## 🌟 ویژگی‌های کلیدی
1. **Agent A (اسکرپر عمومی تلگرام)**:
- بدون نیاز به اکانت تلگرام یا سشن MTProto (حذف کامل ریسک بن شدن).
- استخراج عنوان، متن پیام، عکس/ویدیو، تعداد بازدید، واکنش‌ها و تاریخ پیام از `https://t.me/s/{channel}`.
- جلوگیری از ذخیره پست‌های تکراری با کلید یکتای ترکیبی `(channel_id, message_id)`.
2. **Agent B (موتور سنتز و یادگیری فعال)**:
- نگارش با لحن خودمانی، عامیانه، رفاقتی و به شدت روان فارسی متناسب با برند NetVibe.
- استخراج تفاوت‌ها (Diff Tracking) بین خروجی اولیه هوش مصنوعی و ویرایش‌های نهایی سردبیر با الگوریتم توالی‌یابی کاراکتری.
- تزریق خودکار تجربیات و خط‌قرمزهای سردبیر به عنوان نمونه‌های پرامپت (Active Few-shot In-context Learning).
3. **Agent C (دیسپچر انتشار خودکار)**:
- پایش مداوم صف انتشار در دیتابیس (`publish_queue`).
- ارسال مستقیم به کانال `@NetVibe_VPN` به همراه مدیا (عکس/ویدیو) و کپشن با فرمت Markdown.
- ثبت شناسه پیام منتشرشده (`telegram_msg_id`) و مدیریت خطاها با امکان تلاش مجدد.
4. **پنل مدیریت Next.js (App Router + Tailwind CSS)**:
- صندوق بررسی و ویرایش پیش‌نویس‌ها با ادیتور متنی زنده.
- رعایت دقیق استاندارد Enterprise: **تمامی کارت‌ها، ستون‌های جداول و دکمه‌ها دارای آیکون راهنما (i) (Info Tooltip) با توضیح کامل هستند.**
- مانیتورینگ وضعیت کانال‌ها و صف انتشار زمان‌بندی‌شده.
---
## 🗄️ ساختار جداول دیتابیس (PostgreSQL)
فایل مایگریشن در مسیر `backend/migrations/001_initial_schema.sql` قرار دارد:
- `channels`: ثبت کانال‌های تحت نظر، عنوان، حوزه و وضعیت رصد.
- `raw_posts`: پست‌های خام استخراج‌شده همراه با بازدید، مدیا و لینک اصلی.
- `content_drafts`: پیش‌نویس‌های تولیدشده توسط هوش مصنوعی با وضعیت‌های `pending`, `approved`, `edited`, `rejected`, `published`.
- `feedback_logs`: سوابق دیف‌های ویراستار انسانی، درصد شباهت، دسته‌بندی تغییرات و دلایل رد.
- `publish_queue`: صف زمان‌بندی‌شده انتشار با وضعیت‌های `queued`, `publishing`, `success`, `failed`.
---
## 🚀 راهنمای راه‌اندازی سریع
### روش ۱: اجرا با Docker Compose (پیشنهادی)
```bash
cd /workspace/personal/VPN_chanel
cp .env.example .env
# مقادیر TELEGRAM_BOT_TOKEN و OPENAI_API_KEY را در .env تکمیل کنید
docker compose up -d
```
- بک‌اند: `http://localhost:8000/docs`
- فرانت‌اند: `http://localhost:3000`
---
### روش ۲: راه‌اندازی محلی (Development)
#### راه‌اندازی بک‌اند:
```bash
cd /workspace/personal/VPN_chanel/backend
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
# اجرای سرور API
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
```
#### راه‌اندازی فرانت‌اند:
```bash
cd /workspace/personal/VPN_chanel/frontend
npm install
npm run dev
```
---
## 📡 مسیرهای اصلی API
| متد | مسیر | توضیحات |
| :--- | :--- | :--- |
| `GET` | `/api/v1/channels` | دریافت لیست کانال‌های تحت پایش |
| `POST` | `/api/v1/channels` | افزودن کانال جدید به لیست رصد |
| `POST` | `/api/v1/pipeline/scrape-and-curate` | اجرای آنی فرآیند اسکرپ و تولید پیش‌نویس |
| `GET` | `/api/v1/drafts?status=pending` | دریافت پیش‌نویس‌ها جهت بررسی |
| `POST` | `/api/v1/drafts/{id}/action` | تایید، ویرایش یا رد پیش‌نویس |
| `GET` | `/api/v1/queue` | مشاهده صف زمان‌بندی انتشار |
| `POST` | `/api/v1/pipeline/dispatch-now` | ارسال فوری پست‌های صف به تلگرام |
| `GET` | `/api/v1/feedback-logs` | مشاهده تاریخچه ویرایش‌ها و یادگیری هوش مصنوعی |

View file

@ -0,0 +1,17 @@
FROM python:3.12-slim
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
build-essential \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--limit-concurrency", "10", "--timeout-keep-alive", "5"]

View file

@ -0,0 +1 @@
# NetVibe Automation Pipeline

View file

@ -0,0 +1 @@
# Pipeline Agents A, B, C

View file

@ -0,0 +1,210 @@
import re
import logging
from datetime import datetime, timezone
from typing import List, Dict, Any, Optional
import httpx
from bs4 import BeautifulSoup
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update
from app.models import Channel, RawPost
logger = logging.getLogger("agent_a_scraper")
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9,fa;q=0.8",
}
DEFAULT_SEED_CHANNELS = [
{"handle": "NetVibe_VPN", "title": "کانال رسمی NetVibe (الگوی مرجع لحن و هویت)", "niche": "کانال اختصاصی کسب‌وکار", "subscribers": 5000},
{"handle": "FilterShekanha", "title": "فیلترشکن‌ها و اینترنت آزاد", "niche": "آموزش امنیت و ضدسانسور", "subscribers": 61300},
{"handle": "hiddify", "title": "اکوسیستم رسمی Hiddify", "niche": "کلاینت و ابزارهای نوین دور زدن", "subscribers": 121000},
{"handle": "TechTube", "title": "تک‌توب آموزش شبکه و اینترنت", "niche": "آموزش تخصصی شبکه و فرگمنت", "subscribers": 75300},
{"handle": "MiladNouri", "title": "دیده‌بان اینترنت میلاد نوری", "niche": "اخبار اختلالات و سانسور اینترنت", "subscribers": 27200},
{"handle": "NarimanGharib", "title": "امنیت سایبری نریمان غریب", "niche": "تحلیل اختلالات و امنیت دیجیتال", "subscribers": 16700},
{"handle": "vpn_tehran", "title": "مرکز تخصصی شبکه و V2Ray", "niche": "آموزش و بهینه‌سازی کلاینت‌ها", "subscribers": 21700},
{"handle": "ClashMeta", "title": "هسته Mihomo و Clash Meta", "niche": "تنظیمات هسته و رول‌های هوشمند", "subscribers": 17000},
{"handle": "TorProject", "title": "پروژه رسمی Tor و بریج‌ها", "niche": "حریم خصوصی و ارتباطات ناشناس", "subscribers": 34000},
{"handle": "v2fly", "title": "هسته رسمی V2Fly", "niche": "توسعه پروتکل‌های V2Ray", "subscribers": 6300},
{"handle": "Outline_Vpn", "title": "Outline Vpn Official", "niche": "پروتکل شادوساکس و زیرساخت", "subscribers": 680000},
{"handle": "AzadNet", "title": "آزادنت آموزش و اخبار", "niche": "راهنمای اتصال و ابزارهای امن", "subscribers": 249000},
{"handle": "V2Ray_Alpha", "title": "آلفا V2Ray تحلیل پروتکل", "niche": "بررسی فنی پروتکل‌های ارتباطی", "subscribers": 244000},
{"handle": "V2RayNG_VPN", "title": "راهنمای کلاینت v2rayNG", "niche": "آموزش و آپدیت‌های اندروید", "subscribers": 7750},
{"handle": "v2ray_collector", "title": "پایشگر شبکه V2RayCollector", "niche": "تست و مانیتورینگ اختلالات", "subscribers": 4750},
{"handle": "v2ray_free_conf", "title": "اخبار زیرساخت سرورها", "niche": "وضعیت سرورها و پینگ دیتاسنترها", "subscribers": 15200},
{"handle": "V2rayProxy", "title": "پایش پروکسی‌ها و پورت‌ها", "niche": "تحلیل پورت‌ها و پروتکل‌ها", "subscribers": 7180},
{"handle": "shadowrocket_vpn", "title": "راهنمای Shadowrocket و iOS", "niche": "تنظیمات کلاینت‌های آیفون", "subscribers": 1710},
{"handle": "Digiato", "title": "دیجیاتو اخبار فناوری و اینترنت", "niche": "اخبار رسمی اینترنت و زیرساخت", "subscribers": 115000},
{"handle": "ProxyMTProto", "title": "اطلاعیه‌ها و پروکسی‌های امن", "niche": "تحلیل پروکسی و ترافیک تلگرام", "subscribers": 11900000},
{"handle": "v2rayngvpn", "title": "جامعه کاربری v2rayNG", "niche": "تجربیات اتصال و ترفندهای کاربران", "subscribers": 1030000},
]
async def seed_default_channels(session: AsyncSession):
for seed in DEFAULT_SEED_CHANNELS:
clean_handle = seed["handle"].replace("@", "").strip()
stmt = select(Channel).where(Channel.telegram_handle == clean_handle)
res = await session.execute(stmt)
existing = res.scalar_one_or_none()
if not existing:
ch = Channel(
telegram_handle=clean_handle,
title=seed["title"],
niche=seed["niche"],
subscriber_count=seed.get("subscribers", 10000),
is_active=True
)
session.add(ch)
else:
existing.title = seed["title"]
existing.niche = seed["niche"]
if seed.get("subscribers"):
existing.subscriber_count = seed["subscribers"]
await session.commit()
def parse_views_count(view_text: str) -> int:
if not view_text:
return 0
clean = view_text.strip().upper()
try:
if "M" in clean:
return int(float(clean.replace("M", "")) * 1_000_000)
if "K" in clean:
return int(float(clean.replace("K", "")) * 1_000)
return int(clean)
except ValueError:
return 0
async def scrape_public_telegram_channel(handle: str, limit: int = 20) -> List[Dict[str, Any]]:
clean_handle = handle.replace("@", "").strip()
url = f"https://t.me/s/{clean_handle}"
async with httpx.AsyncClient(headers=HEADERS, timeout=20.0, follow_redirects=True) as client:
try:
res = await client.get(url)
if res.status_code != 200:
logger.warning(f"Channel {clean_handle} returned HTTP {res.status_code}")
return []
except Exception as e:
logger.error(f"Error fetching channel {clean_handle}: {e}")
return []
soup = BeautifulSoup(res.text, "html.parser")
msg_divs = soup.find_all("div", class_="tgme_widget_message")
results: List[Dict[str, Any]] = []
for msg in msg_divs[-limit:]:
post_attr = msg.get("data-post")
if not post_attr or "/" not in post_attr:
continue
parts = post_attr.split("/")
try:
msg_id = int(parts[1])
except ValueError:
continue
post_url = f"https://t.me/{post_attr}"
# Text
text_elem = msg.find("div", class_="tgme_widget_message_text")
original_text = text_elem.get_text(separator="\n").strip() if text_elem else ""
# Media Extraction
media_type = "none"
media_url = None
photo_elem = msg.find("a", class_="tgme_widget_message_photo_wrap")
video_elem = msg.find("video")
doc_elem = msg.find("div", class_="tgme_widget_message_document")
if photo_elem:
media_type = "photo"
style = photo_elem.get("style", "")
bg_match = re.search(r"url\('([^']+)'\)", style)
if bg_match:
media_url = bg_match.group(1)
elif video_elem:
media_type = "video"
media_url = video_elem.get("src")
elif doc_elem:
media_type = "document"
# Views
views_elem = msg.find("span", class_="tgme_widget_message_views")
views = parse_views_count(views_elem.text if views_elem else "0")
# Date & Recency check
time_elem = msg.find("time")
posted_at = datetime.now(timezone.utc)
if time_elem and time_elem.get("datetime"):
try:
dt_str = time_elem["datetime"].replace("Z", "+00:00")
posted_at = datetime.fromisoformat(dt_str)
except Exception:
pass
# STRICT RECENCY FILTER: Discard posts older than 7 days
now_utc = datetime.now(timezone.utc)
days_old = (now_utc - posted_at).total_seconds() / 86400.0
if days_old > 7.0:
logger.debug(f"Skipping stale post {post_attr} ({days_old:.1f} days old)")
continue
# OUTDATED SEASONAL KEYWORDS FILTER (No outdated Nowruz, past holiday greetings)
stale_keywords = [
"نوروز", "سال نو", "عید نوروز", "تعطیلات عید", "فروردین", "تبریک سال نو",
"1402", "۱۴۰۲", "سال ۱۴۰۲", "نوروز مبارک", "سال پیش"
]
text_lower = (original_text or "").lower()
if any(sk in text_lower for sk in stale_keywords):
logger.info(f"Skipping outdated seasonal post {post_attr} containing stale holiday keywords")
continue
if original_text or media_url:
results.append({
"message_id": msg_id,
"original_text": original_text,
"post_url": post_url,
"media_type": media_type,
"media_url": media_url,
"views": views,
"reactions": 0,
"posted_at": posted_at
})
return results
async def run_channel_ingestion(session: AsyncSession, channel: Channel, limit: int = 15) -> int:
posts = await scrape_public_telegram_channel(channel.telegram_handle, limit=limit)
new_count = 0
for post_data in posts:
# Check uniqueness by channel_id and message_id
stmt = select(RawPost).where(
RawPost.channel_id == channel.id,
RawPost.message_id == post_data["message_id"]
)
existing = (await session.execute(stmt)).scalar_one_or_none()
if not existing:
raw_post = RawPost(
channel_id=channel.id,
message_id=post_data["message_id"],
original_text=post_data["original_text"],
post_url=post_data["post_url"],
media_type=post_data["media_type"],
media_url=post_data["media_url"],
views=post_data["views"],
reactions=post_data["reactions"],
posted_at=post_data["posted_at"]
)
session.add(raw_post)
new_count += 1
await session.execute(
update(Channel)
.where(Channel.id == channel.id)
.values(last_scraped_at=datetime.now(timezone.utc))
)
await session.commit()
return new_count

View file

@ -0,0 +1,290 @@
import difflib
import logging
import uuid
import re
import os
from typing import Optional, Dict, Any, List
from openai import AsyncOpenAI
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, desc
from app.config import settings
from app.models import FeedbackLog, ContentDraft, RawPost
from app.banner_generator import (
create_vpn_banner,
create_gemini_banner,
get_gemini_banner_from_pool_or_generate,
get_vpn_banner_from_pool_or_generate
)
logger = logging.getLogger("agent_b_curator")
CURATOR_SYSTEM_PROMPT = """
تو ارشدترین کپی‌رایتر، استراتژیست محتوا و سردبیر کانال تلگرامی NetVibe (@NetVibe_VPN) در حوزه فیلترشکن، اینترنت آزاد، پینگ و امنیت سایبری در ایران هستی.
ماموریت تو: تحلیل دقیق پست منبع رقیب و **بازآفرینی خلاقانه یک پست تلگرامی جدید، مستقل، گیرا و پربازده دقیقاً در همان سبک، موضوع، پرسونای مخاطب و زاویه دید (Angle)** برای کانال NetVibe.
💎 قانون طلایی: انطباق دقیق بر سبک، پرسونای هدف و موضوع پست منبع (Style & Angle Mirroring)
اکیداً از تبدیل همه پست‌ها به یک قالب تکراری خودداری کن! هر پست باید متناسب با روح و محتوای منبع خود بازآفرینی شود:
۱. اگر پست منبع درباره گیمینگ، تست پینگ، اتصال ویندوز/کامپیوتر، دیسکورد، استیم یا فریلنسری است:
- مخاطب هدف: گیمرها، تریدرها، برنامه‌نویسان و کاربرانی که با کامپیوتر کار می‌کنند.
- دغدغه و درد اصلی: پینگ نوسانی، قطعی و تایم‌اوت وسط بازی، پکت‌لاس (Packet Loss)، لود نشدن دیسکورد، یوتیوب و بازی‌های آنلاین روی ویندوز.
- هوک و محتوا: متناسب با فضای گیمینگ و سیستم بنویس (تست پینگ پایدار روی ویندوز با کلاینت‌های استاندارد، پکت‌لاس صفر، پینگ ثابت، اول تست کن بعد تصمیم بگیر).
۲. اگر پست منبع درباره ترید، صرافی‌های ارز دیجیتال و امور مالی است:
- مخاطب هدف: فعالان کریپتو و بازارهای مالی بین‌المللی.
- دغدغه اصلی: نشت DNS و IP، ریسک مسدود شدن حساب در صرافی‌هایی مثل بینگ‌ایکس، کوکوین و بایننس به دلیل تغییر مداوم لوکیشن.
- ارزش NetVibe: آی‌پی تمیز و استاتیک، بدون قطعی، نهایت امنیت سرمایه.
۳. اگر پست منبع شوخی، میم، اعتراض به اختلالات یا اخبار فیلترینگ است:
- با همان لحن صمیمی، محاوره‌ای و تند و تیز تلگرامی بنویس؛ ابتدا همدلی با وضعیت نت و سپس ارائه راه‌حل فوری و بدون قطعی NetVibe.
۴. اگر پست منبع معرفی کانفیگ رایگان یا سرور تست است:
- در صورت وجود لینک کانفیگ، آن را در قالب کدبلاک (```) جهت کپی با یک لمس قرار بده، همراه با مشخصات و لوکیشن سرور.
۵. اگر پست منبع پلن‌های نامحدود، جشنواره یا بسته‌های حجمی و مدت‌دار است:
- با ساختار شفاف قیمت، مزایای رقابتی (بدون لیمیت، بدون قطعی روی همراه اول و ایرانسل) و گارانتی بازگشت وجه معرفی کن.
۶. اگر پست منبع درباره ابزارهای هوش مصنوعی (Gemini Pro، چت‌جی‌پی‌تی) است:
- با تمرکز روی پلن‌های قانونی، فعال‌سازی روی ایمیل شخصی و بدون نیاز به شماره مجازی بنویس.
🛑 الزامات محتوایی و نگارشی:
- لحن: کاملاً محاوره‌ای، روان، انرژی‌بخش و معتبر تلگرام فارسی با چیدمان زیبا و ایموجی‌های متناسب.
- ممنوعیت کپی نعل‌به‌نعل: زاویه دید و ایده را بگیر اما جملات را با قلم اختصاصی و اصیل NetVibe بازنویسی کن.
- پاکسازی ۱۰۰٪ ردپای رقبا: هرگونه آیدی کانال رقیب، ربات ناشناس (@...)، شماره تماس یا نام متفرقه را حذف کن.
- کال‌تو‌اکشن (CTA) استاندارد در انتهای هر پست:
✉️ پشتیبانی، مشاوره و تست رایگان: @NetVibe_admin
🌐 کانال رسمی: https://t.me/NetVibe_VPN
- خروجی الزامی: فقط و فقط متن نهایی پست تلگرامی را ارسال کن؛ از نوشتن هرگونه توضیح، مقدمه یا برچسب اضافی خودداری کن.
درس‌ها و تجربیات ثبت‌شده سردبیر:
{feedback_guidelines}
"""
def get_fallback_persian_copy(raw_text: str, media_type: str) -> str:
txt = (raw_text or "").lower()
# 1. Gaming, Ping test, Windows, Freelancer, Trader
if any(k in txt for k in ["گیم", "پینگ", "ویندوز", "ترید", "کامپیوتر", "لگ", "فریلنس", "بازی", "v2rayn", "v2rayng"]):
return (
"🎮 گیمری یا با کامپیوتر ترید و فریلنسری می‌کنی؟\n\n"
"اگر خسته شدی از پینگ‌های بالا، پکت‌لاس و دیسکانکت شدن وسط بازی یا کار با ویندوز...\n"
"سرورهای اختصاصی NetVibe دقیقاً برای کاربری سنگین و حساس طراحی شدن! ⚡️\n\n"
"▫️ پینگ فوق‌العاده پایین و پایدار (بدون نوسان و بدون پکت‌لاس)\n"
"▫️ سازگار کامل با سیستم‌عامل ویندوز، مک و انواع کلاینت‌ها\n"
"▫️ آی‌پی تمیز و ثابت مناسب ترید و صرافی‌های ارزی\n"
"▫️ تست‌شده روی دیسکورد، استیم، یوتیوب و بازی‌های آنلاین\n\n"
"خودت قبل از خرید تست کن، پینگ و سرعت واقعی رو بسنج! 😎\n\n"
"✉️ تست رایگان، مشاوره و خرید: @NetVibe_admin\n"
"🌐 کانال رسمی: https://t.me/NetVibe_VPN"
)
# 2. Configs & Keys
elif any(k in txt for k in ["vless://", "vmess://", "trojan://", "ss://", "کانفیگ"]):
config_match = re.search(r'(vless://[^\s]+|vmess://[^\s]+|trojan://[^\s]+|ss://[^\s]+)', raw_text or "")
conf_code = config_match.group(1) if config_match else "vless://b6f4a8e2-9d3c-4a1b-8e7f-5c2d1e0a9b8c@185.220.101.5:443?encryption=none&flow=xtls-rprx-vision&security=reality&sni=speedtest.net&fp=chrome#NetVibe-Germany"
return (
"⚡️ سرور تست‌شده و اختصاصی NetVibe\n"
"🌐 لوکیشن: آلمان 🇩🇪\n"
"🛡️ وضعیت: اتصال پرسرعت و پایدار بدون قطعی\n\n"
"کد کانفیگ (تک‌کلیک کپی کنید):\n"
f"```\n{conf_code}\n```\n\n"
"▫️ سازگار با: تمامی نرم‌افزارهای استاندارد (Hiddify, v2rayNG, Sing-box)\n"
"▫️ وضعیت: پایدار روی تمام اپراتورها (همراه اول، ایرانسل و وای‌فای)\n\n"
"✉️ پشتیبانی و سرورهای اختصاصی: @NetVibe_admin\n"
"🌐 کانال رسمی: https://t.me/NetVibe_VPN"
)
# 3. Tutorials & Tricks
elif any(k in txt for k in ["آموزش", "تنظیم", "کلاینت", "hiddify", "v2rayng", "fragment", "dns", "ترفند"]):
return (
"💡 ترفند طلایی پایداری اتصال و رفع قطعی اینترنت\n\n"
"اگر این روزها روی همراه اول یا ایرانسل مدام قطع می‌شید، این چند نکته ساده رو رعایت کنید:\n\n"
"▫️ ۱. استفاده از کلاینت‌های به‌روز: حتماً از آخرین نسخه برنامه‌های استانداردی مثل Hiddify یا v2rayNG استفاده کنید.\n"
"▫️ ۲. تغییر DNS به DoH پاک: مقدار DNS را روی آدرس‌های معتبر مثل Cloudflare ست کنید.\n"
"▫️ ۳. تست دوره‌ای ساب‌لینک: ساب‌لینک هوشمند به طور خودکار بهترین مسیر را برای شما انتخاب می‌کند.\n\n"
"✉️ راهنمایی و پشتیبانی: @NetVibe_admin\n"
"🌐 کانال رسمی: https://t.me/NetVibe_VPN"
)
# 4. Pricing / Packages
elif any(k in txt for k in ["اشتراک", "خرید", "پشتیبانی", "پلن", "قیمت", "ثابت", "کیفیت", "فروش", "تعرفه", "کاربره"]):
return (
"➕ اگر هنوز درگیر قطعی وصلی هستی و دنبال اتصال پایداری ؛ میتونی روی ما حساب کنی !\n\n"
"🛑 بسته‌های جدید بدون محدودیت حجم (نامحدود) 🛑\n"
"فعال روی: تمامی سایت‌ها و اپلیکیشن‌ها\n"
"بدون نگرانی بابت تمام شدن حجم! ♾️\n\n"
"👤 ۲ کاربره: ۳۰۰.۰۰۰ تومان\n"
"👥 ۳ کاربره: ۳۵۰.۰۰۰ تومان\n\n"
"✅ مدت زمان استفاده: ۱ ماه\n"
"✅ محدودیت حجم: ندارد (نامحدود)\n"
"✅ ساب‌لینک اختصاصی: دارد\n"
"✅ بدون قطعی روی تمام اپراتورها\n\n"
"✉️ پشتیبانی و سفارش: @NetVibe_admin\n"
"🌐 کانال رسمی: https://t.me/NetVibe_VPN"
)
else:
return (
"🚨 رادار شبکه: وضعیت اختلالات و پایداری اینترنت\n\n"
"طبق ارزیابی وضعیت ترافیک در ۲۴ ساعت گذشته:\n\n"
"▫️ اختلالات گسترده‌ای روی بخش زیادی از ارتباطات بین‌الملل گزارش شده است.\n"
"▫️ سرورهای NetVibe با سوییچ خودکار روی مسیرهای امن ابری، اتصال بدون افت سرعت را برای کاربران حفظ کرده‌اند.\n\n"
"✉️ پشتیبانی و تهیه اشتراک: @NetVibe_admin\n"
"🌐 کانال رسمی: https://t.me/NetVibe_VPN"
)
async def build_feedback_guidelines(session: AsyncSession, limit: int = 5) -> str:
stmt = (
select(FeedbackLog)
.order_by(desc(FeedbackLog.created_at))
.limit(limit)
)
logs = (await session.execute(stmt)).scalars().all()
if not logs:
return "- تا این لحظه ویرایش متناقضی ثبت نشده است؛ روی لحن صمیمی و خودمانی تمرکز کن."
rules: List[str] = []
for log in logs:
diff_info = log.diff_analysis or {}
summary = diff_info.get("summary", "اصلاح استایل و کلمات")
sample_fix = log.final_human_text[:140].replace("\n", " ")
rules.append(f"• تجربه قبلی: در شرایط '{summary}'، سردبیر متن را این‌گونه ترجیح داد: «{sample_fix}...»")
return "\n".join(rules)
async def generate_draft_for_post(session: AsyncSession, raw_post_or_id: Any) -> ContentDraft:
if isinstance(raw_post_or_id, (str, uuid.UUID)):
stmt = select(RawPost).where(RawPost.id == raw_post_or_id)
raw_post = (await session.execute(stmt)).scalar_one_or_none()
if not raw_post:
raise ValueError(f"Raw post {raw_post_or_id} not found")
else:
raw_post = raw_post_or_id
feedback_guidelines = await build_feedback_guidelines(session)
system_prompt = CURATOR_SYSTEM_PROMPT.format(feedback_guidelines=feedback_guidelines)
user_prompt = (
f"متن پست خام منبع:\n{raw_post.original_text or '(فقط رسانه منتشر شده است)'}\n\n"
f"نوع مدیا: {raw_post.media_type}\n"
f"لینک پست اصلی: {raw_post.post_url}\n"
f"تعداد بازدید پست اصلی: {raw_post.views}"
)
generated_text = ""
if settings.OPENAI_API_KEY:
try:
client = AsyncOpenAI(
api_key=settings.OPENAI_API_KEY,
base_url=settings.OPENAI_API_BASE
)
completion = await client.chat.completions.create(
model=settings.OPENAI_MODEL,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
temperature=0.72,
max_tokens=1000
)
generated_text = completion.choices[0].message.content.strip()
except Exception as e:
logger.error(f"OpenAI generation failed: {e}. Falling back to rule-based engine.")
generated_text = get_fallback_persian_copy(raw_post.original_text or "", raw_post.media_type)
else:
generated_text = get_fallback_persian_copy(raw_post.original_text or "", raw_post.media_type)
# Auto Banner Generation (Smart Media Strategy)
# 1. Configs & quick keys: Always text-only (no banner) so users can tap and copy instantly without visual clutter.
# 2. Promotions & Special Offers: Generate high-resolution 1280x720 neon cyber banners.
banner_url = None
try:
txt_combined = (generated_text + " " + (raw_post.original_text or "")).lower()
has_config = any(c in txt_combined for c in ["vless://", "vmess://", "trojan://", "ss://", "```"])
is_gemini = any(w in txt_combined for w in ["gemini", "جمنای", "جمینی", "هوش مصنوعی", "اکانت ۱۸ ماهه", "گوگل"])
is_gaming = any(w in txt_combined for w in ["گیم", "پینگ", "ویندوز", "ترید", "کامپیوتر", "بازی", "لگ", "فریلنس", "استیم", "دیسکورد"])
if is_gemini:
banner_url = get_gemini_banner_from_pool_or_generate(
headline="جهش چشمگیر در سرعت و کیفیت پروژه‌ها",
price_toman="۶۰۰.۰۰۰ تومان",
is_discount=True
)
logger.info(f"Assigned Gemini banner (pool or dynamic): {banner_url}")
elif not has_config:
if is_gaming:
banner_url = get_vpn_banner_from_pool_or_generate(
title="پینگ پایدار و بدون پکت‌لاس مخصوص گیم، ترید و ویندوز",
card1_title="سرورهای پرسرعت سیستم",
card2_title="آی‌پی تمیز و تست رایگان",
brand=settings.TARGET_CHANNEL
)
else:
banner_url = get_vpn_banner_from_pool_or_generate(
title="اتصال پایدار و بدون قطعی در سراسر ایران",
card1_title="پلن ۲ کاربره نامحدود",
card2_title="پلن ۳ کاربره نامحدود",
brand=settings.TARGET_CHANNEL
)
logger.info(f"Assigned VPN banner (pool or dynamic): {banner_url}")
else:
logger.info("Smart Media: Clean text-only post without banner (faster copy, zero visual clutter).")
except Exception as e:
logger.warning(f"Auto banner generation skipped: {e}")
draft = ContentDraft(
raw_post_id=raw_post.id,
ai_generated_text=generated_text,
current_text=generated_text,
status="pending",
brand_target=settings.TARGET_CHANNEL,
banner_image_url=banner_url
)
session.add(draft)
await session.commit()
await session.refresh(draft)
return draft
def compute_diff_analysis(original_ai: str, edited_text: str) -> Dict[str, Any]:
matcher = difflib.SequenceMatcher(None, original_ai, edited_text)
ratio = round(matcher.ratio(), 3)
summary = "بدون تغییر"
if ratio == 1.0:
category = "identical"
elif ratio > 0.85:
category = "minor_polishing"
summary = "اصلاحات جزئی تایپی، نیم‌فاصله یا نشانه‌گذاری"
elif ratio > 0.55:
category = "tone_adjustment"
summary = "تنظیم لحن و تغییر در واژگان یا بازنویسی بخش‌هایی از متن"
else:
category = "major_rewrite"
summary = "بازنویسی عمده ساختار یا تعویض کامل قلاب و CTA"
return {
"similarity_ratio": ratio,
"category": category,
"summary": summary,
"original_len": len(original_ai),
"edited_len": len(edited_text)
}
async def record_human_feedback(
session: AsyncSession,
draft_id: str,
original_ai_text: str,
final_human_text: str,
rejection_reason: Optional[str] = None
):
diff_data = compute_diff_analysis(original_ai_text, final_human_text)
log = FeedbackLog(
draft_id=draft_id,
original_ai_text=original_ai_text,
final_human_text=final_human_text,
diff_analysis=diff_data,
rejection_reason=rejection_reason
)
session.add(log)
await session.commit()
return log

View file

@ -0,0 +1,317 @@
import os
import re
import logging
from datetime import datetime, timezone
from typing import Tuple, Optional
import httpx
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.config import settings
from app.models import PublishQueue, ContentDraft, RawPost
logger = logging.getLogger("agent_c_publisher")
def ensure_official_links(text: str) -> str:
if not text:
return text
fixed = text
# Remove competing channel handles or links
# Standardize official NetVibe links
official_channel_link = "https://t.me/NetVibe_VPN"
official_admin = "@NetVibe_admin"
# Replace variations of NetVibe channel with the exact official URL
fixed = re.sub(r'https?://t\.me/(?:joinchat/)?[a-zA-Z0-9_+]*NetVibe[a-zA-Z0-9_]*', official_channel_link, fixed, flags=re.IGNORECASE)
fixed = re.sub(r'(?<!t\.me/)@NetVibe_?VPN\b', official_channel_link, fixed, flags=re.IGNORECASE)
# Replace variations of admin handle with exact official admin
fixed = re.sub(r'@NetVibe_?admin[a-zA-Z0-9_]*', official_admin, fixed, flags=re.IGNORECASE)
# Ensure the standard footer format exists
if official_channel_link not in fixed:
fixed = fixed.strip() + f"\n\n🌐 کانال رسمی: {official_channel_link}"
if official_admin not in fixed:
fixed = fixed.strip() + f"\n✉️ پشتیبانی و ثبت سفارش: {official_admin}"
return fixed
def markdown_to_telegram_html(text: str) -> str:
"""
Safely converts Markdown to Telegram HTML format without stripping underscores
from URLs, channel handles, or code snippets.
"""
if not text:
return ""
code_blocks = []
def save_cb(m):
code_blocks.append(m.group(2) if m.group(2) is not None else "")
return f"__CB_{len(code_blocks)-1}__"
text = re.sub(r"```([a-zA-Z0-9_]+)?\n?(.*?)```", save_cb, text, flags=re.DOTALL)
inline_codes = []
def save_ic(m):
inline_codes.append(m.group(1))
return f"__IC_{len(inline_codes)-1}__"
text = re.sub(r"`([^`]+)`", save_ic, text)
# Escape HTML special chars
text = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
# Bold: **bold** -> <b>bold</b>
text = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", text)
# Restore inline code
for i, ic in enumerate(inline_codes):
c = ic.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
text = text.replace(f"__IC_{i}__", f"<code>{c}</code>")
# Restore code blocks
for i, cb in enumerate(code_blocks):
c = cb.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
text = text.replace(f"__CB_{i}__", f"<pre><code>{c}</code></pre>")
return text
def resolve_local_banner_path(banner_image_url: Optional[str]) -> Optional[str]:
"""Finds the physical path for the banner file, supporting relative URLs, casing mismatches, and symlinks."""
if not banner_image_url:
return None
clean_path = banner_image_url.replace("http://127.0.0.1:8000", "").replace("https://netvibe.ehsan.test.zebellkhan.com", "")
if clean_path.startswith("/static/"):
clean_path = clean_path.replace("/static/", "")
backend_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # /backend/app
static_root = os.path.join(backend_dir, "static")
search_dirs = [
static_root,
os.path.join(static_root, "banners"),
os.path.join(static_root, "banner_pool"),
os.path.join(static_root, "banner_pool", "gemini"),
os.path.join(static_root, "banner_pool", "vpn")
]
# Direct candidate
for sdir in search_dirs:
cand = os.path.join(sdir, clean_path)
if os.path.exists(cand) and os.path.isfile(cand):
return cand
# Case-insensitive filename search
target_filename = os.path.basename(clean_path).lower()
for sdir in search_dirs:
if not os.path.isdir(sdir):
continue
for root, _, files in os.walk(sdir):
for f in files:
if f.lower() == target_filename:
return os.path.join(root, f)
# Fallback to default pool banners if image was specifically expected
default_gemini = os.path.join(static_root, "banner_pool", "gemini", "Gemini_Pro_999k_Discount_Holo_Pedestal_6Gmail.png")
default_vpn = os.path.join(static_root, "banner_pool", "vpn", "vpn_master_banner_1.png")
if "gemini" in banner_image_url.lower() and os.path.exists(default_gemini):
return default_gemini
if os.path.exists(default_vpn):
return default_vpn
return None
async def send_to_telegram(
text: str,
target_channel: str,
bot_token: str,
media_type: str = "none",
media_url: Optional[str] = None,
banner_image_url: Optional[str] = None
) -> Tuple[bool, Optional[int], Optional[str]]:
if not bot_token:
logger.info(f"[SIMULATED DISPATCH] Sent to {target_channel} without real bot token.")
return True, 999999, None
base_url = f"https://api.telegram.org/bot{bot_token}"
async with httpx.AsyncClient(timeout=45.0, follow_redirects=True) as client:
try:
local_banner_path = resolve_local_banner_path(banner_image_url)
if local_banner_path:
with open(local_banner_path, "rb") as f:
file_bytes = f.read()
# Telegram photo caption max limit is 1024 characters
caption_text = text
followup_text = None
if len(text) > 1024:
# Split gracefully: first 950 chars as caption, remainder as followup message
split_idx = text[:950].rfind("\n")
if split_idx == -1:
split_idx = 950
caption_text = text[:split_idx].strip()
followup_text = text[split_idx:].strip()
formatted_caption = markdown_to_telegram_html(caption_text)
files = {"photo": (os.path.basename(local_banner_path), file_bytes, "image/png")}
data = {
"chat_id": target_channel,
"caption": formatted_caption,
"parse_mode": "HTML"
}
res = await client.post(f"{base_url}/sendPhoto", data=data, files=files)
# If Telegram fails due to HTML/Markdown entity parsing, retry without parse_mode
if not res.json().get("ok") and ("can't parse entities" in res.json().get("description", "").lower() or "bad request" in res.json().get("description", "").lower()):
logger.warning("Entity parse failed, retrying photo dispatch with plain text without parse_mode...")
files = {"photo": (os.path.basename(local_banner_path), file_bytes, "image/png")}
data["caption"] = caption_text
data.pop("parse_mode", None)
res = await client.post(f"{base_url}/sendPhoto", data=data, files=files)
# If long text, send the remaining portion as followup reply
if res.json().get("ok") and followup_text:
formatted_followup = markdown_to_telegram_html(followup_text)
followup_data = {
"chat_id": target_channel,
"text": formatted_followup,
"parse_mode": "HTML",
"reply_to_message_id": res.json()["result"]["message_id"]
}
res_followup = await client.post(f"{base_url}/sendMessage", json=followup_data)
if not res_followup.json().get("ok") and "can't parse entities" in res_followup.json().get("description", "").lower():
followup_data["text"] = followup_text
followup_data.pop("parse_mode", None)
await client.post(f"{base_url}/sendMessage", json=followup_data)
elif media_type == "photo" and media_url:
formatted_caption = markdown_to_telegram_html(text)
payload = {
"chat_id": target_channel,
"photo": media_url,
"caption": formatted_caption,
"parse_mode": "HTML"
}
res = await client.post(f"{base_url}/sendPhoto", json=payload)
if not res.json().get("ok") and ("can't parse entities" in res.json().get("description", "").lower() or "bad request" in res.json().get("description", "").lower()):
payload["caption"] = text
payload.pop("parse_mode", None)
res = await client.post(f"{base_url}/sendPhoto", json=payload)
elif media_type == "video" and media_url:
formatted_caption = markdown_to_telegram_html(text)
payload = {
"chat_id": target_channel,
"video": media_url,
"caption": formatted_caption,
"parse_mode": "HTML"
}
res = await client.post(f"{base_url}/sendVideo", json=payload)
if not res.json().get("ok") and ("can't parse entities" in res.json().get("description", "").lower() or "bad request" in res.json().get("description", "").lower()):
payload["caption"] = text
payload.pop("parse_mode", None)
res = await client.post(f"{base_url}/sendVideo", json=payload)
else:
formatted_text = markdown_to_telegram_html(text)
payload = {
"chat_id": target_channel,
"text": formatted_text,
"parse_mode": "HTML",
"disable_web_page_preview": False
}
res = await client.post(f"{base_url}/sendMessage", json=payload)
if not res.json().get("ok") and ("can't parse entities" in res.json().get("description", "").lower() or "bad request" in res.json().get("description", "").lower()):
payload["text"] = text
payload.pop("parse_mode", None)
res = await client.post(f"{base_url}/sendMessage", json=payload)
data = res.json()
if data.get("ok"):
msg_id = data["result"]["message_id"]
logger.info(f"Successfully published to Telegram {target_channel}, msg_id: {msg_id}")
return True, msg_id, None
else:
err_desc = data.get("description", "Unknown Telegram Error")
logger.error(f"Telegram dispatch failed: {err_desc}")
return False, None, err_desc
except Exception as e:
logger.error(f"Telegram network request exception: {e}")
return False, None, str(e)
async def dispatch_pending_queue(session: AsyncSession, batch_size: int = 5, force: bool = False) -> int:
now = datetime.now(timezone.utc)
conditions = [PublishQueue.status == "queued"]
if not force:
conditions.append(PublishQueue.scheduled_time <= now)
stmt = (
select(PublishQueue, ContentDraft, RawPost)
.join(ContentDraft, PublishQueue.draft_id == ContentDraft.id)
.outerjoin(RawPost, ContentDraft.raw_post_id == RawPost.id)
.where(*conditions)
.order_by(PublishQueue.scheduled_time.asc())
.limit(batch_size if not force else 1)
)
items = (await session.execute(stmt)).all()
success_count = 0
for queue_item, draft, raw_post in items:
queue_item.status = "publishing"
await session.commit()
success, msg_id, error = await send_to_telegram(
text=ensure_official_links(draft.current_text),
target_channel=draft.brand_target or settings.TARGET_CHANNEL,
bot_token=settings.TELEGRAM_BOT_TOKEN,
media_type=raw_post.media_type if raw_post else "none",
media_url=raw_post.media_url if raw_post else None,
banner_image_url=draft.banner_image_url
)
if success:
queue_item.status = "success"
queue_item.telegram_msg_id = msg_id
draft.status = "published"
success_count += 1
else:
queue_item.status = "failed"
queue_item.error_log = error
queue_item.retry_count += 1
await session.commit()
return success_count
async def dispatch_single_queue_item(session: AsyncSession, queue_id: str) -> tuple[bool, str | None]:
stmt = (
select(PublishQueue, ContentDraft, RawPost)
.join(ContentDraft, PublishQueue.draft_id == ContentDraft.id)
.outerjoin(RawPost, ContentDraft.raw_post_id == RawPost.id)
.where(PublishQueue.id == queue_id)
)
res = (await session.execute(stmt)).first()
if not res:
return False, "Queue item not found"
queue_item, draft, raw_post = res
queue_item.status = "publishing"
await session.commit()
success, msg_id, error = await send_to_telegram(
text=ensure_official_links(draft.current_text),
target_channel=draft.brand_target or settings.TARGET_CHANNEL,
bot_token=settings.TELEGRAM_BOT_TOKEN,
media_type=raw_post.media_type if raw_post else "none",
media_url=raw_post.media_url if raw_post else None,
banner_image_url=draft.banner_image_url
)
if success:
queue_item.status = "success"
queue_item.telegram_msg_id = msg_id
draft.status = "published"
else:
queue_item.status = "failed"
queue_item.error_log = error
queue_item.retry_count += 1
await session.commit()
return success, error

View file

@ -0,0 +1,557 @@
import os
import re
import math
import hashlib
import logging
from typing import Optional, Tuple
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import arabic_reshaper
from bidi.algorithm import get_display
logger = logging.getLogger("banner_generator")
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
BANNER_DIR = os.path.join(BASE_DIR, "static", "banners")
FONTS_DIR = os.path.join(BASE_DIR, "static", "fonts")
os.makedirs(BANNER_DIR, exist_ok=True)
os.makedirs(FONTS_DIR, exist_ok=True)
FONT_BOLD = os.path.join(FONTS_DIR, "Vazirmatn-Bold.ttf")
FONT_REGULAR = os.path.join(FONTS_DIR, "Vazirmatn-Regular.ttf")
def persian_text(text: str) -> str:
"""Format and reshape Persian text for correct RTL and letter joining."""
if not text:
return ""
try:
reshaped = arabic_reshaper.reshape(text)
return get_display(reshaped)
except Exception:
return text
def get_font(path: str, size: int):
try:
if os.path.exists(path):
return ImageFont.truetype(path, size)
return ImageFont.load_default()
except Exception:
return ImageFont.load_default()
# --- VECTOR DRAWING HELPERS ---
def draw_gemini_sparkle(draw, center, size, color):
cx, cy = center
r_outer = size // 2
r_inner = size // 5
points = []
for i in range(8):
angle = i * math.pi / 4
r = r_outer if i % 2 == 0 else r_inner
x = cx + r * math.cos(angle)
y = cy + r * math.sin(angle)
points.append((x, y))
draw.polygon(points, fill=color)
def draw_vector_lock(draw, center, size, color):
cx, cy = center
body_w = int(size * 0.75)
body_h = int(size * 0.55)
bx1 = cx - body_w // 2
by1 = cy - body_h // 6
bx2 = cx + body_w // 2
by2 = by1 + body_h
draw.rounded_rectangle([bx1, by1, bx2, by2], radius=6, fill=color)
shackle_r = int(size * 0.28)
draw.arc([cx - shackle_r, by1 - shackle_r * 2 + 4, cx + shackle_r, by1 + 4], start=180, end=0, fill=color, width=4)
draw.ellipse([cx - 3, by1 + body_h // 3, cx + 3, by1 + body_h // 3 + 6], fill=(15, 23, 42, 255))
def draw_vector_check(draw, center, size, bg_color, check_color=(255, 255, 255)):
cx, cy = center
r = size // 2
draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=bg_color)
p1 = (cx - r * 0.45, cy)
p2 = (cx - r * 0.1, cy + r * 0.4)
p3 = (cx + r * 0.45, cy - r * 0.35)
draw.line([p1, p2], fill=check_color, width=3)
draw.line([p2, p3], fill=check_color, width=3)
def draw_vector_cross(draw, center, size, bg_color, cross_color=(255, 255, 255)):
cx, cy = center
r = size // 2
draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=bg_color)
d = r * 0.35
draw.line([(cx - d, cy - d), (cx + d, cy + d)], fill=cross_color, width=3)
draw.line([(cx - d, cy + d), (cx + d, cy - d)], fill=cross_color, width=3)
def draw_vector_shield(draw, center, size, color):
cx, cy = center
w = int(size * 0.8)
h = size
y1 = cy - h//2
y2 = cy + h//2
pts = [
(cx - w//2, y1),
(cx + w//2, y1),
(cx + w//2, cy + h*0.1),
(cx, y2),
(cx - w//2, cy + h*0.1)
]
draw.polygon(pts, fill=color)
def draw_vector_lightning(draw, center, size, color):
cx, cy = center
s = size // 2
pts = [
(cx + s*0.2, cy - s),
(cx - s*0.6, cy + s*0.05),
(cx - s*0.05, cy + s*0.05),
(cx - s*0.2, cy + s),
(cx + s*0.6, cy - s*0.05),
(cx + s*0.05, cy - s*0.05),
]
draw.polygon(pts, fill=color)
def create_radial_glow(width, height, center_x, center_y, radius, color):
glow = Image.new('RGBA', (width, height), (0, 0, 0, 0))
draw = ImageDraw.Draw(glow)
r, g, b, max_a = color
steps = 35
for i in range(steps, 0, -1):
cur_r = radius * (i / steps)
alpha = int(max_a * (1 - (i / steps)) ** 1.6)
draw.ellipse([center_x - cur_r, center_y - cur_r, center_x + cur_r, center_y + cur_r], fill=(r, g, b, alpha))
return glow.filter(ImageFilter.GaussianBlur(radius // 5))
def draw_rounded_glass_card(img, bbox, bg_color, border_color, radius=28, shadow=True):
x1, y1, x2, y2 = bbox
if shadow:
shadow_layer = Image.new('RGBA', img.size, (0, 0, 0, 0))
sdraw = ImageDraw.Draw(shadow_layer)
sdraw.rounded_rectangle([x1 + 4, y1 + 10, x2 - 4, y2 + 18], radius=radius, fill=(0, 0, 0, 130))
shadow_layer = shadow_layer.filter(ImageFilter.GaussianBlur(16))
img.alpha_composite(shadow_layer)
card_layer = Image.new('RGBA', img.size, (0, 0, 0, 0))
cdraw = ImageDraw.Draw(card_layer)
cdraw.rounded_rectangle([x1, y1, x2, y2], radius=radius, fill=bg_color, outline=border_color, width=2)
cdraw.line([(x1 + radius, y1 + 1), (x2 - radius, y1 + 1)], fill=(255, 255, 255, 60), width=2)
img.alpha_composite(card_layer)
def draw_pill_button(img, bbox, fill_grad_start, fill_grad_end, text, subtext=None, text_color='#000000'):
x1, y1, x2, y2 = bbox
# Clean ambient glow
shadow_layer = Image.new('RGBA', img.size, (0, 0, 0, 0))
sdraw = ImageDraw.Draw(shadow_layer)
sdraw.rounded_rectangle([x1 + 10, y1 + 10, x2 - 10, y2 + 20], radius=(y2 - y1)//2, fill=(fill_grad_start[0], fill_grad_start[1], fill_grad_start[2], 90))
shadow_layer = shadow_layer.filter(ImageFilter.GaussianBlur(14))
img.alpha_composite(shadow_layer)
btn = Image.new('RGBA', (x2 - x1, y2 - y1), (0, 0, 0, 0))
bdraw = ImageDraw.Draw(btn)
for y in range(y2 - y1):
ratio = y / (y2 - y1)
r = int(fill_grad_start[0] * (1 - ratio) + fill_grad_end[0] * ratio)
g = int(fill_grad_start[1] * (1 - ratio) + fill_grad_end[1] * ratio)
b = int(fill_grad_start[2] * (1 - ratio) + fill_grad_end[2] * ratio)
bdraw.line([(0, y), (x2 - x1, y)], fill=(r, g, b, 255))
mask = Image.new('L', (x2 - x1, y2 - y1), 0)
mdraw = ImageDraw.Draw(mask)
mdraw.rounded_rectangle([0, 0, x2 - x1, y2 - y1], radius=(y2 - y1)//2, fill=255)
img.paste(btn, (x1, y1), mask)
odraw = ImageDraw.Draw(img)
odraw.rounded_rectangle([x1, y1, x2, y2], radius=(y2 - y1)//2, outline=(255, 255, 255, 180), width=2)
f_btn = get_font(FONT_BOLD, 34)
odraw.text(((x1 + x2)//2, (y1 + y2)//2 - (10 if subtext else 0)), persian_text(text), font=f_btn, fill=text_color, anchor='mm')
if subtext:
f_sub = get_font(FONT_REGULAR, 20)
odraw.text(((x1 + x2)//2, (y1 + y2)//2 + 22), persian_text(subtext), font=f_sub, fill='#1F2937', anchor='mm')
# ==============================================================================
# 1. GEMINI PRO MASTER BANNER (1080x1080)
# ==============================================================================
def create_gemini_banner(
headline: str = "جهش چشمگیر در سرعت و کیفیت پروژه‌ها",
price_toman: str = "۶۰۰.۰۰۰ تومان",
is_discount: bool = True,
duration: str = "اشتراک ۱۸ ماهه اختصاصی"
) -> str:
"""
Renders high-end commercial 1080x1080 comparison banner for Google Gemini Pro:
- Side-by-side Free vs. Pro comparison cards
- Sharp vector icons (Sparkles, Padlock, Anti-aliased Checks & Crosses)
- Golden CTA pill with smooth lighting
"""
W, H = 1080, 1080
base = Image.new('RGBA', (W, H), (10, 14, 26, 255))
# Atmospheric glows
glow1 = create_radial_glow(W, H, 780, 470, 480, (147, 51, 234, 85))
glow2 = create_radial_glow(W, H, 300, 470, 360, (59, 130, 246, 40))
glow3 = create_radial_glow(W, H, 540, 910, 400, (245, 158, 11, 60))
base.alpha_composite(glow1)
base.alpha_composite(glow2)
base.alpha_composite(glow3)
draw = ImageDraw.Draw(base)
# Top Category Pill
badge_w, badge_h = 440, 46
bx1, by1 = (W - badge_w)//2, 45
draw_rounded_glass_card(base, [bx1, by1, bx1 + badge_w, by1 + badge_h], (30, 41, 59, 180), (71, 85, 105, 160), radius=23, shadow=False)
draw_gemini_sparkle(draw, (bx1 + 35, by1 + 23), 22, (245, 158, 11))
f_badge = get_font(FONT_BOLD, 21)
draw.text((W // 2 + 10, by1 + 23), persian_text("پیشنهاد ویژه اشتراک رسمی هوش مصنوعی"), font=f_badge, fill='#38BDF8', anchor='mm')
# Main Headline
f_title = get_font(FONT_BOLD, 50)
f_sub = get_font(FONT_REGULAR, 23)
draw.text((W // 2, 132), persian_text(headline), font=f_title, fill='#FFFFFF', anchor='mm')
draw.text((W // 2, 186), persian_text("مقایسه نسخه رایگان با اشتراک اختصاصی ۱۸ ماهه Google Gemini Pro"), font=f_sub, fill='#94A3B8', anchor='mm')
# Card dimensions
card_w = 465
card_h = 590
card_top = 230
# --- LEFT CARD: FREE ---
lx1 = 55
lx2 = lx1 + card_w
ly1 = card_top
ly2 = ly1 + card_h
draw_rounded_glass_card(base, [lx1, ly1, lx2, ly2], (15, 23, 42, 220), (51, 65, 85, 180), radius=30)
draw.rounded_rectangle([lx1 + 30, ly1 + 28, lx1 + 90, ly1 + 88], radius=18, fill=(30, 41, 59, 255), outline=(71, 85, 105, 180), width=1)
draw_vector_lock(draw, (lx1 + 60, ly1 + 58), 34, (148, 163, 184))
f_card_title = get_font(FONT_BOLD, 30)
f_tier = get_font(FONT_BOLD, 20)
f_item = get_font(FONT_REGULAR, 21)
draw.text((lx2 - 35, ly1 + 45), persian_text("نسخه معمولی"), font=f_card_title, fill='#E2E8F0', anchor='rm')
draw.text((lx2 - 35, ly1 + 76), persian_text("امکانات محدود و پایه"), font=f_tier, fill='#64748B', anchor='rm')
draw.line([(lx1 + 30, ly1 + 110), (lx2 - 30, ly1 + 110)], fill=(51, 65, 85, 180), width=1)
free_items = [
"محدودیت تعداد پرسش در هر ساعت",
"عدم دسترسی به هوش مصنوعی 1.5 Pro",
"بدون فضای ابری ۲ ترابایتی گوگل",
"پایداری ضعیف در زمان اوج ترافیک",
"پاسخ‌های کوتاه با عمق تحلیلی کم",
"عدم اتصال به Docs و Google Drive",
]
cur_y = ly1 + 155
for item in free_items:
draw_vector_cross(draw, (lx2 - 25, cur_y), 24, (239, 68, 68), (255, 255, 255))
draw.text((lx2 - 50, cur_y), persian_text(item), font=f_item, fill='#94A3B8', anchor='rm')
cur_y += 58
# Left bottom footer badge
draw.rounded_rectangle([lx1 + 35, ly2 - 75, lx2 - 35, ly2 - 25], radius=15, fill=(30, 41, 59, 230), outline=(51, 65, 85, 200), width=1)
draw.text(((lx1 + lx2)//2, ly2 - 50), persian_text("پلن پایه: رایگان"), font=get_font(FONT_BOLD, 21), fill='#94A3B8', anchor='mm')
# --- RIGHT CARD: GEMINI PRO (PREMIUM) ---
rx1 = W - 55 - card_w
rx2 = rx1 + card_w
ry1 = card_top
ry2 = ry1 + card_h
draw_rounded_glass_card(base, [rx1, ry1, rx2, ry2], (24, 18, 45, 240), (168, 85, 247, 230), radius=30)
draw.line([(rx1 + 30, ry1 + 2), (rx2 - 30, ry1 + 2)], fill=(245, 158, 11, 255), width=3)
draw.rounded_rectangle([rx1 + 30, ry1 + 28, rx1 + 90, ry1 + 88], radius=18, fill=(88, 28, 135, 255), outline=(216, 180, 254, 200), width=1)
draw_gemini_sparkle(draw, (rx1 + 60, ry1 + 58), 40, (245, 158, 11))
draw.text((rx2 - 35, ry1 + 45), persian_text("Google Gemini Pro"), font=f_card_title, fill='#FFFFFF', anchor='rm')
draw.text((rx2 - 35, ry1 + 76), persian_text("اشتراک رسمی و قانونی ۱۸ ماهه"), font=f_tier, fill='#F59E0B', anchor='rm')
draw.line([(rx1 + 30, ry1 + 110), (rx2 - 30, ry1 + 110)], fill=(107, 33, 168, 200), width=1)
pro_items = [
"دسترسی ۱۸ ماهه نامحدود و رسمی",
"پیشرفته‌ترین مدل استدلال 1.5 Pro",
"۲ ترابایت فضای ابری Google One",
"فعال‌سازی ایمن و قانونی روی جیمیل شما",
"پایداری ۱۰۰٪ بدون قطعی در تمام ساعات",
"یکپارچگی مستقیم با Docs و Drive",
]
cur_y = ry1 + 155
for item in pro_items:
draw_vector_check(draw, (rx2 - 25, cur_y), 24, (16, 185, 129), (255, 255, 255))
draw.text((rx2 - 50, cur_y), persian_text(item), font=f_item, fill='#F8FAFC', anchor='rm')
cur_y += 58
# Right bottom footer: Balanced with left card
draw.rounded_rectangle([rx1 + 35, ly2 - 75, rx2 - 35, ly2 - 25], radius=15, fill=(76, 29, 149, 230), outline=(216, 180, 254, 200), width=1)
f_orig = get_font(FONT_REGULAR, 17)
f_cur = get_font(FONT_BOLD, 22)
orig_str = persian_text("۱.۵۰۰.۰۰۰ تومان")
cur_str = persian_text(f"قیمت تخفیفی: {price_toman}")
draw.text((rx2 - 40, ly2 - 50), cur_str, font=f_cur, fill='#FCD34D', anchor='rm')
draw.text((rx1 + 40, ly2 - 50), orig_str, font=f_orig, fill='#94A3B8', anchor='lm')
# Strike through line at exact vertical center
ow = draw.textlength(orig_str, font=f_orig)
draw.line([(rx1 + 40, ly2 - 50), (rx1 + 40 + ow, ly2 - 50)], fill=(239, 68, 68, 255), width=2)
# --- BOTTOM CTA BUTTON ---
btn_w = 660
btn_h = 100
bx1 = (W - btn_w)//2
by1 = 855
bx2 = bx1 + btn_w
by2 = by1 + btn_h
draw_pill_button(base, [bx1, by1, bx2, by2],
fill_grad_start=(245, 158, 11),
fill_grad_end=(251, 191, 36),
text="سفارش و تحویل فوری اشتراک ۱۸ ماهه",
subtext=f"تخفیف ویژه ۶۰ درصدی • فقط {price_toman} • تحویل فوری",
text_color='#0B0F19')
# FOOTER CONTACT
f_footer = get_font(FONT_BOLD, 22)
draw.text((W // 2, 995), persian_text("سفارش و مشاوره فوری: NetVibe_admin@ • کانال رسمی: NetVibe_VPN@"), font=f_footer, fill='#94A3B8', anchor='mm')
final_img = Image.new('RGB', (W, H), (10, 14, 26))
final_img.paste(base, (0, 0), base)
# Save banner
content_str = f"gemini_{headline}_{price_toman}_{duration}"
img_hash = hashlib.md5(content_str.encode()).hexdigest()[:10]
out_filename = f"gemini_banner_{img_hash}.png"
out_png_path = os.path.join(BANNER_DIR, out_filename)
final_img.save(out_png_path, "PNG", quality=95)
logger.info(f"Generated premium Gemini banner: {out_png_path}")
return f"/static/banners/{out_filename}"
# ==============================================================================
# 2. VPN SERVICE MASTER BANNER (1080x1080)
# ==============================================================================
def create_vpn_banner(
title: str = "اتصال پرسرعت، پایدار و بدون قطعی",
subtitle: str = "مناسب اینستاگرام، تلگرام، ترید، یوتیوب و وب‌گردی با پینگ فوق‌العاده",
topic_badge: str = "⚡ سرویس اینترنت آزاد و پایدار NetVibe",
card1_title: str = "پلن ۲ کاربره نامحدود",
card1_sub: str = "۳۰۰.۰۰۰ تومان • یک‌ماهه",
card2_title: str = "پلن ۳ کاربره نامحدود",
card2_sub: str = "۳۵۰.۰۰۰ تومان • یک‌ماهه",
card3_title: str = "حجم کاملاً نامحدود ♾️",
card3_sub: str = "سوییچ هوشمند • ساب‌لینک",
brand: str = "@NetVibe_VPN"
) -> str:
"""
Renders modern 1080x1080 comparison banner for NetVibe VPN plans:
- Plan 2-User: 300,000 Tomans
- Plan 3-User: 350,000 Tomans (Featured & Best-seller)
- Cyan & Violet cyberpunk aesthetic
"""
W, H = 1080, 1080
base = Image.new('RGBA', (W, H), (11, 15, 28, 255))
glow1 = create_radial_glow(W, H, 300, 480, 450, (6, 182, 212, 65))
glow2 = create_radial_glow(W, H, 780, 480, 450, (139, 92, 246, 75))
glow3 = create_radial_glow(W, H, 540, 910, 380, (16, 185, 129, 50))
base.alpha_composite(glow1)
base.alpha_composite(glow2)
base.alpha_composite(glow3)
draw = ImageDraw.Draw(base)
# Top Category Pill
badge_w, badge_h = 420, 46
bx1, by1 = (W - badge_w)//2, 45
draw_rounded_glass_card(base, [bx1, by1, bx1 + badge_w, by1 + badge_h], (30, 41, 59, 180), (71, 85, 105, 160), radius=23, shadow=False)
draw_vector_shield(draw, (bx1 + 35, by1 + 23), 22, (6, 182, 212))
f_badge = get_font(FONT_BOLD, 21)
draw.text((W // 2 + 10, by1 + 23), persian_text("سرویس اینترنت پرسرعت و پایدار NetVibe"), font=f_badge, fill='#38BDF8', anchor='mm')
# Main Headline
f_title = get_font(FONT_BOLD, 50)
f_sub = get_font(FONT_REGULAR, 23)
draw.text((W // 2, 132), persian_text(title), font=f_title, fill='#FFFFFF', anchor='mm')
draw.text((W // 2, 186), persian_text(subtitle), font=f_sub, fill='#94A3B8', anchor='mm')
# Card dimensions
card_w = 465
card_h = 590
card_top = 230
# --- LEFT CARD: PLAN 2-USER ---
lx1 = 55
lx2 = lx1 + card_w
ly1 = card_top
ly2 = ly1 + card_h
draw_rounded_glass_card(base, [lx1, ly1, lx2, ly2], (15, 23, 42, 230), (14, 165, 233, 200), radius=30)
draw.rounded_rectangle([lx1 + 30, ly1 + 28, lx1 + 90, ly1 + 88], radius=18, fill=(12, 74, 110, 255), outline=(56, 189, 248, 180), width=1)
draw_vector_shield(draw, (lx1 + 60, ly1 + 58), 34, (56, 189, 248))
f_card_title = get_font(FONT_BOLD, 30)
f_tier = get_font(FONT_BOLD, 20)
f_item = get_font(FONT_REGULAR, 21)
draw.text((lx2 - 35, ly1 + 45), persian_text(card1_title), font=f_card_title, fill='#FFFFFF', anchor='rm')
draw.text((lx2 - 35, ly1 + 76), persian_text("مناسب استفاده دو دستگاه همزمان"), font=f_tier, fill='#38BDF8', anchor='rm')
draw.line([(lx1 + 30, ly1 + 110), (lx2 - 30, ly1 + 110)], fill=(14, 116, 144, 180), width=1)
plan2_items = [
"حجم کاملاً نامحدود بدون سقف مصرف",
"سازگار با همراه اول، ایرانسل و وای‌فای",
"اتصال آنی و پایدار بدون افت سرعت",
"اتصال فوق‌العاده روان و بدون قطعی در ساعات اوج",
"حفظ کامل حریم خصوصی و امنیت داده‌ها",
"پشتیبانی فعال ۲۴ ساعته تا انتهای اشتراک",
]
cur_y = ly1 + 155
for item in plan2_items:
draw_vector_check(draw, (lx2 - 25, cur_y), 24, (14, 165, 233), (255, 255, 255))
draw.text((lx2 - 50, cur_y), persian_text(item), font=f_item, fill='#E2E8F0', anchor='rm')
cur_y += 58
# Price at bottom of Plan 2
draw.rounded_rectangle([lx1 + 35, ly2 - 75, lx2 - 35, ly2 - 25], radius=15, fill=(12, 74, 110, 230), outline=(56, 189, 248, 180), width=1)
draw.text(((lx1 + lx2)//2, ly2 - 50), persian_text("ماهانه: ۳۰۰.۰۰۰ تومان"), font=get_font(FONT_BOLD, 21), fill='#FFFFFF', anchor='mm')
# --- RIGHT CARD: PLAN 3-USER (FEATURED) ---
rx1 = W - 55 - card_w
rx2 = rx1 + card_w
ry1 = card_top
ry2 = ry1 + card_h
draw_rounded_glass_card(base, [rx1, ry1, rx2, ry2], (26, 19, 52, 240), (168, 85, 247, 230), radius=30)
draw.line([(rx1 + 30, ry1 + 2), (rx2 - 30, ry1 + 2)], fill=(245, 158, 11, 255), width=3)
draw.rounded_rectangle([rx1 + 30, ry1 + 28, rx1 + 90, ry1 + 88], radius=18, fill=(88, 28, 135, 255), outline=(216, 180, 254, 200), width=1)
draw_vector_lightning(draw, (rx1 + 60, ry1 + 58), 34, (245, 158, 11))
draw.text((rx2 - 35, ry1 + 45), persian_text(card2_title), font=f_card_title, fill='#FFFFFF', anchor='rm')
draw.text((rx2 - 35, ry1 + 76), persian_text("⭐ پرفروش‌ترین و اقتصادی‌ترین پلن"), font=f_tier, fill='#F59E0B', anchor='rm')
draw.line([(rx1 + 30, ry1 + 110), (rx2 - 30, ry1 + 110)], fill=(107, 33, 168, 200), width=1)
plan3_items = [
"اتصال ۳ دستگاه همزمان با حجم نامحدود",
"سرورهای اختصاصی با بالاترین پهنای باند",
"بدون قطعی و افت سرعت در اینترنت ملی",
"سازگار با Android, iOS, Windows, Mac",
"آی‌پی ثابت مناسب ترید و بایننس",
"تضمین بازگشت وجه در صورت عدم رضایت",
]
cur_y = ry1 + 155
for item in plan3_items:
draw_vector_check(draw, (rx2 - 25, cur_y), 24, (168, 85, 247), (255, 255, 255))
draw.text((rx2 - 50, cur_y), persian_text(item), font=f_item, fill='#F8FAFC', anchor='rm')
cur_y += 58
# Price at bottom of Plan 3
draw.rounded_rectangle([rx1 + 35, ly2 - 75, rx2 - 35, ly2 - 25], radius=15, fill=(76, 29, 149, 230), outline=(216, 180, 254, 200), width=1)
draw.text(((rx1 + rx2)//2, ly2 - 50), persian_text("ماهانه: ۳۵۰.۰۰۰ تومان"), font=get_font(FONT_BOLD, 21), fill='#FCD34D', anchor='mm')
# --- BOTTOM CTA BUTTON ---
btn_w = 660
btn_h = 100
bx1 = (W - btn_w)//2
by1 = 855
bx2 = bx1 + btn_w
by2 = by1 + btn_h
draw_pill_button(base, [bx1, by1, bx2, by2],
fill_grad_start=(16, 185, 129),
fill_grad_end=(52, 211, 153),
text="تحویل آنی و تست اتصال قبل از پرداخت",
subtext="پشتیبانی ۲۴ ساعته و کانفیگ رایگان تمام پلتفرم‌ها",
text_color='#062D1F')
# FOOTER CONTACT
f_footer = get_font(FONT_BOLD, 22)
draw.text((W // 2, 995), persian_text(f"ثبت سفارش و دریافت تست: NetVibe_admin@ • کانال رسمی: {brand}"), font=f_footer, fill='#94A3B8', anchor='mm')
final_img = Image.new('RGB', (W, H), (11, 15, 28))
final_img.paste(base, (0, 0), base)
# Save banner
content_str = f"vpn_{title}_{card1_title}_{card2_title}_{brand}"
img_hash = hashlib.md5(content_str.encode()).hexdigest()[:10]
out_filename = f"vpn_banner_{img_hash}.png"
out_png_path = os.path.join(BANNER_DIR, out_filename)
final_img.save(out_png_path, "PNG", quality=95)
logger.info(f"Generated premium VPN banner: {out_png_path}")
return f"/static/banners/{out_filename}"
# ==============================================================================
# 3. BANNER POOL SELECTION HELPERS (Custom Pool with Fallback)
# ==============================================================================
import random
POOL_DIR = os.path.join(BASE_DIR, "static", "banner_pool")
GEMINI_POOL_DIR = os.path.join(POOL_DIR, "gemini")
VPN_POOL_DIR = os.path.join(POOL_DIR, "vpn")
def get_gemini_banner_from_pool_or_generate(
headline: str = "جهش چشمگیر در سرعت و کیفیت پروژه‌ها",
price_toman: str = "۶۰۰.۰۰۰ تومان",
is_discount: bool = True,
banner_type: str = "discount_600k" # 'discount_600k', 'multi_tier_6gmail', or 'any'
) -> str:
"""
STRICTLY selects from the user's uploaded Gemini banners.
Does NOT generate procedural banners for Gemini.
- 'discount_600k': selects between Gemini_Pro_600k_Discount_Laptop.png and Gemini_Pro_600k_Discount_Robot.png
- 'multi_tier_6gmail': selects Gemini_Pro_Multi_Tier_6Gmail.png
"""
valid_extensions = ('.png', '.jpg', '.jpeg', '.webp')
if os.path.exists(GEMINI_POOL_DIR):
pool_files = [f for f in os.listdir(GEMINI_POOL_DIR) if f.lower().endswith(valid_extensions)]
if pool_files:
filtered = []
if banner_type == "discount_999k":
filtered = [f for f in pool_files if "999k" in f.lower()]
elif banner_type == "discount_1200k":
filtered = [f for f in pool_files if "1200k" in f.lower()]
elif banner_type == "multi_tier_6gmail":
filtered = [f for f in pool_files if "6gmail" in f.lower() and "1200k" not in f.lower() and "999k" not in f.lower()]
elif banner_type == "discount_600k":
filtered = [f for f in pool_files if ("600k" in f.lower() or "discount" in f.lower()) and "1200k" not in f.lower() and "999k" not in f.lower() and "multi" not in f.lower()]
chosen_list = filtered if filtered else pool_files
chosen = random.choice(chosen_list)
logger.info(f"Strictly using user-provided Gemini banner: {chosen} (type: {banner_type})")
return f"/static/banner_pool/gemini/{chosen}"
# Static hardcoded fallback to user images if dir scan has any issue
if banner_type == "discount_999k":
return "/static/banner_pool/gemini/Gemini_Pro_999k_Discount_Holo_Pedestal_6Gmail.png"
if banner_type == "discount_1200k":
return random.choice([
"/static/banner_pool/gemini/Gemini_Pro_1200k_Discount_Robot_6Gmail.png",
"/static/banner_pool/gemini/Gemini_Pro_1200k_Discount_Gold_Pedestal_6Gmail.png"
])
if banner_type == "multi_tier_6gmail":
return "/static/banner_pool/gemini/Gemini_Pro_Multi_Tier_6Gmail.png"
return random.choice([
"/static/banner_pool/gemini/Gemini_Pro_600k_Discount_Laptop.png",
"/static/banner_pool/gemini/Gemini_Pro_600k_Discount_Robot.png"
])
def get_vpn_banner_from_pool_or_generate(
title: str = "اتصال پرسرعت، پایدار و بدون قطعی",
card1_title: str = "پلن ۲ کاربره نامحدود",
card2_title: str = "پلن ۳ کاربره نامحدود",
brand: str = "@NetVibe_VPN"
) -> str:
"""
Selects a banner from the user-uploaded VPN Banner Pool, or dynamically generates one.
"""
if os.path.exists(VPN_POOL_DIR):
valid_extensions = ('.png', '.jpg', '.jpeg', '.webp')
pool_files = [f for f in os.listdir(VPN_POOL_DIR) if f.lower().endswith(valid_extensions)]
if pool_files:
chosen = random.choice(pool_files)
logger.info(f"Selected VPN banner from pool: {chosen} (pool size: {len(pool_files)})")
return f"/static/banner_pool/vpn/{chosen}"
return create_vpn_banner(title=title, card1_title=card1_title, card2_title=card2_title, brand=brand)

View file

@ -0,0 +1,57 @@
import os
from typing import List
from pydantic_settings import BaseSettings
def get_env_secret(key: str, default: str = "") -> str:
val = os.getenv(key)
if val:
return val
# Fallback to ~/.hermes/.env
env_path = os.path.expanduser("~/.hermes/.env")
if os.path.exists(env_path):
try:
with open(env_path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line.startswith(f"{key}="):
return line.split("=", 1)[1].strip().strip('"').strip("'")
except Exception:
pass
return default
class Settings(BaseSettings):
PROJECT_NAME: str = "NetVibe Telegram Content Automation"
API_V1_STR: str = "/api/v1"
# Database
DATABASE_URL: str = os.getenv(
"DATABASE_URL",
"sqlite+aiosqlite:///./vpn_pipeline.db"
)
# Telegram Bot
TELEGRAM_BOT_TOKEN: str = get_env_secret("TELEGRAM_BOT_TOKEN", "")
TARGET_CHANNEL: str = os.getenv("TARGET_CHANNEL", "@NetVibe_VPN")
# LLM Settings
OPENAI_API_BASE: str = get_env_secret("OPENAI_API_BASE", "https://router.zebellkhan.com/v1")
OPENAI_API_KEY: str = get_env_secret("OPENAI_API_KEY") or get_env_secret("NINEROUTER_API_KEY", "")
OPENAI_MODEL: str = os.getenv("OPENAI_MODEL", "01")
# Scheduling & Automation
SCRAPE_INTERVAL_HOURS: int = 6
PUBLISH_CHECK_INTERVAL_SECONDS: int = 60
# CORS
CORS_ORIGINS: List[str] = [
"http://localhost:3000",
"http://127.0.0.1:3000",
"https://netvibe.ehsan.test.zebellkhan.com",
"*"
]
class Config:
env_file = ".env"
extra = "ignore"
settings = Settings()

View file

@ -0,0 +1,61 @@
import uuid
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import declarative_base
from sqlalchemy.types import TypeDecorator, CHAR
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from app.config import settings
# GUID type decorator that maps to PG_UUID on Postgres and CHAR(36) on SQLite
class GUID(TypeDecorator):
impl = CHAR
cache_ok = True
def load_dialect_impl(self, dialect):
if dialect.name == "postgresql":
return dialect.type_descriptor(PG_UUID(as_uuid=True))
else:
return dialect.type_descriptor(CHAR(36))
def process_bind_param(self, value, dialect):
if value is None:
return value
elif dialect.name == "postgresql":
return str(value)
else:
if not isinstance(value, uuid.UUID):
return str(uuid.UUID(str(value)))
return str(value)
def process_result_value(self, value, dialect):
if value is None:
return value
if not isinstance(value, uuid.UUID):
return uuid.UUID(str(value))
return value
engine = create_async_engine(
settings.DATABASE_URL,
echo=False,
future=True
)
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False
)
Base = declarative_base()
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()
async def init_db():
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)

View file

@ -0,0 +1,231 @@
"""
Gemini Pro High-Converting Copywriting & Content Engine
Provides diverse marketing angles (Devs, Researchers, Content Creators, Agencies, Business)
and handles countdown/urgency timing for the 600k Toman promotion.
"""
import random
from datetime import datetime, timedelta
# Persian digits helper
def to_persian_num(n: int or str) -> str:
en_to_fa = str.maketrans("0123456789", "۰۱۲۳۴۵۶۷۸۹")
return str(n).translate(en_to_fa)
def get_campaign_deadline_text(hours_remaining: int = 48) -> dict:
"""
Computes an dynamic urgency text with specific Iranian date & time.
"""
now = datetime.now()
deadline = now + timedelta(hours=hours_remaining)
persian_weekdays = {
0: "دوشنبه",
1: "سه‌شنبه",
2: "چهارشنبه",
3: "پنج‌شنبه",
4: "جمعه",
5: "شنبه",
6: "یکشنبه"
}
day_name = persian_weekdays.get(deadline.weekday(), "جمعه")
time_str = "۲۴:۰۰"
return {
"hours": hours_remaining,
"deadline_phrase": f"تا پایان {day_name} ساعت {time_str}",
"warning_text": (
f"⏰ مهلت تخفیف استثنایی ۶۰۰.۰۰۰ تومان: فقط تا {day_name} ساعت {time_str} (ظرفیت رو به اتمام)\n"
f"⚠️ پس از پایان زمان جشنواره، ثبت سفارش صرفاً با قیمت رسمی ۱.۵۰۰.۰۰۰ تومان انجام خواهد شد."
)
}
# 6 Rich, highly-converting copywriting templates for Gemini Pro
GEMINI_ANGLES = [
{
"id": "programmers_coders",
"name": "توسعه‌دهندگان و برنامه‌نویسان",
"banner_type": "discount_600k",
"generate": lambda deadline: (
f"💻 برنامه‌نویس هستی و هنوز درگیر کدهای باگ‌دار و سینتکس‌های طولانی می‌شی؟\n\n"
f"اشتراک رسمی Google Gemini Pro 1.5 همون دستیار ارشد هوشمندی هست که سرعت کدنویسی‌ت رو ۵ برابر می‌کنه:\n\n"
f"▫️ پنجره کانتکست عظیم (۲ میلیون توکن): کل ریپازیتوری یا داکیومنت ۱۰۰۰ صفحه‌ای رو یکجا بهش بده!\n"
f"▫️ دیباگ آنی، ریفکتور تمیز و تبدیل کدهای پایتون، جاوااسکریپت، Go و...\n"
f"▫️ فعال‌سازی ۱۰۰٪ شخصی و بدون دغدغه روی جیمیل خودت (بدون شماره مجازی)\n"
f"▫️ اعتبار کامل ۱۸ ماهه بدون قطعی و مسدودی اکانت\n\n"
f"💰 قیمت رسمی گوگل: ۱.۵۰۰.۰۰۰ تومان\n"
f"🔥 قیمت در آف ویژه برنامه‌نویسان: ۶۰۰.۰۰۰ تومان!\n\n"
f"{deadline['warning_text']}\n\n"
f"💡 نکته جذاب: همین بنری که در تصویر مشاهده می‌کنید به طور کامل با هوش مصنوعی جمنای خلق شده است!\n\n"
f"مشاوره و فعال‌سازی فوری در کمتر از ۵ دقیقه:\n"
f"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
f"🌐 کانال تلگرام: https://t.me/NetVibe_VPN"
)
},
{
"id": "researchers_students",
"name": "دانشجویان، پژوهشگران و نگارش مقاله",
"banner_type": "discount_600k",
"generate": lambda deadline: (
f"📚 برای نگارش پایان‌نامه، مقاله ISI و تحلیل منابع وقت کم آوردی؟\n\n"
f"هوش مصنوعی Google Gemini Pro ابزار طلایی دانشجویان و پژوهشگران حرفه‌ای:\n\n"
f"▫️ آنالیز عمیق فایل‌های سنگین PDF، کتاب‌ها و مقالات علمی به زبان فارسی روان\n"
f"▫️ استخراج نکات کلیدی، رفرنس‌دهی و ترجمه تخصصی متون دانشگاهی\n"
f"▫️ درک کامل جداول، نمودارها و تصاویر علمی پیچیده\n"
f"▫️ اشتراک ۱۸ ماهه پایدار، بدون تحریم و بدون نیاز به دور زدن شماره مجازی\n\n"
f"💰 قیمت معمول بازار: ۱.۵۰۰.۰۰۰ تومان\n"
f"🔥 قیمت جشنواره ویژه جامعه دانشگاهی: فقط ۶۰۰.۰۰۰ تومان!\n\n"
f"{deadline['warning_text']}\n\n"
f"🎨 بنر این پست تماماً با جمنای طراحی شده تا قدرت این غول هوش مصنوعی رو لمس کنید!\n\n"
f"جهت فعال‌سازی مستقیم روی جیمیل شخصی:\n"
f"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
f"🌐 کانال تلگرام: https://t.me/NetVibe_VPN"
)
},
{
"id": "content_creators_marketers",
"name": "تولیدکنندگان محتوا و ادمین‌های سوشال",
"banner_type": "discount_600k",
"generate": lambda deadline: (
f"🚀 بمب ایده‌پردازی و تولید محتوا: Gemini Pro دستیار ۲۴ ساعته شما!\n\n"
f"اگر ادمین، یوتیوبر، نویسنده یا طراح هستی، با هوش مصنوعی گوگل چند گام جلوتر باش:\n\n"
f"▫️ سناریونویسی دقیق برای ریلز، یوتیوب و پست‌های پربازدید اینستاگرام\n"
f"▫️ نگارش کپی‌های تبلیغاتی فوق‌العاده جذاب و سئو محور\n"
f"▫️ ایده‌پردازی تصویری، ساخت پرامپت‌های گرافیکی و تحلیل رقبا\n"
f"▫️ بدون محدودیت و بدون قطعی در طول ۱۸ ماه کامل\n\n"
f"💰 هزینه خرید اکانت: ۱.۵۰۰.۰۰۰ تومان\n"
f"🔥 قیمت در تخفیف زمان‌دار: ۶۰۰.۰۰۰ تومان!\n\n"
f"{deadline['warning_text']}\n\n"
f"💡 نمونه کار بصری: این پوستر نئونی جذاب با استفاده از قابلیت‌های پیشرفته جمنای ساخته شده است.\n\n"
f"سفارش و تحویل آنی:\n"
f"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
f"🌐 کانال تلگرام: https://t.me/NetVibe_VPN"
)
},
{
"id": "team_6gmails_agency",
"name": "پکیج تیمی و چندکاربره (۱ اکانت = ۶ جیمیل)",
"banner_type": "multi_tier_6gmail",
"generate": lambda deadline: (
f"🌐 یک اکانت، ۶ جیمیل مجزا! انقلابی‌ترین پکیج Gemini Pro برای تیم‌ها و دوستان\n\n"
f"چرا برای هر نفر جداگانه هزینه کنی؟ با تهیه این پکیج بی‌نظیر، ۶ اکانت مستقل جیمیل را همزمان مجهز کنید:\n\n"
f"▫️ اتصال مستقل به ۶ جیمیل مجزا (با حفظ ۱۰۰٪ حریم خصوصی هر فرد)\n"
f"▫️ هر کاربر دسترسی نامحدود به جمنای پرو ۱۸ ماهه خواهد داشت\n"
f"▫️ مناسب فریلنسرها، تیم‌های استارتاپی، آژانس‌ها و جمع‌های دانشجویی\n"
f"▫️ پوشش کامل کدنویسی، تحلیل ویدیو، صوت و پردازش اسناد سنگین\n\n"
f"💰 قیمت اصلی پکیج: ۱.۵۰۰.۰۰۰ تومان\n"
f"👑 بسته‌های تخفیف‌دار متناسب با بودجه شما:\n"
f"▫️ پلن جشنواره‌ای: ۶۰۰,۰۰۰ تومان (هر جیمیل فقط ۱۰۰ هزار تومن!)\n"
f"▫️ پلن طلایی پشتیبانی ویژه: ۹۹۹,۰۰۰ تومان\n"
f"▫️ پلن جامع بدون محدودیت: ۱,۲۰۰,۰۰۰ تومان\n\n"
f"⏰ هشدار ظرفیت: این پکیج ۶ جیمیل به دلیل ظرفیت اشتراکی، محدود بوده و پس از اتمام به قیمت پایه ۱.۵۰۰.۰۰۰ بازمی‌گردد.\n\n"
f"🎨 بنر اینفوگرافیک بالا ۱۰۰٪ با هوش مصنوعی جمنای طراحی شده است.\n\n"
f"مشاوره و فعال‌سازی فوری:\n"
f"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
f"🌐 کانال تلگرام: https://t.me/NetVibe_VPN"
)
},
{
"id": "business_executive_productivity",
"name": "مدیران، بیزینس و تحلیل داده",
"banner_type": "discount_600k",
"generate": lambda deadline: (
f"📊 دستیار هوشمند اجرایی در کنار شما: بهره‌وری کسب‌وکارتان را دگرگون کنید!\n\n"
f"اشتراک رسمی Google Gemini Pro 18 Months برای مدیران و تصمیم‌گیران:\n\n"
f"▫️ تحلیل فوری فایل‌های حجیم اکسل، داده‌های مالی و گزارش‌های فصلی\n"
f"▫️ پاسخگویی و نگارش ایمیل‌های تجاری بین‌المللی با لحن رسمی و متقاعدکننده\n"
f"▫️ خلاصه کردن جلسات صوتی و ویدیوهای طولانی در چند ثانیه\n"
f"▫️ امنیت و حفظ محرمانگی: فعال‌سازی بدون واسطه روی جیمیل شخصی سازمان یا خودتان\n\n"
f"💰 بهای واقعی اشتراک: ۱.۵۰۰.۰۰۰ تومان\n"
f"🔥 نرخ تشویقی جشنواره: ۶۰۰.۰۰۰ تومان!\n\n"
f"{deadline['warning_text']}\n\n"
f"💡 گواه قدرت تصویرسازی: همین پوستر نئونی با ابزارهای هوش مصنوعی جمنای ساخته شده است.\n\n"
f"جهت مشاوره تجاری و ثبت سفارش:\n"
f"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
f"🌐 کانال تلگرام: https://t.me/NetVibe_VPN"
)
},
{
"id": "discount_999k_holo_6gmail",
"name": "پلن ویژه ۹۹۹.۰۰۰ تومان (۱۸ ماهه + ۶ جیمیل)",
"banner_type": "discount_999k",
"generate": lambda deadline: (
f"🔮 شاهکار هوش مصنوعی گوگل در دستان شما: Google Gemini Pro با آفر باورنکردنی!\n\n"
f"ارتقای لول کارها و پروژه‌ها با قوی‌ترین دستیار هوشمند جهان در یک جشنواره استثنایی:\n\n"
f"💎 امکانات پکیج اختصاصی:\n"
f"▫️ اتصال به ۶ جیمیل مجزا (استفاده همزمان، کاملاً تفکیک‌شده و مستقل)\n"
f"▫️ فعال‌سازی ۱۰۰٪ قانونی و تضمینی روی جیمیل شخصی شما\n"
f"▫️ درک کامل و بی‌نقص عکس، صوت، ویدیو و فایل‌های سنگین تحلیلی\n"
f"▫️ کدنویسی پیشرفته، تبدیل زبان‌های برنامه‌نویسی و حل مسائل پیچیده\n"
f"▫️ پشتیبانی تخصصی از نگارش پایان‌نامه، تحلیل داده و مقالات دانشگاهی\n"
f"▫️ ۱۸ ماه اعتبار بدون قطعی و بدون نیاز به تحریم‌شکن و شماره مجازی\n\n"
f"💰 قیمت رسمی بازار: ۱.۵۰۰.۰۰۰ تومان\n"
f"🔥 قیمت در آف طلایی: ۹۹۹.۰۰۰ تومان! (هر کاربر فقط ۱۶۶ هزار تومن برای ۱۸ ماه)\n\n"
f"⏰ مهلت جشنواره: این تخفیف تنها برای تعداد محدودی اکانت فعال است و پس از آن به ۱.۵۰۰.۰۰۰ تومان بازخواهد گشت.\n\n"
f"🎨 بنر فضایی بالا ۱۰۰٪ با هوش مصنوعی جمنای تصویرسازی شده است.\n\n"
f"مشاوره و خرید سریع:\n"
f"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
f"🌐 کانال تلگرام: https://t.me/NetVibe_VPN"
)
},
{
"id": "discount_1200k_robot_6gmail",
"name": "پلن ویژه ۱.۲۰۰.۰۰۰ تومان (۱۸ ماهه + ۶ جیمیل)",
"banner_type": "discount_1200k",
"generate": lambda deadline: (
f"🚀 ارتقای لول کارها و پروژه‌ها با Google Gemini Pro (طرح فوق‌العاده ۱۸ ماهه)\n\n"
f"اگر به دنبال دسترسی همه‌جانبه، قانونی و بی‌دغدغه به یکی از قوی‌ترین هوش‌های مصنوعی دنیا هستید:\n\n"
f"⭐️ ویژگی‌های کلیدی این اشتراک:\n"
f"▫️ اتصال به ۶ جیمیل مجزا (امکان استفاده همزمان و مستقل برای خودتان و هم‌تیمی‌ها)\n"
f"▫️ فعال‌سازی ۱۰۰٪ مستقیم روی جیمیل شخصی شما\n"
f"▫️ درک عمیق عکس، فایل‌های صوتی، ویدیو و اسناد سنگین بدون افت سرعت\n"
f"▫️ کدنویسی پیشرفته، خطایابی کدهای سنگین و حل مسائل پیچیده الگوریتمی\n"
f"▫️ ایده‌آل برای دانشگاه، تحقیق، ترجمه تخصصی و تحلیل داده‌های حجیم\n"
f"▫️ ۱۸ ماه اعتبار کامل بدون نیاز به شماره مجازی و بدون قطعی\n\n"
f"💰 قیمت اصلی اشتراک: ۱.۵۰۰.۰۰۰ تومان\n"
f"🔥 قیمت در آف ویژه: ۱.۲۰۰.۰۰۰ تومان! (هر جیمیل فقط ۲۰۰ هزار تومان برای ۱۸ ماه)\n\n"
f"⏰ مهلت تخفیف: ظرفیت ثبت‌نام با قیمت ۱.۲۰۰.۰۰۰ تومان محدود بوده و پس از تکمیل، قیمت به ۱.۵۰۰.۰۰۰ تومان بازمی‌گردد.\n\n"
f"🎨 بنر نئونی بالا مستقیماً توسط هوش مصنوعی جمنای خلق شده است.\n\n"
f"جهت فعال‌سازی آنی و راهنمایی:\n"
f"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
f"🌐 کانال تلگرام: https://t.me/NetVibe_VPN"
)
},
{
"id": "gemini_vs_chatgpt",
"name": "برتری Gemini Pro نسبت به سایر هوش‌های مصنوعی",
"banner_type": "discount_600k",
"generate": lambda deadline: (
f"⚡️ چرا کاربران حرفه‌ای از ChatGPT Plus به Google Gemini Pro کوچ می‌کنند؟\n\n"
f"اگر از لیمیت‌ها و قطعی‌های مداوم هوش‌های مصنوعی خسته شدید، تفاوت جمنای پرو را ببینید:\n\n"
f"▫️ پردازش تا ۲ میلیون توکن کانتکست (چندین برابر چت‌جی‌پی‌تی)\n"
f"▫️ تحلیل مستقیم و بدون قطعی فایل‌های ویدیویی، پادکست‌های صوتی و PDFهای قطور\n"
f"▫️ بدون نیاز به شماره مجازی خارجی و بدون ترس از بن شدن اکانت\n"
f"▫️ فعال‌سازی قانونی ۱۸ ماهه مستقیماً روی ایمیل شخصی\n\n"
f"💰 قیمت رسمی سالیانه: ۱.۵۰۰.۰۰۰ تومان\n"
f"🔥 قیمت استثنایی در آفر فعلی: ۶۰۰.۰۰۰ تومان!\n\n"
f"{deadline['warning_text']}\n\n"
f"🎨 بنر دیدنی بالا به عنوان نمونه بارز توانایی هنری و بصری هوش مصنوعی جمنای است.\n\n"
f"خرید و دریافت فوری:\n"
f"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
f"🌐 کانال تلگرام: https://t.me/NetVibe_VPN"
)
}
]
def generate_random_gemini_post(angle_id: str = None, hours_remaining: int = 48) -> tuple[str, str, str]:
"""
Returns (post_text, banner_type, angle_name)
"""
deadline = get_campaign_deadline_text(hours_remaining)
if angle_id:
selected = next((a for a in GEMINI_ANGLES if a["id"] == angle_id), None)
if not selected:
selected = random.choice(GEMINI_ANGLES)
else:
selected = random.choice(GEMINI_ANGLES)
text = selected["generate"](deadline)
return text, selected["banner_type"], selected["name"]

View file

@ -0,0 +1,975 @@
import logging
import os
import re
import asyncio
from datetime import datetime, timezone
from typing import List, Optional
from uuid import UUID
from pydantic import BaseModel
from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends, HTTPException, Query, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
import shutil
import uuid
from datetime import timedelta
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, desc
from sqlalchemy.orm import selectinload
from app.config import settings
from app.database import init_db, get_db
from app.models import Channel, RawPost, ContentDraft, FeedbackLog, PublishQueue
from app.banner_generator import (
create_gemini_banner,
create_vpn_banner,
get_gemini_banner_from_pool_or_generate,
get_vpn_banner_from_pool_or_generate,
GEMINI_POOL_DIR,
VPN_POOL_DIR
)
from app.schemas import (
ChannelCreate, ChannelOut, ContentDraftOut,
DraftActionRequest, FeedbackLogOut, PublishQueueOut,
PipelineRunResponse
)
from app.agents.agent_a_scraper import seed_default_channels, run_channel_ingestion
from app.agents.agent_b_curator import generate_draft_for_post, record_human_feedback
from app.agents.agent_c_publisher import dispatch_pending_queue, dispatch_single_queue_item, send_to_telegram
from app.gemini_content_engine import (
generate_random_gemini_post,
GEMINI_ANGLES,
get_campaign_deadline_text
)
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
logger = logging.getLogger("main_api")
async def periodic_queue_worker():
"""Background worker checking publish queue every 60 seconds and auto-dispatching due posts."""
logger.info("Starting background Telegram auto-dispatch worker...")
while True:
try:
async for session in get_db():
dispatched = await dispatch_pending_queue(session)
if dispatched > 0:
logger.info(f"Auto-dispatch worker successfully published {dispatched} scheduled post(s) to Telegram.")
break
except Exception as e:
logger.error(f"Error in periodic_queue_worker: {e}")
await asyncio.sleep(60)
async def periodic_scrape_worker():
"""Background worker periodically scraping active Telegram channels."""
interval = max(1, getattr(settings, "SCRAPE_INTERVAL_HOURS", 4)) * 3600
logger.info(f"Starting background channel scraper worker (interval: {interval}s)...")
while True:
try:
await asyncio.sleep(interval)
logger.info("Executing scheduled channel scraping cycle...")
async for session in get_db():
channels = (await session.execute(select(Channel).where(Channel.is_active == True))).scalars().all()
for ch in channels:
try:
await run_channel_ingestion(session, ch, limit=10)
except Exception as e:
logger.error(f"Error scraping channel {ch.telegram_handle}: {e}")
break
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Error in periodic_scrape_worker: {e}")
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Initializing database and seeding default channels...")
await init_db()
async for session in get_db():
await seed_default_channels(session)
break
# Start periodic publisher task and scraper worker in background
worker_task = asyncio.create_task(periodic_queue_worker())
scraper_task = asyncio.create_task(periodic_scrape_worker())
yield
logger.info("Cancelling background tasks...")
worker_task.cancel()
scraper_task.cancel()
try:
await worker_task
except asyncio.CancelledError:
pass
try:
await scraper_task
except asyncio.CancelledError:
pass
logger.info("Shutting down pipeline service.")
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
lifespan=lifespan
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- CHANNELS ENDPOINTS ---
@app.get("/api/v1/channels", response_model=List[ChannelOut])
async def list_channels(db: AsyncSession = Depends(get_db)):
stmt = select(Channel).order_by(Channel.niche, Channel.telegram_handle)
result = await db.execute(stmt)
return result.scalars().all()
@app.post("/api/v1/channels", response_model=ChannelOut)
async def create_channel(channel_in: ChannelCreate, db: AsyncSession = Depends(get_db)):
clean_handle = channel_in.telegram_handle.replace("@", "").strip()
stmt = select(Channel).where(Channel.telegram_handle == clean_handle)
existing = (await db.execute(stmt)).scalar_one_or_none()
if existing:
raise HTTPException(status_code=400, detail="Channel handle already registered")
new_ch = Channel(
telegram_handle=clean_handle,
title=channel_in.title or clean_handle,
niche=channel_in.niche,
subscriber_count=channel_in.subscriber_count or 0,
is_active=channel_in.is_active
)
db.add(new_ch)
await db.commit()
await db.refresh(new_ch)
return new_ch
# --- PIPELINE TRIGGER ENDPOINTS ---
@app.api_route("/api/v1/pipeline/run-now", methods=["GET", "POST"], response_model=PipelineRunResponse)
@app.post("/api/v1/pipeline/scrape-and-curate", response_model=PipelineRunResponse)
async def run_full_pipeline(limit_posts: int = 10, db: AsyncSession = Depends(get_db)):
channels = (await db.execute(select(Channel).where(Channel.is_active == True))).scalars().all()
new_posts_total = 0
drafts_created_total = 0
errors = []
for ch in channels:
try:
new_p = await run_channel_ingestion(db, ch, limit=limit_posts)
new_posts_total += new_p
except Exception as e:
errors.append(f"Scrape channel {ch.telegram_handle}: {str(e)}")
# Curate un-drafted raw posts (prioritize newest posts with configs and high engagement)
stmt_unprocessed = (
select(RawPost)
.outerjoin(ContentDraft, RawPost.id == ContentDraft.raw_post_id)
.where(ContentDraft.id == None)
.order_by(desc(RawPost.posted_at), desc(RawPost.views))
.limit(40)
)
unprocessed_posts = (await db.execute(stmt_unprocessed)).scalars().all()
for p in unprocessed_posts:
try:
await generate_draft_for_post(db, p)
drafts_created_total += 1
except Exception as e:
errors.append(f"Curate post {p.id}: {str(e)}")
return PipelineRunResponse(
scraped_channels=len(channels),
new_posts=new_posts_total,
drafts_generated=drafts_created_total,
errors=errors
)
# --- DRAFTS & REVIEW ENDPOINTS ---
@app.post("/api/v1/raw-posts/{post_id}/create-draft", response_model=ContentDraftOut)
async def create_draft_for_single_post(post_id: str, db: AsyncSession = Depends(get_db)):
stmt = select(RawPost).where(RawPost.id == post_id)
post = (await db.execute(stmt)).scalar_one_or_none()
if not post:
raise HTTPException(status_code=404, detail="Post not found")
draft = await generate_draft_for_post(db, post)
stmt_draft = (
select(ContentDraft)
.options(selectinload(ContentDraft.raw_post).selectinload(RawPost.channel))
.where(ContentDraft.id == draft.id)
)
loaded_draft = (await db.execute(stmt_draft)).scalar_one()
return loaded_draft
@app.get("/api/v1/gemini/angles")
async def get_gemini_angles_list():
"""Return available marketing personas/angles for Gemini Pro."""
return [
{"id": a["id"], "name": a["name"], "banner_type": a["banner_type"]}
for a in GEMINI_ANGLES
]
@app.post("/api/v1/drafts/create-gemini-promo", response_model=ContentDraftOut)
async def create_gemini_promo_draft(
price_toman: str = Query("۶۰۰.۰۰۰ تومان"),
is_flash_sale: bool = Query(True),
angle_id: Optional[str] = Query(None),
hours_remaining: int = Query(48),
db: AsyncSession = Depends(get_db)
):
"""Generate an instant Gemini Pro promo draft with strictly selected user pool banners, rich copywriting angles, and precise countdown deadlines."""
promo_text, banner_type, angle_name = generate_random_gemini_post(
angle_id=angle_id,
hours_remaining=hours_remaining
)
banner_url = get_gemini_banner_from_pool_or_generate(
headline=f"پروموشن {angle_name}",
price_toman=price_toman,
is_discount=is_flash_sale,
banner_type=banner_type
)
stmt_post = select(RawPost).limit(1)
sample_post = (await db.execute(stmt_post)).scalar_one_or_none()
if not sample_post:
stmt_ch = select(Channel).limit(1)
ch = (await db.execute(stmt_ch)).scalar_one_or_none()
if not ch:
ch = Channel(name="NetVibe Seed", handle="NetVibe_VPN", is_active=True)
db.add(ch)
await db.flush()
sample_post = RawPost(
channel_id=ch.id,
message_id=999999,
original_text=promo_text,
post_url="https://t.me/NetVibe_VPN",
media_type="photo",
views=1000,
reactions=50,
posted_at=datetime.now(timezone.utc)
)
db.add(sample_post)
await db.flush()
draft = ContentDraft(
raw_post_id=sample_post.id,
ai_generated_text=promo_text,
current_text=promo_text,
banner_image_url=banner_url,
status="pending"
)
db.add(draft)
await db.commit()
stmt_load = (
select(ContentDraft)
.options(selectinload(ContentDraft.raw_post).selectinload(RawPost.channel))
.where(ContentDraft.id == draft.id)
)
loaded_draft = (await db.execute(stmt_load)).scalar_one()
return loaded_draft
@app.post("/api/v1/drafts/create-budget-vpn-promo", response_model=ContentDraftOut)
async def create_budget_vpn_promo_draft(db: AsyncSession = Depends(get_db)):
"""Generate an instant Budget Marketing Package draft (100GB / 3 Months for 200,000 Tomans)."""
banner_url = get_vpn_banner_from_pool_or_generate(
title="بسته ویژه ۳ ماهه اقتصادی NetVibe",
card1_title="بسته ۱۰۰ گیگ ۳ ماهه",
card2_title="قیمت ویژه: ۲۰۰.۰۰۰ تومان",
brand=settings.TARGET_CHANNEL
)
promo_text = (
"🔥 جشنواره اقتصادی NetVibe: بسته ویژه ۳ ماهه با تخفیف طلایی\n\n"
"اگر مصرف ماهانه‌ات خیلی سنگین نیست ولی دنبال یک اینترنت پایدار و بی‌دردسر برای چند ماه هستی:\n\n"
"📦 بسته ۱۰۰ گیگابایت ۳ ماهه\n"
"💰 قیمت استثنایی: فقط ۲۰۰.۰۰۰ تومان! (روزی کمتر از ۲.۵۰۰ تومان)\n\n"
"▫️ اعتبار زمانی: ۹۰ روز کامل\n"
"▫️ ساب‌لینک هوشمند با قابلیت اتصال خودکار به خلوت‌ترین سرور\n"
"▫️ آی‌پی تمیز و باکیفیت مناسب ترید، صرافی و امور بانکی\n"
"▫️ بدون محدودیت در تعداد دستگاه همزمان\n"
"▫️ سازگار با تمام اپراتورها (همراه اول، ایرانسل، رایتل و مخابرات)\n\n"
"⚡️ ظرفیت جشنواره محدود است. جهت خرید و دریافت تست:\n"
"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
"🌐 کانال رسمی: https://t.me/NetVibe_VPN"
)
stmt_post = select(RawPost).limit(1)
sample_post = (await db.execute(stmt_post)).scalar_one_or_none()
draft = ContentDraft(
raw_post_id=sample_post.id if sample_post else None,
ai_generated_text=promo_text,
current_text=promo_text,
banner_image_url=banner_url,
status="pending"
)
db.add(draft)
await db.commit()
stmt_load = (
select(ContentDraft)
.options(selectinload(ContentDraft.raw_post).selectinload(RawPost.channel))
.where(ContentDraft.id == draft.id)
)
return (await db.execute(stmt_load)).scalar_one()
@app.post("/api/v1/drafts/create-unlimited-vpn-promo", response_model=ContentDraftOut)
async def create_unlimited_vpn_promo_draft(db: AsyncSession = Depends(get_db)):
"""Generate an instant Unlimited VPN Promo draft (2-User 300k & 3-User 350k)."""
banner_url = get_vpn_banner_from_pool_or_generate(
title="اتصال پرسرعت، پایدار و بدون قطعی",
card1_title="پلن ۲ کاربره نامحدود",
card2_title="پلن ۳ کاربره نامحدود",
brand=settings.TARGET_CHANNEL
)
promo_text = (
"➕ اگر هنوز درگیر قطعی وصلی هستی و دنبال اتصال پایداری ؛ میتونی روی ما حساب کنی !\n\n"
"✔️ یک اشتراک ثابت و پرسرعت\n"
"✔️ پشتیبانی قدرتمند ۲۴ ساعته\n\n"
"🛑 بسته‌های جدید بدون محدودیت حجم (نامحدود) 🛑\n"
"فعال روی: تمامی سایت‌ها و اپلیکیشن‌ها (اینستاگرام، یوتیوب، تلگرام)\n"
"بدون نگرانی بابت تمام شدن حجم! ♾️\n\n"
"👤 ۲ کاربره: ۳۰۰.۰۰۰ تومان\n"
"👥 ۳ کاربره: ۳۵۰.۰۰۰ تومان\n\n"
"✅ مدت زمان استفاده: ۱ ماه\n"
"✅ محدودیت حجم: ندارد (نامحدود واقعی)\n"
"✅ ساب‌لینک اختصاصی و هوشمند: دارد\n"
"✅ اتصال پایدار با همه اینترنت‌ها (همراه اول، ایرانسل، رایتل و مخابرات)\n\n"
"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
"🌐 کانال رسمی: https://t.me/NetVibe_VPN"
)
stmt_post = select(RawPost).limit(1)
sample_post = (await db.execute(stmt_post)).scalar_one_or_none()
draft = ContentDraft(
raw_post_id=sample_post.id if sample_post else None,
ai_generated_text=promo_text,
current_text=promo_text,
banner_image_url=banner_url,
status="pending"
)
db.add(draft)
await db.commit()
stmt_load = (
select(ContentDraft)
.options(selectinload(ContentDraft.raw_post).selectinload(RawPost.channel))
.where(ContentDraft.id == draft.id)
)
return (await db.execute(stmt_load)).scalar_one()
@app.post("/api/v1/drafts/generate-marketing-batch")
async def generate_marketing_batch(db: AsyncSession = Depends(get_db)):
"""Generate a batch of diverse creative marketing drafts across different angles and hooks."""
stmt_post = select(RawPost).limit(1)
sample_post = (await db.execute(stmt_post)).scalar_one_or_none()
marketing_promos = [
# Angle 1: Connection Agitation & Reality
(
"➕ اگر هنوز درگیر قطعی وصلی هستی و دنبال اتصال پایداری ؛ میتونی روی ما حساب کنی !\n\n"
"✔️ یک اشتراک ثابت و پرسرعت\n"
"✔️ پشتیبانی قدرتمند ۲۴ ساعته\n\n"
"🛑 بسته‌های جدید بدون محدودیت حجم (نامحدود) 🛑\n"
"فعال روی: تمامی سایت‌ها و اپلیکیشن‌ها (اینستاگرام، یوتیوب، تلگرام)\n"
"بدون نگرانی بابت تمام شدن حجم! ♾️\n\n"
"👤 ۲ کاربره: ۳۰۰.۰۰۰ تومان\n"
"👥 ۳ کاربره: ۳۵۰.۰۰۰ تومان\n\n"
"✅ مدت زمان استفاده: ۱ ماه\n"
"✅ محدودیت حجم: ندارد (نامحدود واقعی)\n"
"✅ ساب‌لینک اختصاصی و هوشمند: دارد\n"
"✅ اتصال پایدار با همه اینترنت‌ها (همراه اول، ایرانسل، رایتل و مخابرات)\n\n"
"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
"🌐 کانال رسمی: https://t.me/NetVibe_VPN",
get_vpn_banner_from_pool_or_generate(
title="اتصال پایدار، بدون قطعی و نامحدود",
card1_title="پلن ۲ کاربره نامحدود",
card2_title="پلن ۳ کاربره نامحدود",
brand=settings.TARGET_CHANNEL
)
),
# Angle 2: Programmers & Coders Gemini Pro Angle
(
generate_random_gemini_post(angle_id="programmers_coders")[0],
get_gemini_banner_from_pool_or_generate(banner_type="discount_600k")
),
# Angle 2.1: Researchers & Students Gemini Pro Angle
(
generate_random_gemini_post(angle_id="researchers_students")[0],
get_gemini_banner_from_pool_or_generate(banner_type="discount_600k")
),
# Angle 2.2: 6-Gmail Multi-Account Team Package
(
generate_random_gemini_post(angle_id="team_6gmails_agency")[0],
get_gemini_banner_from_pool_or_generate(banner_type="multi_tier_6gmail")
),
# Angle 2.3: Content Creators & Social Media
(
generate_random_gemini_post(angle_id="content_creators_marketers")[0],
get_gemini_banner_from_pool_or_generate(banner_type="discount_600k")
),
# Angle 2.4: Economy 100GB 3-Month Plan (Budget Marketing)
(
"🔥 بسته اقتصادی و بهینه ۱۰۰ گیگ ۳ ماهه NetVibe\n\n"
"دنبال یک اشتراک طولانی‌مدت و باصرفه هستی که هر ماه نگران تمدید نباشی؟\n\n"
"▫️ ترافیک: ۱۰۰ گیگابایت خالص\n"
"▫️ مدت زمان اعتبار: ۳ ماه کامل\n"
"▫️ اتصال آنی و پرسرعت روی تمام اپراتورها\n"
"▫️ بدون افت سرعت در ساعات شلوغی\n\n"
"💰 قیمت استثنایی: فقط ۲۰۰.۰۰۰ تومان!\n\n"
"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
"🌐 کانال رسمی: https://t.me/NetVibe_VPN",
get_vpn_banner_from_pool_or_generate(
title="بسته بهینه ۱۰۰ گیگ ۳ ماهه",
card1_title="قیمت اقتصادی ۲۰۰.۰۰۰ تومان",
card2_title="اعتبار طولانی ۳ ماهه",
brand=settings.TARGET_CHANNEL
)
),
# Angle 3: Low Ping & Trader Dedicated IP Angle
(
"⚡️ پینگ پایین و آی‌پی ثابت تمیز برای ترید و کارهای حساس\n\n"
"بزرگترین دغدغه تریدرها، گیمرها و فریلنسرها پرش ناگهانی آی‌پی و مسدود شدن حساب‌هاست.\n"
"در NetVibe ترافیک شما از تونل‌های اختصاصی و سرورهای خلوت عبور داده می‌شود تا بالاترین ثبات را تجربه کنید.\n\n"
"▫️ پینگ پایدار زیر ۷۰ میلی‌ثانیه\n"
"▫️ عدم تداخل لوکیشن و مناسب بایننس، تریدینگ‌ویو و صرافی‌ها\n"
"▫️ تضمین تعویض سرور در صورت بروز اختلال زیرساختی\n\n"
"تعرفه‌های ماهانه نامحدود:\n"
"👤 ۲ کاربره: ۳۰۰.۰۰۰ تومان\n"
"👥 ۳ کاربره: ۳۵۰.۰۰۰ تومان\n\n"
"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
"🌐 کانال رسمی: https://t.me/NetVibe_VPN",
get_vpn_banner_from_pool_or_generate(
title="پینگ فوق‌العاده و آی‌پی تمیز ترید",
card1_title="تونل اختصاصی آلمان و هلند",
card2_title="ضمانت پایداری ۲۴ ساعته",
brand=settings.TARGET_CHANNEL
)
),
# Angle 4: Family & Team Multi-Device Solution
(
"👥 یک اشتراک برای تمام اعضای خانواده یا همکاران\n\n"
"لازم نیست برای هر گوشی جداگانه هزینه کنید؛ با پلن‌های چندکاربره NetVibe، همه به طور همزمان بدون افت سرعت متصل می‌مانید.\n\n"
"✨ پلن ۳ کاربره نامحدود: ۳۵۰.۰۰۰ تومان\n"
"✨ پلن ۲ کاربره نامحدود: ۳۰۰.۰۰۰ تومان\n\n"
"✔️ سازگار با اندروید، iOS، ویندوز، مک و تلویزیون هوشمند\n"
"✔️ پشتیبانی لحظه‌ای و اختصاصی\n\n"
"✉️ پشتیبانی و ثبت سفارش: @NetVibe_admin\n"
"🌐 کانال رسمی: https://t.me/NetVibe_VPN",
get_vpn_banner_from_pool_or_generate(
title="اشتراک همزمان بدون افت سرعت",
card1_title="پوشش همه دیوایس‌ها",
card2_title="پشتیبانی ۲۴ ساعته اختصاصی",
brand=settings.TARGET_CHANNEL
)
)
]
created_ids = []
for promo_text, banner_url in marketing_promos:
draft = ContentDraft(
raw_post_id=sample_post.id if sample_post else None,
ai_generated_text=promo_text,
current_text=promo_text,
banner_image_url=banner_url,
status="pending"
)
db.add(draft)
await db.flush()
created_ids.append(str(draft.id))
await db.commit()
return {"status": "success", "count": len(created_ids), "draft_ids": created_ids}
# --- BANNER POOL MANAGEMENT APIS ---
@app.get("/api/v1/banner-pool")
async def list_banner_pool(category: str = Query("gemini")):
"""List all banners in user-uploaded pool for gemini or vpn."""
target_dir = GEMINI_POOL_DIR if category == "gemini" else VPN_POOL_DIR
os.makedirs(target_dir, exist_ok=True)
items = []
valid_exts = ('.png', '.jpg', '.jpeg', '.webp')
for fname in sorted(os.listdir(target_dir)):
if fname.lower().endswith(valid_exts):
fpath = os.path.join(target_dir, fname)
stat = os.stat(fpath)
items.append({
"filename": fname,
"url": f"/static/banner_pool/{category}/{fname}",
"size_kb": round(stat.st_size / 1024, 1),
"modified_at": datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat()
})
return {"category": category, "count": len(items), "banners": items}
@app.post("/api/v1/banner-pool/upload")
async def upload_banner_to_pool(
category: str = Query("gemini"),
file: UploadFile = File(...)
):
"""Upload a new banner into the Gemini or VPN banner pool (up to 10+ banners)."""
target_dir = GEMINI_POOL_DIR if category == "gemini" else VPN_POOL_DIR
os.makedirs(target_dir, exist_ok=True)
clean_name = re.sub(r'[^a-zA-Z0-9_.-]', '_', file.filename or "banner.png")
unique_name = f"{uuid.uuid4().hex[:6]}_{clean_name}"
save_path = os.path.join(target_dir, unique_name)
with open(save_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return {
"status": "success",
"category": category,
"filename": unique_name,
"url": f"/static/banner_pool/{category}/{unique_name}"
}
@app.delete("/api/v1/banner-pool/{category}/{filename}")
async def delete_banner_from_pool(category: str, filename: str):
"""Delete a banner from the pool."""
target_dir = GEMINI_POOL_DIR if category == "gemini" else VPN_POOL_DIR
clean_name = os.path.basename(filename)
target_path = os.path.join(target_dir, clean_name)
if os.path.exists(target_path):
os.remove(target_path)
return {"status": "success", "message": f"Deleted {clean_name}"}
raise HTTPException(status_code=404, detail="Banner not found in pool")
@app.get("/api/v1/drafts", response_model=List[ContentDraftOut])
async def list_drafts(
status: Optional[str] = Query("pending"),
db: AsyncSession = Depends(get_db)
):
query = (
select(ContentDraft)
.options(selectinload(ContentDraft.raw_post))
.order_by(desc(ContentDraft.created_at))
)
if status and status != "all":
query = query.where(ContentDraft.status == status)
result = await db.execute(query)
return result.scalars().all()
import random
def generate_random_tehran_prime_time(base_date: datetime, min_allowed_utc: Optional[datetime] = None) -> datetime:
"""
ساعات اوج بازدید ۴ تا ۸ شب به وقت تهران (16:00 تا 20:00 تهران == 12:30 تا 16:30 UTC):
انتخاب تصادفی ساعت، دقیقه و ثانیه در این بازه ۲۴۰ دقیقه‌ای.
"""
year, month, day = base_date.year, base_date.month, base_date.day
window_start = datetime(year, month, day, 12, 30, 0, tzinfo=timezone.utc)
window_end = datetime(year, month, day, 16, 30, 0, tzinfo=timezone.utc)
if min_allowed_utc and min_allowed_utc.tzinfo is None:
min_allowed_utc = min_allowed_utc.replace(tzinfo=timezone.utc)
if min_allowed_utc:
earliest_possible = min_allowed_utc + timedelta(minutes=10)
if earliest_possible > window_end:
next_day = base_date + timedelta(days=1)
return generate_random_tehran_prime_time(next_day, None)
elif earliest_possible > window_start:
window_start = earliest_possible
total_seconds = int((window_end - window_start).total_seconds())
if total_seconds <= 60:
rand_sec = 0
else:
rand_sec = random.randint(0, total_seconds)
return window_start + timedelta(seconds=rand_sec)
@app.post("/api/v1/drafts/{draft_id}/action", response_model=ContentDraftOut)
async def handle_draft_action(
draft_id: UUID,
payload: DraftActionRequest,
db: AsyncSession = Depends(get_db)
):
stmt = (
select(ContentDraft)
.options(selectinload(ContentDraft.raw_post))
.where(ContentDraft.id == draft_id)
)
draft = (await db.execute(stmt)).scalar_one_or_none()
if not draft:
raise HTTPException(status_code=404, detail="Draft not found")
if payload.action == "reject":
draft.status = "rejected"
await record_human_feedback(
db,
draft_id=draft.id,
original_ai_text=draft.ai_generated_text,
final_human_text=payload.text or draft.current_text,
rejection_reason=payload.rejection_reason or "Rejected by reviewer"
)
elif payload.action in ["approve", "edit_approve"]:
if payload.action == "edit_approve" and payload.text:
draft.current_text = payload.text.strip()
draft.status = "edited"
await record_human_feedback(
db,
draft_id=draft.id,
original_ai_text=draft.ai_generated_text,
final_human_text=draft.current_text
)
else:
draft.status = "approved"
# Apply Banner Choice (Remove banner or assign custom uploaded banner)
if payload.remove_banner:
draft.banner_image_url = None
elif payload.banner_image_url:
draft.banner_image_url = payload.banner_image_url
# SMART AUTO-SCHEDULER (حداقل یک پست در هر روز در ساعات اوج بازدید)
now_utc = datetime.now(timezone.utc)
if payload.scheduled_time:
sched_time = payload.scheduled_time
if sched_time.tzinfo is None:
sched_time = sched_time.replace(tzinfo=timezone.utc)
else:
# Query the latest scheduled time currently in queue
stmt_latest = (
select(PublishQueue.scheduled_time)
.where(PublishQueue.status == "queued")
.order_by(desc(PublishQueue.scheduled_time))
.limit(1)
)
latest_res = (await db.execute(stmt_latest)).scalar_one_or_none()
if latest_res and latest_res.tzinfo is None:
latest_res = latest_res.replace(tzinfo=timezone.utc)
# ساعات اوج بازدید تلگرام: تصادفی بین ۱۶:۰۰ تا ۲۰:۰۰ عصر به وقت تهران
if not latest_res or latest_res < now_utc:
sched_time = generate_random_tehran_prime_time(now_utc, min_allowed_utc=now_utc)
else:
next_day = latest_res + timedelta(days=1)
sched_time = generate_random_tehran_prime_time(next_day, None)
# Push or update PublishQueue
q_stmt = select(PublishQueue).where(PublishQueue.draft_id == draft.id)
existing_q = (await db.execute(q_stmt)).scalar_one_or_none()
if not existing_q:
queue_item = PublishQueue(
draft_id=draft.id,
scheduled_time=sched_time,
status="queued"
)
db.add(queue_item)
else:
existing_q.scheduled_time = sched_time
existing_q.status = "queued"
await db.commit()
await db.refresh(draft)
return draft
@app.post("/api/v1/upload-banner")
async def upload_custom_banner(file: UploadFile = File(...)):
# Validate content type
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="Only image files are allowed")
ext = os.path.splitext(file.filename)[1] or ".png"
unique_name = f"upload_{uuid.uuid4().hex[:10]}{ext}"
dest_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static", "banners")
os.makedirs(dest_dir, exist_ok=True)
dest_path = os.path.join(dest_dir, unique_name)
with open(dest_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return {"banner_url": f"/static/banners/{unique_name}"}
# --- FEEDBACK & QUEUE ENDPOINTS ---
@app.get("/api/v1/feedback-logs", response_model=List[FeedbackLogOut])
async def list_feedback_logs(limit: int = 20, db: AsyncSession = Depends(get_db)):
stmt = select(FeedbackLog).order_by(desc(FeedbackLog.created_at)).limit(limit)
res = await db.execute(stmt)
return res.scalars().all()
@app.get("/api/v1/queue", response_model=List[PublishQueueOut])
async def list_publish_queue(db: AsyncSession = Depends(get_db)):
stmt = (
select(PublishQueue)
.options(
selectinload(PublishQueue.draft).selectinload(ContentDraft.raw_post)
)
.order_by(desc(PublishQueue.created_at))
)
res = await db.execute(stmt)
return res.scalars().all()
class QueueUpdateIn(BaseModel):
scheduled_time: Optional[datetime] = None
status: Optional[str] = None
@app.patch("/api/v1/queue/{queue_id}")
async def update_queue_item(
queue_id: str,
payload: QueueUpdateIn,
db: AsyncSession = Depends(get_db)
):
import uuid as _uuid
try:
qid = _uuid.UUID(queue_id)
except Exception:
raise HTTPException(status_code=400, detail="شناسه صف نامعتبر است")
stmt = select(PublishQueue).where(PublishQueue.id == qid)
item = (await db.execute(stmt)).scalar_one_or_none()
if not item:
raise HTTPException(status_code=404, detail="آیتم صف یافت نشد")
if payload.scheduled_time:
t = payload.scheduled_time
if t.tzinfo is None:
t = t.replace(tzinfo=timezone.utc)
item.scheduled_time = t
if payload.status:
item.status = payload.status
await db.commit()
await db.refresh(item)
return {"id": str(item.id), "scheduled_time": item.scheduled_time.isoformat(), "status": item.status}
@app.post("/api/v1/queue/{queue_id}/randomize")
async def randomize_queue_item(
queue_id: str,
db: AsyncSession = Depends(get_db)
):
import uuid as _uuid
try:
qid = _uuid.UUID(queue_id)
except Exception:
raise HTTPException(status_code=400, detail="شناسه صف نامعتبر است")
stmt = select(PublishQueue).where(PublishQueue.id == qid)
item = (await db.execute(stmt)).scalar_one_or_none()
if not item:
raise HTTPException(status_code=404, detail="آیتم صف یافت نشد")
now_utc = datetime.now(timezone.utc)
base_date = item.scheduled_time or now_utc
if base_date.tzinfo is None:
base_date = base_date.replace(tzinfo=timezone.utc)
# اگر برای امروز است، بررسی کنیم زمان گذشته نباشد
min_allowed = now_utc if base_date.date() == now_utc.date() else None
item.scheduled_time = generate_random_tehran_prime_time(base_date, min_allowed_utc=min_allowed)
item.status = "queued"
await db.commit()
await db.refresh(item)
return {"id": str(item.id), "scheduled_time": item.scheduled_time.isoformat(), "status": item.status}
@app.post("/api/v1/queue/rebalance-random")
async def rebalance_all_queued(db: AsyncSession = Depends(get_db)):
"""
تمام پست‌های در صف را بازآرایی و زمان آن‌ها را در بازه ۴ تا ۸ شب (۱۶:۰۰ تا ۲۰:۰۰ تهران) روزهای متوالی رندوم می‌کند.
"""
stmt = (
select(PublishQueue)
.where(PublishQueue.status == "queued")
.order_by(PublishQueue.scheduled_time.asc())
)
items = (await db.execute(stmt)).scalars().all()
if not items:
return {"rebalanced": 0, "items": []}
now_utc = datetime.now(timezone.utc)
curr_date = now_utc
# اگر از امروز کمتر از ۲۰ دقیقه به ساعت ۲۰:۰۰ تهران (16:30 UTC) مانده، از فردا شروع کن
today_deadline = curr_date.replace(hour=16, minute=30, second=0, microsecond=0)
if now_utc >= today_deadline - timedelta(minutes=20):
curr_date = curr_date + timedelta(days=1)
min_allowed = None
else:
min_allowed = now_utc
res_items = []
for i, item in enumerate(items):
target_day = curr_date + timedelta(days=i)
min_limit = min_allowed if i == 0 and min_allowed else None
new_time = generate_random_tehran_prime_time(target_day, min_allowed_utc=min_limit)
item.scheduled_time = new_time
res_items.append({"id": str(item.id), "scheduled_time": new_time.isoformat()})
await db.commit()
return {"rebalanced": len(items), "items": res_items}
@app.delete("/api/v1/queue/{queue_id}")
async def delete_queue_item(
queue_id: str,
db: AsyncSession = Depends(get_db)
):
import uuid as _uuid
try:
qid = _uuid.UUID(queue_id)
except Exception:
raise HTTPException(status_code=400, detail="شناسه صف نامعتبر است")
stmt = select(PublishQueue).where(PublishQueue.id == qid)
item = (await db.execute(stmt)).scalar_one_or_none()
if not item:
raise HTTPException(status_code=404, detail="آیتم صف یافت نشد")
if item.draft_id:
d_stmt = select(ContentDraft).where(ContentDraft.id == item.draft_id)
draft = (await db.execute(d_stmt)).scalar_one_or_none()
if draft:
draft.status = "pending"
await db.delete(item)
await db.commit()
return {"status": "deleted", "id": str(qid)}
import os
from pydantic import BaseModel
from fastapi.staticfiles import StaticFiles
from app.banner_generator import create_vpn_banner, BANNER_DIR
STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
os.makedirs(os.path.join(STATIC_DIR, "banners"), exist_ok=True)
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
class BannerRequest(BaseModel):
title: Optional[str] = "سرویس اینترنت پرسرعت و پایدار"
location: Optional[str] = "آلمان 🇩🇪 و هلند 🇳🇱"
subtitle: Optional[str] = "اتصال پایدار و بدون قطعی روی تمامی اپراتورها"
@app.post("/api/v1/generate-banner")
async def generate_banner_api(req: BannerRequest):
path = create_vpn_banner(
title=req.title or "سرویس اینترنت پرسرعت و پایدار",
subtitle=req.subtitle or "اتصال پایدار و بدون قطعی روی تمامی اپراتورها"
)
filename = os.path.basename(path)
return {"banner_url": f"/static/banners/{filename}", "local_path": path}
@app.get("/api/v1/stats")
async def get_dashboard_stats(db: AsyncSession = Depends(get_db)):
# Channels
ch_stmt = select(Channel)
channels = (await db.execute(ch_stmt)).scalars().all()
total_subscribers = sum(c.subscriber_count or 0 for c in channels)
# Raw Posts
p_stmt = select(RawPost).options(selectinload(RawPost.channel)).order_by(desc(RawPost.views)).limit(25)
viral_posts = (await db.execute(p_stmt)).scalars().all()
p_latest_stmt = select(RawPost).options(selectinload(RawPost.channel)).order_by(desc(RawPost.posted_at)).limit(35)
latest_posts = (await db.execute(p_latest_stmt)).scalars().all()
# All posts for analytics
all_p_stmt = select(RawPost)
all_posts = (await db.execute(all_p_stmt)).scalars().all()
# Protocols distribution
proto_counts = {"VLESS": 0, "VMESS": 0, "TROJAN": 0, "SHADOWSOCKS": 0, "WARP": 0, "OTHER": 0}
hourly = {i: 0 for i in range(24)}
for p in all_posts:
txt = (p.original_text or "").upper()
matched = False
for proto in ["VLESS", "VMESS", "TROJAN", "SHADOWSOCKS", "WARP"]:
if proto in txt:
proto_counts[proto] += 1
matched = True
if not matched:
proto_counts["OTHER"] += 1
if p.posted_at:
h = p.posted_at.hour
hourly[h] = hourly.get(h, 0) + 1
# Queue counts
q_stmt = select(PublishQueue)
all_q = (await db.execute(q_stmt)).scalars().all()
# Drafts counts
d_stmt = select(ContentDraft)
all_d = (await db.execute(d_stmt)).scalars().all()
return {
"total_channels": len(channels),
"total_subscribers": total_subscribers,
"total_raw_posts": len(all_posts),
"total_drafts": len(all_d),
"total_queued": len([q for q in all_q if q.status == "queued"]),
"total_published": len([q for q in all_q if q.status in ["published", "success"]]),
"channels": [
{
"id": str(c.id),
"handle": c.telegram_handle,
"title": c.title,
"niche": c.niche,
"subscribers": c.subscriber_count or 0,
"is_active": c.is_active,
"last_scraped_at": c.last_scraped_at.isoformat() if c.last_scraped_at else None
}
for c in channels
],
"hourly_distribution": [{"hour": f"{h:02d}:00", "count": cnt} for h, cnt in hourly.items()],
"protocol_distribution": [{"protocol": k, "count": v} for k, v in proto_counts.items()],
"top_viral_posts": [
{
"id": str(p.id),
"message_id": p.message_id,
"channel_handle": p.channel.telegram_handle if p.channel else "",
"channel_title": p.channel.title if p.channel else "",
"views": p.views or 0,
"text": p.original_text or "",
"media_type": p.media_type,
"media_url": p.media_url,
"post_url": p.post_url,
"posted_at": p.posted_at.isoformat() if p.posted_at else None
}
for p in viral_posts
],
"latest_posts": [
{
"id": str(p.id),
"message_id": p.message_id,
"channel_handle": p.channel.telegram_handle if p.channel else "",
"channel_title": p.channel.title if p.channel else "",
"views": p.views or 0,
"text": p.original_text or "",
"media_type": p.media_type,
"media_url": p.media_url,
"post_url": p.post_url,
"posted_at": p.posted_at.isoformat() if p.posted_at else None
}
for p in latest_posts
]
}
@app.post("/api/v1/pipeline/dispatch-now")
async def trigger_dispatch_now(db: AsyncSession = Depends(get_db)):
# Manual trigger forces dispatch of pending queued items without blocking on future scheduled_time
count = await dispatch_pending_queue(db, force=True)
return {"published_count": count}
@app.post("/api/v1/queue/{queue_id}/send-now")
async def trigger_send_single_queue_item(queue_id: str, db: AsyncSession = Depends(get_db)):
success, error = await dispatch_single_queue_item(db, queue_id)
if not success:
raise HTTPException(status_code=400, detail=error or "Failed to publish queue item")
return {"status": "success", "message": "Queue item published to Telegram successfully"}

View file

@ -0,0 +1,94 @@
import uuid
from datetime import datetime, timezone
from sqlalchemy import (
Column, String, Integer, BigInteger, Boolean, Text,
DateTime, ForeignKey, UniqueConstraint, JSON
)
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.database import Base, GUID
class Channel(Base):
__tablename__ = "channels"
id = Column(GUID, primary_key=True, default=uuid.uuid4)
telegram_handle = Column(String(128), unique=True, nullable=False, index=True)
title = Column(String(255), nullable=True)
niche = Column(String(64), nullable=False, index=True)
subscriber_count = Column(Integer, default=0)
is_active = Column(Boolean, default=True, nullable=False)
last_scraped_at = Column(DateTime(timezone=True), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
raw_posts = relationship("RawPost", back_populates="channel", cascade="all, delete-orphan")
class RawPost(Base):
__tablename__ = "raw_posts"
id = Column(GUID, primary_key=True, default=uuid.uuid4)
channel_id = Column(GUID, ForeignKey("channels.id", ondelete="CASCADE"), nullable=False, index=True)
message_id = Column(BigInteger, nullable=False)
original_text = Column(Text, nullable=True)
post_url = Column(Text, nullable=False)
media_type = Column(String(32), default="none", nullable=False)
media_url = Column(Text, nullable=True)
views = Column(Integer, default=0, index=True)
reactions = Column(Integer, default=0)
posted_at = Column(DateTime(timezone=True), nullable=False, index=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
__table_args__ = (
UniqueConstraint("channel_id", "message_id", name="uq_channel_message"),
)
channel = relationship("Channel", back_populates="raw_posts")
drafts = relationship("ContentDraft", back_populates="raw_post", cascade="all, delete-orphan")
class ContentDraft(Base):
__tablename__ = "content_drafts"
id = Column(GUID, primary_key=True, default=uuid.uuid4)
raw_post_id = Column(GUID, ForeignKey("raw_posts.id", ondelete="CASCADE"), nullable=False, index=True)
ai_generated_text = Column(Text, nullable=False)
current_text = Column(Text, nullable=False)
status = Column(String(32), default="pending", nullable=False, index=True) # pending, approved, edited, rejected, published
brand_target = Column(String(64), default="@NetVibe_VPN", nullable=False)
banner_image_url = Column(String(512), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True)
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
raw_post = relationship("RawPost", back_populates="drafts")
feedback_logs = relationship("FeedbackLog", back_populates="draft", cascade="all, delete-orphan")
queue_item = relationship("PublishQueue", back_populates="draft", uselist=False, cascade="all, delete-orphan")
class FeedbackLog(Base):
__tablename__ = "feedback_logs"
id = Column(GUID, primary_key=True, default=uuid.uuid4)
draft_id = Column(GUID, ForeignKey("content_drafts.id", ondelete="CASCADE"), nullable=False, index=True)
original_ai_text = Column(Text, nullable=False)
final_human_text = Column(Text, nullable=False)
diff_analysis = Column(JSON, default=dict, nullable=False)
rejection_reason = Column(Text, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True)
draft = relationship("ContentDraft", back_populates="feedback_logs")
class PublishQueue(Base):
__tablename__ = "publish_queue"
id = Column(GUID(), primary_key=True, default=uuid.uuid4)
draft_id = Column(GUID(), ForeignKey("content_drafts.id", ondelete="CASCADE"), nullable=False, unique=True)
scheduled_time = Column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(timezone.utc), index=True)
status = Column(String(32), default="queued", nullable=False, index=True) # queued, publishing, success, failed
telegram_msg_id = Column(BigInteger, nullable=True)
retry_count = Column(Integer, default=0, nullable=False)
error_log = Column(Text, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False)
draft = relationship("ContentDraft", back_populates="queue_item")

View file

@ -0,0 +1,63 @@
import logging
import asyncio
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from sqlalchemy import select, desc
from app.database import AsyncSessionLocal
from app.models import Channel, RawPost, ContentDraft
from app.agents.agent_a_scraper import run_channel_ingestion
from app.agents.agent_b_curator import generate_draft_for_post
from app.agents.agent_c_publisher import dispatch_pending_queue
from app.config import settings
logger = logging.getLogger("pipeline_scheduler")
scheduler = AsyncIOScheduler()
async def scheduled_scrape_and_curate():
logger.info("Executing periodic scrape and curate cycle...")
async with AsyncSessionLocal() as session:
try:
# 1. Scrape active channels
channels = (await session.execute(select(Channel).where(Channel.is_active == True))).scalars().all()
for ch in channels:
await run_channel_ingestion(session, ch, limit=10)
# 2. Curate pending raw posts
stmt_unprocessed = (
select(RawPost)
.outerjoin(ContentDraft, RawPost.id == ContentDraft.raw_post_id)
.where(ContentDraft.id == None)
.order_by(desc(RawPost.views), desc(RawPost.posted_at))
.limit(10)
)
unprocessed_posts = (await session.execute(stmt_unprocessed)).scalars().all()
for p in unprocessed_posts:
await generate_draft_for_post(session, p)
logger.info(f"Scrape & Curate completed. Curated {len(unprocessed_posts)} posts.")
except Exception as e:
logger.error(f"Scheduled scrape/curate error: {e}")
async def scheduled_publisher():
async with AsyncSessionLocal() as session:
try:
dispatched = await dispatch_pending_queue(session, batch_size=5)
if dispatched > 0:
logger.info(f"Dispatched {dispatched} posts to Telegram channel.")
except Exception as e:
logger.error(f"Scheduled publisher error: {e}")
def start_scheduler():
scheduler.add_job(
scheduled_scrape_and_curate,
"interval",
hours=settings.SCRAPE_INTERVAL_HOURS,
id="scrape_and_curate_job"
)
scheduler.add_job(
scheduled_publisher,
"interval",
seconds=settings.PUBLISH_CHECK_INTERVAL_SECONDS,
id="publisher_job"
)
scheduler.start()
logger.info("Continuous pipeline scheduler started.")

View file

@ -0,0 +1,99 @@
from datetime import datetime
from typing import Optional, List, Dict, Any
from uuid import UUID
from pydantic import BaseModel, Field
# Channel Schemas
class ChannelBase(BaseModel):
telegram_handle: str
title: Optional[str] = None
niche: str
subscriber_count: Optional[int] = 0
is_active: Optional[bool] = True
class ChannelCreate(ChannelBase):
pass
class ChannelOut(ChannelBase):
id: UUID
last_scraped_at: Optional[datetime] = None
created_at: datetime
class Config:
from_attributes = True
# Raw Post Schemas
class RawPostOut(BaseModel):
id: UUID
channel_id: UUID
message_id: int
original_text: Optional[str] = None
post_url: str
media_type: str
media_url: Optional[str] = None
views: int
reactions: int
posted_at: datetime
created_at: datetime
class Config:
from_attributes = True
# Content Draft Schemas
class DraftActionRequest(BaseModel):
action: str = Field(..., description="approve, edit_approve, reject")
text: Optional[str] = None
banner_image_url: Optional[str] = None
remove_banner: Optional[bool] = False
scheduled_time: Optional[datetime] = None
rejection_reason: Optional[str] = None
class ContentDraftOut(BaseModel):
id: UUID
raw_post_id: UUID
ai_generated_text: str
current_text: str
status: str
brand_target: str
banner_image_url: Optional[str] = None
created_at: datetime
updated_at: datetime
raw_post: Optional[RawPostOut] = None
class Config:
from_attributes = True
# Feedback Log Schemas
class FeedbackLogOut(BaseModel):
id: UUID
draft_id: UUID
original_ai_text: str
final_human_text: str
diff_analysis: Dict[str, Any]
rejection_reason: Optional[str] = None
created_at: datetime
class Config:
from_attributes = True
# Publish Queue Schemas
class PublishQueueOut(BaseModel):
id: UUID
draft_id: UUID
scheduled_time: datetime
status: str
telegram_msg_id: Optional[int] = None
retry_count: int
error_log: Optional[str] = None
created_at: datetime
updated_at: datetime
draft: Optional[ContentDraftOut] = None
class Config:
from_attributes = True
class PipelineRunResponse(BaseModel):
scraped_channels: int
new_posts: int
drafts_generated: int
errors: List[str] = []

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

View file

@ -0,0 +1 @@
Gemini_Pro_600k_Discount_Laptop.png

View file

@ -0,0 +1 @@
Gemini_Pro_600k_Discount_Robot.png

View file

@ -0,0 +1 @@
Gemini_Pro_Multi_Tier_6Gmail.png

View file

@ -0,0 +1 @@
Gemini_Pro_999k_Discount_Holo_Pedestal_6Gmail.png

View file

@ -0,0 +1 @@
Gemini_Pro_1200k_Discount_Robot_6Gmail.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 KiB

View file

@ -0,0 +1,301 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 675" width="1200" height="675">
<defs>
<!-- Background Gradients -->
<radialGradient id="bgGlowCyan" cx="15%" cy="25%" r="60%">
<stop offset="0%" stop-color="#00f3ff" stop-opacity="0.18"/>
<stop offset="100%" stop-color="#000000" stop-opacity="0"/>
</radialGradient>
<radialGradient id="bgGlowPurple" cx="85%" cy="75%" r="65%">
<stop offset="0%" stop-color="#b000ff" stop-opacity="0.22"/>
<stop offset="100%" stop-color="#000000" stop-opacity="0"/>
</radialGradient>
<radialGradient id="coreShieldGlow" cx="50%" cy="50%" r="50%">
<stop offset="0%" stop-color="#00f3ff" stop-opacity="0.25"/>
<stop offset="50%" stop-color="#b000ff" stop-opacity="0.1"/>
<stop offset="100%" stop-color="#000000" stop-opacity="0"/>
</radialGradient>
<!-- Linear Gradients -->
<linearGradient id="cyberCyan" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#00f3ff"/>
<stop offset="100%" stop-color="#00a8ff"/>
</linearGradient>
<linearGradient id="cyberPurple" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#d946ef"/>
<stop offset="100%" stop-color="#8b5cf6"/>
</linearGradient>
<linearGradient id="panelGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#111827" stop-opacity="0.85"/>
<stop offset="100%" stop-color="#070a13" stop-opacity="0.7"/>
</linearGradient>
<linearGradient id="borderGradCyan" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#00f3ff" stop-opacity="0.8"/>
<stop offset="50%" stop-color="#00f3ff" stop-opacity="0.1"/>
<stop offset="100%" stop-color="#b000ff" stop-opacity="0.6"/>
</linearGradient>
<linearGradient id="textGrad" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#ffffff"/>
<stop offset="40%" stop-color="#e0faff"/>
<stop offset="100%" stop-color="#00f3ff"/>
</linearGradient>
<!-- Glow Filters -->
<filter id="glowCyan" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="6" result="blur"/>
<feMerge>
<feMergeNode in="blur"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
<filter id="glowPurple" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="8" result="blur"/>
<feMerge>
<feMergeNode in="blur"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
<filter id="glowSoft" x="-30%" y="-30%" width="160%" height="160%">
<feGaussianBlur stdDeviation="15" result="blur"/>
<feMerge>
<feMergeNode in="blur"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
<!-- Patterns -->
<pattern id="hudGrid" width="40" height="40" patternUnits="userSpaceOnUse">
<path d="M 40 0 L 0 0 0 40" fill="none" stroke="#00f3ff" stroke-width="0.5" stroke-opacity="0.08"/>
</pattern>
<pattern id="dotGrid" width="20" height="20" patternUnits="userSpaceOnUse">
<circle cx="2" cy="2" r="1" fill="#8b5cf6" fill-opacity="0.12"/>
</pattern>
<!-- Clip Paths -->
<clipPath id="panelClip1">
<polygon points="0,0 260,0 280,20 280,75 260,95 0,95"/>
</clipPath>
<clipPath id="badgeClip">
<polygon points="10,0 100,0 110,10 110,26 100,36 0,36 0,10"/>
</clipPath>
</defs>
<!-- Deep Base Background -->
<rect width="1200" height="675" fill="#0B0F19"/>
<!-- Perspective Floor Grid (Tron style) -->
<g opacity="0.4">
<line x1="-200" y1="675" x2="400" y2="420" stroke="#00f3ff" stroke-width="0.8" stroke-opacity="0.3"/>
<line x1="100" y1="675" x2="500" y2="420" stroke="#00f3ff" stroke-width="0.8" stroke-opacity="0.3"/>
<line x1="400" y1="675" x2="600" y2="420" stroke="#00f3ff" stroke-width="0.8" stroke-opacity="0.3"/>
<line x1="700" y1="675" x2="650" y2="420" stroke="#00f3ff" stroke-width="0.8" stroke-opacity="0.3"/>
<line x1="1000" y1="675" x2="720" y2="420" stroke="#00f3ff" stroke-width="0.8" stroke-opacity="0.3"/>
<line x1="1300" y1="675" x2="800" y2="420" stroke="#00f3ff" stroke-width="0.8" stroke-opacity="0.3"/>
<!-- Horizontals -->
<line x1="0" y1="640" x2="1200" y2="640" stroke="#00f3ff" stroke-width="0.5" stroke-opacity="0.2"/>
<line x1="120" y1="580" x2="1080" y2="580" stroke="#00f3ff" stroke-width="0.6" stroke-opacity="0.25"/>
<line x1="260" y1="520" x2="940" y2="520" stroke="#00f3ff" stroke-width="0.7" stroke-opacity="0.3"/>
<line x1="380" y1="465" x2="820" y2="465" stroke="#00f3ff" stroke-width="0.8" stroke-opacity="0.35"/>
</g>
<!-- Grid Overlays -->
<rect width="1200" height="675" fill="url(#hudGrid)"/>
<rect width="1200" height="675" fill="url(#dotGrid)"/>
<!-- Ambient Glow Sources -->
<rect width="1200" height="675" fill="url(#bgGlowCyan)"/>
<rect width="1200" height="675" fill="url(#bgGlowPurple)"/>
<circle cx="920" cy="337" r="280" fill="url(#coreShieldGlow)"/>
<!-- Cybernetic Circuit Details / Vectors -->
<g stroke="#00f3ff" stroke-width="1.5" stroke-opacity="0.3" fill="none">
<path d="M 50 100 L 150 100 L 180 130 L 320 130"/>
<circle cx="50" cy="100" r="3" fill="#00f3ff"/>
<circle cx="320" cy="130" r="2" fill="#00f3ff"/>
<path d="M 1150 540 L 1020 540 L 990 510 L 850 510"/>
<circle cx="1150" cy="540" r="3" fill="#b000ff"/>
<circle cx="850" cy="510" r="2" fill="#00f3ff"/>
<path d="M 680 80 L 740 80 L 770 110 L 850 110"/>
<circle cx="680" cy="80" r="2.5" fill="#00f3ff"/>
</g>
<!-- Giant Background Typography / Watermark -->
<text x="50" y="440" font-family="'Courier New', monospace" font-size="160" font-weight="900" fill="#ffffff" fill-opacity="0.02" letter-spacing="15">REALITY</text>
<!-- Top Bar / Header HUD Elements -->
<g transform="translate(60, 45)">
<!-- Protocol Badge -->
<g>
<polygon points="0,0 150,0 165,18 150,36 0,36" fill="#111827" stroke="#00f3ff" stroke-width="1.5" opacity="0.9"/>
<line x1="3" y1="3" x2="145" y2="3" stroke="#00f3ff" stroke-width="1" stroke-opacity="0.4"/>
<circle cx="15" cy="18" r="4" fill="#00f3ff" filter="url(#glowCyan)"/>
<text x="28" y="23" font-family="'Segoe UI', Roboto, monospace" font-size="12" font-weight="900" fill="#00f3ff" letter-spacing="2">SYSTEM ACTIVE</text>
</g>
<!-- Top Corner Ticks -->
<path d="M 1030 5 L 1070 5 L 1080 15" fill="none" stroke="#8b5cf6" stroke-width="2" opacity="0.8"/>
<text x="1015" y="16" font-family="'Segoe UI', Roboto, monospace" font-size="11" fill="#8b5cf6" text-anchor="end" letter-spacing="3" opacity="0.9">SECURE UPLINK // 2025</text>
</g>
<!-- Central Left: Brand & Identification Area -->
<g transform="translate(60, 160)">
<!-- Micro Tagline -->
<g transform="translate(0, 0)">
<rect x="0" y="0" width="8" height="8" fill="#00f3ff"/>
<text x="18" y="8" font-family="'Courier New', monospace" font-size="12" font-weight="700" fill="#89a0b9" letter-spacing="4">NEXT-GEN OBFUSCATION PROXY</text>
</g>
<!-- Main Title -->
<g transform="translate(0, 75)">
<text x="0" y="0" font-family="'Segoe UI', 'Montserrat', Arial Black, sans-serif" font-size="78" font-weight="900" fill="url(#textGrad)" letter-spacing="2">NetVibe</text>
<!-- VPN Badge Offset -->
<g transform="translate(350, -62)">
<polygon points="0,5 5,0 115,0 120,5 120,45 115,50 0,50" fill="#b000ff" fill-opacity="0.15" stroke="#d946ef" stroke-width="1.5"/>
<text x="60" y="34" font-family="'Segoe UI', Arial Black, sans-serif" font-size="30" font-weight="900" fill="#d946ef" text-anchor="middle" letter-spacing="2" filter="url(#glowPurple)">VPN</text>
</g>
</g>
<!-- Cyber Decorative Underline -->
<g transform="translate(0, 100)">
<line x1="0" y1="0" x2="280" y2="0" stroke="#00f3ff" stroke-width="3" filter="url(#glowCyan)"/>
<line x1="285" y1="0" x2="330" y2="0" stroke="#b000ff" stroke-width="3"/>
<circle cx="345" cy="0" r="2.5" fill="#ffffff"/>
<line x1="355" y1="0" x2="480" y2="0" stroke="#1f293d" stroke-width="2"/>
</g>
<!-- Handle & Telegram Info Box -->
<g transform="translate(0, 135)">
<rect x="0" y="0" width="260" height="42" rx="6" fill="#111827" fill-opacity="0.8" stroke="#1f2d47" stroke-width="1.2"/>
<!-- Small Telegram Vector Logo -->
<path d="M 24 21 L 18 29 L 20 22 L 32 14 Z" fill="#00f3ff"/>
<path d="M 14 20 L 33 13 L 28 30 L 23 23 Z" fill="none" stroke="#00f3ff" stroke-width="1.5" stroke-linejoin="round"/>
<text x="44" y="26" font-family="'Segoe UI', monospace" font-size="16" font-weight="700" fill="#ffffff" letter-spacing="1.5">@NetVibe_VPN</text>
<!-- Small Signal Bars inside Tag -->
<rect x="226" y="24" width="3" height="6" fill="#00f3ff"/>
<rect x="232" y="20" width="3" height="10" fill="#00f3ff"/>
<rect x="238" y="16" width="3" height="14" fill="#00f3ff"/>
</g>
</g>
<!-- Bottom Left: High-Tech Telemetry Badges (3 Grid Panels) -->
<g transform="translate(60, 420)">
<!-- Panel 1: Protocol -->
<g transform="translate(0, 0)">
<polygon points="0,0 185,0 200,15 200,85 15,85 0,70" fill="url(#panelGrad)" stroke="url(#borderGradCyan)" stroke-width="1.2"/>
<rect x="15" y="14" width="4" height="12" fill="#00f3ff"/>
<text x="26" y="24" font-family="'Courier New', monospace" font-size="11" fill="#728ca8" font-weight="700" letter-spacing="1.5">PROTOCOL</text>
<text x="16" y="55" font-family="'Segoe UI', Roboto, sans-serif" font-size="17" font-weight="900" fill="#ffffff" letter-spacing="1">VLESS</text>
<text x="76" y="55" font-family="'Segoe UI', Roboto, sans-serif" font-size="17" font-weight="900" fill="#00f3ff" letter-spacing="1">REALITY</text>
<text x="16" y="73" font-family="'Courier New', monospace" font-size="10" fill="#00f3ff" opacity="0.7">PORT: 443 // XTLS</text>
<!-- Micro tech details -->
<line x1="150" y1="73" x2="185" y2="73" stroke="#00f3ff" stroke-width="2" stroke-opacity="0.4"/>
</g>
<!-- Panel 2: Server Location -->
<g transform="translate(220, 0)">
<polygon points="0,0 220,0 235,15 235,85 15,85 0,70" fill="url(#panelGrad)" stroke="url(#borderGradCyan)" stroke-width="1.2"/>
<rect x="15" y="14" width="4" height="12" fill="#b000ff"/>
<text x="26" y="24" font-family="'Courier New', monospace" font-size="11" fill="#728ca8" font-weight="700" letter-spacing="1.5">LOCATION / NODE</text>
<text x="16" y="55" font-family="'Segoe UI', Roboto, sans-serif" font-size="18" font-weight="900" fill="#ffffff" letter-spacing="1">GERMANY</text>
<text x="16" y="73" font-family="'Courier New', monospace" font-size="10" fill="#d946ef" opacity="0.8">HETZNER DEDICATED</text>
<!-- German Flag Cyber Minimal Pill -->
<g transform="translate(170, 42)">
<rect x="0" y="0" width="42" height="4" fill="#1a1a1a"/>
<rect x="0" y="4" width="42" height="4" fill="#ff2a4b"/>
<rect x="0" y="8" width="42" height="4" fill="#ffb800"/>
</g>
</g>
<!-- Panel 3: Performance / Ping -->
<g transform="translate(475, 0)">
<polygon points="0,0 155,0 170,15 170,85 15,85 0,70" fill="url(#panelGrad)" stroke="url(#borderGradCyan)" stroke-width="1.2"/>
<circle cx="20" cy="20" r="4" fill="#00ff88" filter="url(#glowCyan)"/>
<text x="32" y="24" font-family="'Courier New', monospace" font-size="11" fill="#728ca8" font-weight="700" letter-spacing="1.5">LATENCY</text>
<text x="16" y="58" font-family="'Segoe UI', Roboto, sans-serif" font-size="28" font-weight="900" fill="#00ff88">45</text>
<text x="60" y="58" font-family="'Segoe UI', Roboto, sans-serif" font-size="16" font-weight="800" fill="#00ff88">ms</text>
<!-- Sine Wave Ping Display -->
<path d="M 98 52 Q 104 38 110 52 T 122 52 T 134 52" fill="none" stroke="#00ff88" stroke-width="2" stroke-linecap="round"/>
<text x="16" y="74" font-family="'Courier New', monospace" font-size="9" fill="#00ff88" opacity="0.8">ULTRA-LOW JITTER</text>
</g>
</g>
<!-- Right Visual Anchor: Giant Cyber Shield & HUD Orb Core -->
<g transform="translate(900, 335)">
<!-- Outer Hex Ring Rotators -->
<polygon points="0,-240 208,-120 208,120 0,240 -208,120 -208,-120" fill="none" stroke="#b000ff" stroke-width="1.5" stroke-opacity="0.3" stroke-dasharray="10 15"/>
<polygon points="0,-220 190,-110 190,110 0,220 -190,110 -190,-110" fill="none" stroke="#00f3ff" stroke-width="1" stroke-opacity="0.2"/>
<!-- Outer Tech HUD Circles -->
<circle cx="0" cy="0" r="195" fill="none" stroke="#00f3ff" stroke-width="2" stroke-opacity="0.4" stroke-dasharray="40 20 5 20"/>
<circle cx="0" cy="0" r="175" fill="none" stroke="#b000ff" stroke-width="1.5" stroke-opacity="0.5" stroke-dasharray="8 6"/>
<circle cx="0" cy="0" r="160" fill="none" stroke="#00f3ff" stroke-width="1" stroke-opacity="0.2"/>
<!-- Concentric Meter Segments -->
<path d="M -140 -60 A 155 155 0 0 1 -60 -140" fill="none" stroke="#00f3ff" stroke-width="6" stroke-linecap="round" filter="url(#glowCyan)"/>
<path d="M 60 140 A 155 155 0 0 1 140 60" fill="none" stroke="#d946ef" stroke-width="6" stroke-linecap="round" filter="url(#glowPurple)"/>
<!-- Cybernetic Hex Security Shield Core -->
<!-- Back Outer Solid -->
<polygon points="0,-125 108,-62 108,62 0,125 -108,62 -108,-62" fill="#060913" stroke="#00f3ff" stroke-width="2.5" filter="url(#glowCyan)"/>
<!-- Inner Glowing Plate -->
<polygon points="0,-105 91,-52 91,52 0,105 -91,52 -91,-52" fill="#0d1424" fill-opacity="0.8" stroke="#8b5cf6" stroke-width="2"/>
<!-- Shield Central Icon / Cyber Lock System -->
<!-- Network Nodes inside Hexagon -->
<g stroke="#00f3ff" stroke-width="2" fill="#00f3ff">
<!-- Data Tunnel Geometry -->
<line x1="0" y1="-55" x2="0" y2="55" stroke="#b000ff" stroke-width="3" filter="url(#glowPurple)"/>
<line x1="-48" y1="-28" x2="48" y2="28" stroke="#00f3ff" stroke-width="1.5" stroke-opacity="0.7"/>
<line x1="-48" y1="28" x2="48" y2="-28" stroke="#00f3ff" stroke-width="1.5" stroke-opacity="0.7"/>
<circle cx="0" cy="-55" r="5" fill="#ffffff" filter="url(#glowCyan)"/>
<circle cx="0" cy="55" r="5" fill="#ffffff" filter="url(#glowCyan)"/>
<circle cx="-48" cy="-28" r="4"/>
<circle cx="48" cy="28" r="4"/>
<circle cx="-48" cy="28" r="4"/>
<circle cx="48" cy="-28" r="4"/>
<!-- Central Core Lock Reactor -->
<circle cx="0" cy="0" r="24" fill="#0B0F19" stroke="#00f3ff" stroke-width="3"/>
<circle cx="0" cy="0" r="10" fill="#00f3ff" filter="url(#glowCyan)"/>
</g>
<!-- Radar Crosshairs & Peripheral Coordinates -->
<line x1="-210" y1="0" x2="-180" y2="0" stroke="#00f3ff" stroke-width="2"/>
<line x1="180" y1="0" x2="210" y2="0" stroke="#00f3ff" stroke-width="2"/>
<line x1="0" y1="-210" x2="0" y2="-180" stroke="#00f3ff" stroke-width="2"/>
<line x1="0" y1="180" x2="0" y2="210" stroke="#00f3ff" stroke-width="2"/>
<text x="0" y="-140" font-family="'Courier New', monospace" font-size="10" fill="#00f3ff" text-anchor="middle" letter-spacing="3" opacity="0.8">ENCRYPTED STREAM</text>
<text x="0" y="150" font-family="'Courier New', monospace" font-size="9" fill="#d946ef" text-anchor="middle" letter-spacing="2" opacity="0.8">ZERO-LOG INGRESS</text>
</g>
<!-- Technical Framing & Corner Decals (HUD Overlay) -->
<g stroke="#00f3ff" stroke-opacity="0.6" stroke-width="2" fill="none">
<!-- Top-Left Corner Bracket -->
<path d="M 25 50 L 25 25 L 50 25"/>
<line x1="25" y1="25" x2="35" y2="35"/>
<!-- Top-Right Corner Bracket -->
<path d="M 1175 50 L 1175 25 L 1150 25"/>
<line x1="1175" y1="25" x2="1165" y2="35"/>
<!-- Bottom-Left Corner Bracket -->
<path d="M 25 625 L 25 650 L 50 650"/>
<line x1="25" y1="650" x2="35" y2="640"/>
<!-- Bottom-Right Corner Bracket -->
<path d="M 1175 625 L 1175 650 L 1150 650"/>
<line x1="1175" y1="650" x2="1165" y2="640"/>
</g>
<!-- Lower Edge Status Stream -->
<g transform="translate(60, 645)">
<text x="0" y="0" font-family="'Courier New', monospace" font-size="10" fill="#58718d" letter-spacing="2">TUNNEL: TLS_AES_128_GCM_SHA256 // FLOW: XRAY-CORE REALITY // STATUS: 100% OPERATIONAL</text>
</g>
<g transform="translate(1140, 645)">
<circle cx="-50" cy="-4" r="3" fill="#00ff88" filter="url(#glowCyan)"/>
<text x="-40" y="0" font-family="'Courier New', monospace" font-size="10" fill="#00ff88" letter-spacing="1">BYPASS GFW/DPI</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

View file

@ -0,0 +1,105 @@
-- ==============================================================================
-- Migration: 001_initial_schema.sql
-- Description: Production PostgreSQL schema for Telegram Pipeline & Curation
-- ==============================================================================
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-- Enum Types
DO $$ BEGIN
CREATE TYPE draft_status AS ENUM ('pending', 'approved', 'edited', 'rejected', 'published');
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
DO $$ BEGIN
CREATE TYPE queue_status AS ENUM ('queued', 'publishing', 'success', 'failed');
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
DO $$ BEGIN
CREATE TYPE media_type_enum AS ENUM ('none', 'photo', 'video', 'document', 'animation');
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
-- 1. Channels Table
CREATE TABLE IF NOT EXISTS channels (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
telegram_handle VARCHAR(128) NOT NULL UNIQUE,
title VARCHAR(255),
niche VARCHAR(64) NOT NULL,
subscriber_count INT DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT true,
last_scraped_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_channels_niche ON channels (niche);
CREATE INDEX IF NOT EXISTS idx_channels_active_scraped ON channels (is_active, last_scraped_at);
-- 2. Raw Posts Table
CREATE TABLE IF NOT EXISTS raw_posts (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
channel_id UUID NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
message_id BIGINT NOT NULL,
original_text TEXT,
post_url TEXT NOT NULL,
media_type media_type_enum NOT NULL DEFAULT 'none',
media_url TEXT,
views INT DEFAULT 0,
reactions INT DEFAULT 0,
posted_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT uq_channel_message UNIQUE (channel_id, message_id)
);
CREATE INDEX IF NOT EXISTS idx_raw_posts_views ON raw_posts (views DESC);
CREATE INDEX IF NOT EXISTS idx_raw_posts_posted_at ON raw_posts (posted_at DESC);
CREATE INDEX IF NOT EXISTS idx_raw_posts_channel ON raw_posts (channel_id);
-- 3. Content Drafts Table
CREATE TABLE IF NOT EXISTS content_drafts (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
raw_post_id UUID NOT NULL REFERENCES raw_posts(id) ON DELETE CASCADE,
ai_generated_text TEXT NOT NULL,
current_text TEXT NOT NULL,
status draft_status NOT NULL DEFAULT 'pending',
brand_target VARCHAR(64) NOT NULL DEFAULT '@NetVibe_VPN',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_drafts_status ON content_drafts (status);
CREATE INDEX IF NOT EXISTS idx_drafts_created_at ON content_drafts (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_drafts_raw_post ON content_drafts (raw_post_id);
-- 4. Feedback Logs Table (Active Learning Memory)
CREATE TABLE IF NOT EXISTS feedback_logs (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
draft_id UUID NOT NULL REFERENCES content_drafts(id) ON DELETE CASCADE,
original_ai_text TEXT NOT NULL,
final_human_text TEXT NOT NULL,
diff_analysis JSONB NOT NULL DEFAULT '{}'::jsonb,
rejection_reason TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_feedback_logs_created ON feedback_logs (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_feedback_logs_draft ON feedback_logs (draft_id);
-- 5. Publish Queue Table
CREATE TABLE IF NOT EXISTS publish_queue (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
draft_id UUID NOT NULL UNIQUE REFERENCES content_drafts(id) ON DELETE CASCADE,
scheduled_time TIMESTAMPTZ NOT NULL,
status queue_status NOT NULL DEFAULT 'queued',
telegram_msg_id BIGINT,
retry_count INT NOT NULL DEFAULT 0,
error_log TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_queue_dispatch ON publish_queue (status, scheduled_time ASC) WHERE status = 'queued';

View file

@ -0,0 +1,144 @@
import asyncio
import os
import re
import sqlite3
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from sqlalchemy import select, desc
from app.models import Base, Channel, RawPost, ContentDraft, PublishQueue, FeedbackLog
from app.agents.agent_a_scraper import seed_default_channels, run_channel_ingestion
from app.agents.agent_b_curator import generate_draft_for_post
DB_PATH = "/workspace/personal/VPN_chanel/backend/vpn_pipeline.db"
DATABASE_URL = f"sqlite+aiosqlite:///{DB_PATH}"
def calculate_quality_score(text: str) -> int:
"""
Score a post based on its educational, analytical, and technical value.
Penalizes raw config dumps and spam.
"""
if not text or len(text.strip()) < 30:
return 0
score = 10
t_low = text.lower()
# Educational & Tutorial Keywords (+30)
edu_words = ["آموزش", "تنظیمات", "راهنما", "کلاینت", "نحوه", "چگونه", "حل مشکل", "ارور", "رفع خطا", "ستاپ"]
for w in edu_words:
if w in t_low:
score += 25
break
# Software & Apps (+20)
app_words = ["hiddify", "v2rayng", "sing-box", "singbox", "mihomo", "clash", "outline", "nekoray", "shadowrocket", "تور", "tor"]
for w in app_words:
if w in t_low:
score += 20
break
# Censorship, Disruptions & Datacenter News (+25)
news_words = ["اختلال", "فیلترینگ", "قطعی", "کلودفلر", "پورت", "دیتاسنتر", "همراه اول", "ایرانسل", "مخابرات", "رادار", "زیرساخت", "سراسری"]
for w in news_words:
if w in t_low:
score += 25
break
# Security & Privacy (+25)
sec_words = ["امنیت", "حریم خصوصی", "بدافزار", "جاسوسی", "شنود", "لو رفتن", "رمزنگاری", "نشت", "dns", "فیشینگ"]
for w in sec_words:
if w in t_low:
score += 25
break
# Technical Optimization (+20)
tech_words = ["پینگ", "کاهش پینگ", "سرعت", "فرگمنت", "fragment", "reality", "tls", "ech", "doh", "پروتکل"]
for w in tech_words:
if w in t_low:
score += 20
break
# Bonus for well-structured long-form content
if 200 <= len(text) <= 2500:
score += 25
# Heavy Penalty for pure config dumps without educational text (-40)
raw_configs = ["vless://", "vmess://", "trojan://", "ss://"]
config_matches = sum(1 for c in raw_configs if c in t_low)
if config_matches > 0:
# If it's mostly a dump of configs
lines = [l for l in text.splitlines() if any(c in l for c in raw_configs)]
if len(lines) >= 3 or (len(text) < 300 and config_matches >= 1):
score -= 50
return score
async def main():
print("1. Cleaning old database entries...")
if os.path.exists(DB_PATH):
os.remove(DB_PATH)
print("Removed old vpn_pipeline.db")
engine = create_async_engine(DATABASE_URL)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
print("Created clean SQLite schema")
session_maker = async_sessionmaker(engine, expire_on_commit=False)
async with session_maker() as session:
print("\n2. Seeding TOP 20 high-value channels...")
await seed_default_channels(session)
channels = (await session.execute(select(Channel))).scalars().all()
print(f"Seeded {len(channels)} channels:")
for idx, ch in enumerate(channels, 1):
print(f" {idx:2d}. @{ch.telegram_handle:18} | {ch.title[:35]}")
print("\n3. Ingesting freshest posts from all 20 channels...")
for ch in channels:
try:
new_count = await run_channel_ingestion(session, ch, limit=20)
print(f"Scraped @{ch.telegram_handle}: {new_count} posts")
except Exception as e:
print(f"Error scraping @{ch.telegram_handle}: {e}")
# Fetch all ingested posts
stmt = select(RawPost)
all_posts = (await session.execute(stmt)).scalars().all()
print(f"\nTotal raw posts ingested across 20 channels: {len(all_posts)}")
# Score and rank posts by educational / tech-news quality
scored_posts = []
for p in all_posts:
s = calculate_quality_score(p.original_text or "")
if s >= 40: # Only high quality analytical/educational/news posts
scored_posts.append((s, p))
scored_posts.sort(key=lambda x: (x[0], x[1].posted_at or x[1].created_at), reverse=True)
print(f"Total high-quality educational/news candidates (score >= 40): {len(scored_posts)}")
# Print top 10 candidates
print("\nTop 10 High-Yield Educational/News Posts:")
for rank, (score, post) in enumerate(scored_posts[:10], 1):
first_l = post.original_text.splitlines()[0] if post.original_text else ""
print(f" #{rank:02d} [Score: {score:3d}] Channel: @{post.channel.telegram_handle if post.channel else 'N/A'}")
print(f" Title: {first_l[:70]}")
print("\n4. Curating top 5 educational/news posts with AI Model 01 and generating customized banners...")
top_curate = [p for _, p in scored_posts[:5]]
for idx, post in enumerate(top_curate, 1):
ch_name = post.channel.telegram_handle if post.channel else 'unknown'
print(f"\n--- Curating Educational Post {idx}/{len(top_curate)} from @{ch_name} ---")
try:
draft = await generate_draft_for_post(session, post)
print(f"Draft ID: {draft.id}")
print(f"Banner URL: {draft.banner_image_url}")
print(f"AI Generated Text Preview:\n{draft.current_text[:200]}...\n")
except Exception as e:
print(f"Error curating post {post.id}: {e}")
await engine.dispose()
print("\nRefresh and educational curation completed successfully!")
if __name__ == "__main__":
asyncio.run(main())

View file

@ -0,0 +1,19 @@
fastapi>=0.115.0
uvicorn[standard]>=0.32.0
pydantic>=2.9.0
pydantic-settings>=2.6.0
sqlalchemy>=2.0.36
asyncpg>=0.30.0
aiosqlite>=0.20.0
greenlet>=3.0.0
httpx>=0.28.0
beautifulsoup4>=4.12.3
openai>=1.54.0
apscheduler>=3.10.4
python-dotenv>=1.0.1
pillow>=10.0.0
arabic-reshaper>=3.0.0
python-bidi>=0.4.2
resvg_py>=0.5.0
python-multipart>=0.0.9
pyyaml>=6.0

View file

@ -0,0 +1,88 @@
import asyncio
import sys
import os
from datetime import datetime, timezone
# Add backend to sys.path
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
from app.database import init_db, AsyncSessionLocal
from app.models import Channel, RawPost, ContentDraft, FeedbackLog, PublishQueue
from app.agents.agent_a_scraper import run_channel_ingestion, seed_default_channels
from app.agents.agent_b_curator import generate_draft_for_post, record_human_feedback
from app.agents.agent_c_publisher import dispatch_pending_queue
from sqlalchemy import select
async def main():
print("=" * 60)
print("1. INITIALIZING DATABASE TABLES...")
await init_db()
print("-> Tables initialized successfully.")
async with AsyncSessionLocal() as session:
print("\n2. RUNNING SEED DISCOVERY & CHANNEL REGISTRATION...")
await seed_default_channels(session)
res = await session.execute(select(Channel))
channels = res.scalars().all()
print(f"-> Registered {len(channels)} channels:")
for ch in channels:
print(f" • @{ch.telegram_handle} ({ch.niche})")
print("\n3. RUNNING AGENT A (SCRAPER) ON CHANNELS...")
total_ingested = 0
for ch in channels[:2]:
print(f" Scraping channel @{ch.telegram_handle}...")
count = await run_channel_ingestion(session, ch, limit=5)
print(f" -> Ingested {count} new posts.")
total_ingested += count
# Query raw posts
stmt = select(RawPost).limit(3)
res = await session.execute(stmt)
sample_posts = res.scalars().all()
for i, post in enumerate(sample_posts, 1):
print(f" Post #{i} [ID: {post.message_id}]: {post.views} views, Media: {post.media_type}")
print(f" Original preview: {post.original_text[:80]}...")
if sample_posts:
target_post = sample_posts[0]
print(f"\n4. RUNNING AGENT B (CURATOR & COPYWRITER) ON POST {target_post.message_id}...")
draft = await generate_draft_for_post(session, target_post.id)
print("-> Generated Draft ID:", draft.id)
print("-> Status:", draft.status)
print("-> Generated Persian NetVibe Copy:\n" + "-"*40)
print(draft.current_text)
print("-" * 40)
print("\n5. SIMULATING HUMAN EDITOR EDIT & ACTIVE LEARNING DIFF...")
edited_text = draft.current_text + "\n\n💡 نکته ویژه: برای اتصال پرسرعت کانفیگ اختصاصی تست ۲۴ ساعته در بات ما فعاله!"
feedback = await record_human_feedback(
session=session,
draft_id=draft.id,
original_ai_text=draft.ai_generated_text,
final_human_text=edited_text
)
print("-> Feedback log recorded successfully:")
print(f" Similarity Ratio: {feedback.diff_analysis.get('similarity_ratio')}")
print(f" Summary: {feedback.diff_analysis.get('summary')}")
print("\n6. MOVING DRAFT TO PUBLISH QUEUE...")
q_item = PublishQueue(
draft_id=draft.id,
status='queued',
scheduled_time=datetime.now(timezone.utc)
)
session.add(q_item)
draft.status = 'approved'
await session.commit()
print("-> Draft approved and queued for dispatch.")
print("\n7. RUNNING AGENT C (TELEGRAM PUBLISHER DISPATCHER)...")
count = await dispatch_pending_queue(session)
print(f"-> Agent C processed and dispatched {count} items in queue.")
print("\n" + "=" * 60)
print("ALL TESTS COMPLETED SUCCESSFULLY!")
if __name__ == "__main__":
asyncio.run(main())

View file

@ -0,0 +1,15 @@
import resvg_py
import re
with open('/workspace/personal/VPN_chanel/backend/app/static/banners/test_ai_01.svg', 'r') as f:
svg_data = f.read()
# Extract pure svg tag
m = re.search(r'(<svg[\s\S]*?</svg>)', svg_data)
if m:
svg_data = m.group(1)
png_bytes = resvg_py.svg_to_bytes(svg_data)
with open('/workspace/personal/VPN_chanel/backend/app/static/banners/test_ai_01.png', 'wb') as f:
f.write(png_bytes)
print('Successfully converted to PNG, size:', len(png_bytes), 'bytes')

View file

@ -0,0 +1,38 @@
services:
backend:
image: netvibe-backend:latest
container_name: netvibe-backend
restart: unless-stopped
volumes:
- /workspace/personal/ehsan/dashboards/VPN_chanel/backend/vpn_pipeline.db:/app/vpn_pipeline.db
- /workspace/personal/ehsan/dashboards/VPN_chanel/backend/app/static:/app/app/static
- /workspace/personal/ehsan/dashboards/VPN_chanel/backend/.env:/app/.env
environment:
- PYTHONUNBUFFERED=1
mem_limit: 160m
cpus: 0.2
networks:
- netvibe-net
- ekeepa_hermes
frontend:
image: netvibe-frontend:latest
container_name: netvibe-frontend
restart: unless-stopped
environment:
- INTERNAL_BACKEND_URL=http://netvibe-backend:8000
- NODE_OPTIONS=--max-old-space-size=64
- PORT=3000
depends_on:
- backend
mem_limit: 96m
cpus: 0.2
networks:
- netvibe-net
- ekeepa_hermes
networks:
netvibe-net:
driver: bridge
ekeepa_hermes:
external: true

View file

@ -0,0 +1,15 @@
import urllib.request
import re
urls = ['104', '110', '114', '120']
for pid in urls:
try:
req = urllib.request.Request(f"https://t.me/NetVibe_VPN/{pid}", headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'})
html = urllib.request.urlopen(req).read().decode('utf-8')
m = re.findall(r'property="og:image"\s+content="([^"]+)"', html)
if m:
img_url = m[0]
print(f"Downloading {pid}: {img_url}")
urllib.request.urlretrieve(img_url, f"/tmp/netvibe_{pid}.jpg")
except Exception as e:
print(f"Error {pid}: {e}")

View file

@ -0,0 +1 @@
-4i-VIMVgHeLQS5ZqIuyn

View file

@ -0,0 +1,47 @@
{
"pages": {
"/_not-found/page": [
"static/chunks/webpack-29957205745576aa.js",
"static/chunks/fd9d1056-cf48984c1108c87a.js",
"static/chunks/117-07cd2ade56352db2.js",
"static/chunks/main-app-a6b7f3492c17ffae.js",
"static/chunks/app/_not-found/page-41ffdbb4455d3b7e.js"
],
"/layout": [
"static/chunks/webpack-29957205745576aa.js",
"static/chunks/fd9d1056-cf48984c1108c87a.js",
"static/chunks/117-07cd2ade56352db2.js",
"static/chunks/main-app-a6b7f3492c17ffae.js",
"static/css/ae85ede501883e01.css",
"static/chunks/app/layout-6b2961dba121edec.js"
],
"/channels/page": [
"static/chunks/webpack-29957205745576aa.js",
"static/chunks/fd9d1056-cf48984c1108c87a.js",
"static/chunks/117-07cd2ade56352db2.js",
"static/chunks/main-app-a6b7f3492c17ffae.js",
"static/chunks/app/channels/page-3d045a2043b9dc4b.js"
],
"/feedback/page": [
"static/chunks/webpack-29957205745576aa.js",
"static/chunks/fd9d1056-cf48984c1108c87a.js",
"static/chunks/117-07cd2ade56352db2.js",
"static/chunks/main-app-a6b7f3492c17ffae.js",
"static/chunks/app/feedback/page-696b3a8e9785685c.js"
],
"/queue/page": [
"static/chunks/webpack-29957205745576aa.js",
"static/chunks/fd9d1056-cf48984c1108c87a.js",
"static/chunks/117-07cd2ade56352db2.js",
"static/chunks/main-app-a6b7f3492c17ffae.js",
"static/chunks/app/queue/page-44da436b43795024.js"
],
"/page": [
"static/chunks/webpack-29957205745576aa.js",
"static/chunks/fd9d1056-cf48984c1108c87a.js",
"static/chunks/117-07cd2ade56352db2.js",
"static/chunks/main-app-a6b7f3492c17ffae.js",
"static/chunks/app/page-acae020347f8bae3.js"
]
}
}

View file

@ -0,0 +1 @@
{"/_not-found/page":"/_not-found","/channels/page":"/channels","/feedback/page":"/feedback","/queue/page":"/queue","/page":"/"}

View file

@ -0,0 +1,32 @@
{
"polyfillFiles": [
"static/chunks/polyfills-42372ed130431b0a.js"
],
"devFiles": [],
"ampDevFiles": [],
"lowPriorityFiles": [
"static/-4i-VIMVgHeLQS5ZqIuyn/_buildManifest.js",
"static/-4i-VIMVgHeLQS5ZqIuyn/_ssgManifest.js"
],
"rootMainFiles": [
"static/chunks/webpack-29957205745576aa.js",
"static/chunks/fd9d1056-cf48984c1108c87a.js",
"static/chunks/117-07cd2ade56352db2.js",
"static/chunks/main-app-a6b7f3492c17ffae.js"
],
"pages": {
"/_app": [
"static/chunks/webpack-29957205745576aa.js",
"static/chunks/framework-f66176bb897dc684.js",
"static/chunks/main-de370cc56804d9e7.js",
"static/chunks/pages/_app-72b849fbd24ac258.js"
],
"/_error": [
"static/chunks/webpack-29957205745576aa.js",
"static/chunks/framework-f66176bb897dc684.js",
"static/chunks/main-de370cc56804d9e7.js",
"static/chunks/pages/_error-7ba65e1336b92748.js"
]
},
"ampFirstPages": []
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,7 @@
{
"telemetry": {
"notifiedAt": "1792484454481",
"anonymousId": "7620f821d758f0b3f29d498c408d9dbb3bceb6b80314a12d010ce3ca0464621c",
"salt": "606a5d1e942a560336063f1ee2a7a48d"
}
}

Some files were not shown because too many files have changed in this diff Show more