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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import json
|
| 4 |
+
import asyncio
|
| 5 |
+
import logging
|
| 6 |
+
from typing import Optional, Dict, Any, List, Tuple
|
| 7 |
+
import httpx
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
GLOBAL_COOLDOWN = 3600
|
| 12 |
+
KEY_COOLDOWN = 300
|
| 13 |
+
RATE_LIMIT_COOLDOWN = 60
|
| 14 |
+
QUOTA_COOLDOWN = 43200
|
| 15 |
+
TIMEOUT = 30.0
|
| 16 |
+
MODEL_CACHE_TTL = 3600
|
| 17 |
+
MODEL_CACHE_RETRY_COOLDOWN = 300
|
| 18 |
+
MODEL_404_BLACKLIST_TTL = 6 * 3600
|
| 19 |
+
PROVIDER_ORDER = ["gemini", "groq", "openrouter"]
|
| 20 |
+
_IRRELEVANT_MODEL_HINTS = (
|
| 21 |
+
"embedding", "imagen", "veo", "tts", "lyria", "live", "robotics",
|
| 22 |
+
"image", "aqa", "learnlm", "whisper", "tts", "stt", "moderation",
|
| 23 |
+
"dall-e", "dalle", "stable-diffusion", "sdxl",
|
| 24 |
+
"audio", "speech", "control", "vision", "preview",
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _empty_perf() -> Dict[str, Any]:
|
| 29 |
+
return {
|
| 30 |
+
"started_at": int(time.time()),
|
| 31 |
+
"requests": 0,
|
| 32 |
+
"success": 0,
|
| 33 |
+
"errors": 0,
|
| 34 |
+
"timeouts": 0,
|
| 35 |
+
"rate_limited": 0,
|
| 36 |
+
"auth_failures": 0,
|
| 37 |
+
"latency_ms_total": 0,
|
| 38 |
+
"by_provider": {},
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class AllProvidersExhausted(Exception):
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class NoAvailableAIProvider(AllProvidersExhausted):
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _rank_model(name: str) -> tuple:
|
| 51 |
+
n = name.lower()
|
| 52 |
+
if any(h in n for h in _IRRELEVANT_MODEL_HINTS):
|
| 53 |
+
return (99,)
|
| 54 |
+
if "gemini" in n:
|
| 55 |
+
is_preview = "preview" in n or "-exp" in n or n.endswith("exp")
|
| 56 |
+
if "flash" in n and not is_preview:
|
| 57 |
+
return (1,)
|
| 58 |
+
if "pro" in n and not is_preview:
|
| 59 |
+
return (2,)
|
| 60 |
+
if not is_preview:
|
| 61 |
+
return (3,)
|
| 62 |
+
return (4,)
|
| 63 |
+
stable = 0 if ("stable" in n or "production" in n or "latest" in n) else 1
|
| 64 |
+
fast = 0 if "flash" in n else (0 if "mini" in n else 1)
|
| 65 |
+
context = 0 if "128k" in n or "1m" in n else 1
|
| 66 |
+
return (stable, fast, context)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
PROVIDER_CONFIGS = {
|
| 70 |
+
"gemini": {
|
| 71 |
+
"api_base": "https://generativelanguage.googleapis.com/v1beta/models",
|
| 72 |
+
"env_prefix": "GEMINI_KEY_",
|
| 73 |
+
"timeout": 60,
|
| 74 |
+
},
|
| 75 |
+
"groq": {
|
| 76 |
+
"api_base": "https://api.groq.com/openai/v1",
|
| 77 |
+
"env_prefix": "GROQ_KEY_",
|
| 78 |
+
"timeout": 60,
|
| 79 |
+
},
|
| 80 |
+
"openrouter": {
|
| 81 |
+
"api_base": "https://openrouter.ai/api/v1",
|
| 82 |
+
"env_prefix": "OPENROUTER_KEY_",
|
| 83 |
+
"timeout": 60,
|
| 84 |
+
},
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
async def _discover_gemini_models(http: httpx.AsyncClient, api_key: str) -> list:
|
| 89 |
+
url = f"{PROVIDER_CONFIGS['gemini']['api_base']}?key={api_key}&pageSize=200"
|
| 90 |
+
try:
|
| 91 |
+
resp = await http.get(url, timeout=TIMEOUT)
|
| 92 |
+
if resp.status_code != 200:
|
| 93 |
+
return []
|
| 94 |
+
data = resp.json()
|
| 95 |
+
names = []
|
| 96 |
+
for m in data.get("models", []):
|
| 97 |
+
methods = m.get("supportedGenerationMethods", [])
|
| 98 |
+
if "generateContent" not in methods:
|
| 99 |
+
continue
|
| 100 |
+
short = m.get("name", "").split("/")[-1]
|
| 101 |
+
if not short.startswith("gemini"):
|
| 102 |
+
continue
|
| 103 |
+
names.append(short)
|
| 104 |
+
return sorted(set(names), key=_rank_model)
|
| 105 |
+
except Exception:
|
| 106 |
+
return []
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
async def _discover_openai_models(http: httpx.AsyncClient, base_url: str, api_key: str) -> list:
|
| 110 |
+
url = f"{base_url}/models"
|
| 111 |
+
headers = {"Authorization": f"Bearer {api_key}"}
|
| 112 |
+
try:
|
| 113 |
+
resp = await http.get(url, headers=headers, timeout=TIMEOUT)
|
| 114 |
+
if resp.status_code != 200:
|
| 115 |
+
logger.warning(f"{base_url}/models returned {resp.status_code}")
|
| 116 |
+
return []
|
| 117 |
+
data = resp.json()
|
| 118 |
+
models_raw = data.get("data", [])
|
| 119 |
+
names = []
|
| 120 |
+
for m in models_raw:
|
| 121 |
+
mid = m.get("id", "")
|
| 122 |
+
if any(h in mid.lower() for h in ("embedding", "whisper", "tts", "stt", "moderation", "dall-e", "audio", "speech", "vision", "preview")):
|
| 123 |
+
continue
|
| 124 |
+
names.append(mid)
|
| 125 |
+
result = sorted(set(names), key=_rank_model)
|
| 126 |
+
logger.info(f"{base_url}/models: found {len(result)} usable models")
|
| 127 |
+
return result
|
| 128 |
+
except Exception as e:
|
| 129 |
+
logger.warning(f"{base_url}/models: exception: {e}")
|
| 130 |
+
return []
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
_model_cache: Dict[str, Dict[str, Any]] = {}
|
| 134 |
+
_model_cache_lock = asyncio.Lock()
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
async def get_models(provider: str, http: httpx.AsyncClient, api_key: str, force: bool = False) -> list:
|
| 138 |
+
cfg = PROVIDER_CONFIGS.get(provider)
|
| 139 |
+
if not cfg:
|
| 140 |
+
return []
|
| 141 |
+
now = time.time()
|
| 142 |
+
async with _model_cache_lock:
|
| 143 |
+
cached = _model_cache.get(provider, {})
|
| 144 |
+
if not force and cached.get("models") and (now - cached.get("fetched_at", 0) < MODEL_CACHE_TTL):
|
| 145 |
+
return cached["models"]
|
| 146 |
+
if not force and not cached.get("models") and (now - cached.get("last_attempt", 0) < MODEL_CACHE_RETRY_COOLDOWN):
|
| 147 |
+
return cached.get("models", [])
|
| 148 |
+
cached["last_attempt"] = now
|
| 149 |
+
_model_cache[provider] = cached
|
| 150 |
+
if provider == "gemini":
|
| 151 |
+
fetched = await _discover_gemini_models(http, api_key)
|
| 152 |
+
else:
|
| 153 |
+
fetched = await _discover_openai_models(http, cfg["api_base"], api_key)
|
| 154 |
+
async with _model_cache_lock:
|
| 155 |
+
if fetched:
|
| 156 |
+
_model_cache[provider] = {"models": fetched, "fetched_at": now, "last_attempt": now}
|
| 157 |
+
logger.info(f"{provider}: refreshed model list ({len(fetched)} usable): {fetched[:4]}")
|
| 158 |
+
return fetched
|
| 159 |
+
return _model_cache.get(provider, {}).get("models", [])
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def invalidate_model_cache(provider: str = None):
|
| 163 |
+
if provider:
|
| 164 |
+
_model_cache.pop(provider, None)
|
| 165 |
+
else:
|
| 166 |
+
_model_cache.clear()
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
async def _gemini_chat(http: httpx.AsyncClient, api_key: str, model: str, prompt: str, system: str = None) -> Tuple[int, Any]:
|
| 170 |
+
body = {
|
| 171 |
+
"contents": [{"parts": [{"text": prompt}]}],
|
| 172 |
+
"generationConfig": {"temperature": 0.7, "maxOutputTokens": 4096},
|
| 173 |
+
}
|
| 174 |
+
if system:
|
| 175 |
+
body["systemInstruction"] = {"parts": [{"text": system}]}
|
| 176 |
+
url = f"{PROVIDER_CONFIGS['gemini']['api_base']}/{model}:generateContent?key={api_key}"
|
| 177 |
+
resp = await http.post(url, json=body, timeout=TIMEOUT)
|
| 178 |
+
if resp.status_code == 200:
|
| 179 |
+
data = resp.json()
|
| 180 |
+
candidates = data.get("candidates", [])
|
| 181 |
+
if candidates:
|
| 182 |
+
text = candidates[0].get("content", {}).get("parts", [{}])[0].get("text", "")
|
| 183 |
+
return (200, text)
|
| 184 |
+
return (200, "")
|
| 185 |
+
error_data = {}
|
| 186 |
+
try:
|
| 187 |
+
error_data = resp.json()
|
| 188 |
+
except Exception:
|
| 189 |
+
pass
|
| 190 |
+
error_obj = error_data.get("error", {})
|
| 191 |
+
status = error_obj.get("status", "UNKNOWN")
|
| 192 |
+
message = error_obj.get("message", resp.reason_phrase)
|
| 193 |
+
body_preview = resp.text[:500]
|
| 194 |
+
logger.warning(
|
| 195 |
+
f"Gemini API error: Endpoint={url} Code={resp.status_code} "
|
| 196 |
+
f"GoogleStatus={status} Message={message} Body={body_preview}"
|
| 197 |
+
)
|
| 198 |
+
return (resp.status_code, {"google_status": status, "google_message": message, "body": body_preview})
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
async def _openai_chat(http: httpx.AsyncClient, base_url: str, api_key: str, model: str, prompt: str, system: str = None) -> Tuple[int, Any]:
|
| 202 |
+
headers = {
|
| 203 |
+
"Authorization": f"Bearer {api_key}",
|
| 204 |
+
"Content-Type": "application/json",
|
| 205 |
+
}
|
| 206 |
+
if "openrouter" in base_url:
|
| 207 |
+
headers["HTTP-Referer"] = "https://t.me/blogger_publisher"
|
| 208 |
+
headers["X-Title"] = "BloggerPublisher"
|
| 209 |
+
body = {
|
| 210 |
+
"model": model,
|
| 211 |
+
"messages": [],
|
| 212 |
+
"temperature": 0.7,
|
| 213 |
+
"max_tokens": 4096,
|
| 214 |
+
}
|
| 215 |
+
if system:
|
| 216 |
+
body["messages"].append({"role": "system", "content": system})
|
| 217 |
+
body["messages"].append({"role": "user", "content": prompt})
|
| 218 |
+
url = f"{base_url}/chat/completions"
|
| 219 |
+
resp = await http.post(url, headers=headers, json=body, timeout=TIMEOUT)
|
| 220 |
+
if resp.status_code == 200:
|
| 221 |
+
data = resp.json()
|
| 222 |
+
choices = data.get("choices", [])
|
| 223 |
+
if choices:
|
| 224 |
+
text = choices[0].get("message", {}).get("content", "")
|
| 225 |
+
return (200, text)
|
| 226 |
+
return (200, "")
|
| 227 |
+
error_data = {}
|
| 228 |
+
try:
|
| 229 |
+
error_data = resp.json()
|
| 230 |
+
except Exception:
|
| 231 |
+
pass
|
| 232 |
+
err = error_data.get("error", {})
|
| 233 |
+
message = err.get("message", resp.reason_phrase)
|
| 234 |
+
body_preview = resp.text[:500]
|
| 235 |
+
provider_label = "OpenRouter" if "openrouter" in base_url else "OpenAI"
|
| 236 |
+
logger.warning(
|
| 237 |
+
f"{provider_label} API error: Endpoint={url} Code={resp.status_code} "
|
| 238 |
+
f"Message={message} Body={body_preview}"
|
| 239 |
+
)
|
| 240 |
+
return (resp.status_code, {"message": message, "body": body_preview})
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class AIKeyManager:
|
| 244 |
+
def __init__(self, db):
|
| 245 |
+
self.db = db
|
| 246 |
+
self._env_keys: Dict[str, dict] = {}
|
| 247 |
+
self._keys: Dict[str, dict] = {}
|
| 248 |
+
self._cooldown_until: Dict[str, float] = {}
|
| 249 |
+
self._global_cooldown_until: float = 0.0
|
| 250 |
+
self._provider_index: Dict[str, int] = {}
|
| 251 |
+
self._lock = asyncio.Lock()
|
| 252 |
+
self._perf: Dict[str, Any] = _empty_perf()
|
| 253 |
+
self._load_env_keys_once()
|
| 254 |
+
self._merge_db_keys()
|
| 255 |
+
self._restore_state()
|
| 256 |
+
self._log_startup_summary()
|
| 257 |
+
|
| 258 |
+
def _log_startup_summary(self):
|
| 259 |
+
counts: Dict[str, int] = {}
|
| 260 |
+
for k in self._keys.values():
|
| 261 |
+
p = k.get("_provider", "unknown")
|
| 262 |
+
counts[p] = counts.get(p, 0) + 1
|
| 263 |
+
logger.info("Loading AI Providers...")
|
| 264 |
+
providers_created = 0
|
| 265 |
+
for p in PROVIDER_ORDER:
|
| 266 |
+
c = counts.get(p, 0)
|
| 267 |
+
if c:
|
| 268 |
+
logger.info(f"{p.capitalize()} Keys Loaded: {c}")
|
| 269 |
+
providers_created += 1
|
| 270 |
+
logger.info(f"Providers Created: {providers_created}")
|
| 271 |
+
logger.info(f"Total Keys: {len(self._keys)}")
|
| 272 |
+
models_summary = ", ".join(
|
| 273 |
+
f"{p}: {len(_model_cache.get(p, {}).get('models', [])) if _model_cache.get(p, {}).get('models') else 'pending'}"
|
| 274 |
+
for p in PROVIDER_ORDER
|
| 275 |
+
)
|
| 276 |
+
logger.info(f"Models Loaded: {models_summary}")
|
| 277 |
+
logger.info("AI Manager Ready")
|
| 278 |
+
|
| 279 |
+
def _load_env_keys_once(self):
|
| 280 |
+
"""Scan env vars once at startup. Never called again."""
|
| 281 |
+
self._env_keys = {}
|
| 282 |
+
seen_val: Dict[str, str] = {}
|
| 283 |
+
for provider in PROVIDER_ORDER:
|
| 284 |
+
prefix = PROVIDER_CONFIGS[provider]["env_prefix"]
|
| 285 |
+
prefix_upper = prefix.upper()
|
| 286 |
+
for env_name, value in os.environ.items():
|
| 287 |
+
if not env_name.upper().startswith(prefix_upper):
|
| 288 |
+
continue
|
| 289 |
+
val = value.strip()
|
| 290 |
+
if not val:
|
| 291 |
+
continue
|
| 292 |
+
if val in seen_val:
|
| 293 |
+
display = env_name.upper()
|
| 294 |
+
existing = seen_val[val].upper()
|
| 295 |
+
logger.warning(f"Dropping duplicate {display} (same value as {existing})")
|
| 296 |
+
continue
|
| 297 |
+
seen_val[val] = env_name
|
| 298 |
+
display_name = env_name.upper()
|
| 299 |
+
self._env_keys[env_name.lower()] = {
|
| 300 |
+
"name": display_name,
|
| 301 |
+
"key": val,
|
| 302 |
+
"enabled": True,
|
| 303 |
+
"usage_count": 0,
|
| 304 |
+
"error_count": 0,
|
| 305 |
+
"last_used": 0,
|
| 306 |
+
"added_at": 0,
|
| 307 |
+
"_source": "env",
|
| 308 |
+
"_provider": provider,
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
def _merge_db_keys(self):
|
| 312 |
+
"""Merge DB keys into self._keys (env keys have priority)."""
|
| 313 |
+
self._keys = dict(self._env_keys)
|
| 314 |
+
raw = self.db.get_all_ai_keys()
|
| 315 |
+
seen_vals: set = set(v["key"] for v in self._keys.values() if v.get("key"))
|
| 316 |
+
for kid, kdata in raw.items():
|
| 317 |
+
if not kdata.get("enabled", True):
|
| 318 |
+
continue
|
| 319 |
+
val = kdata.get("key", "")
|
| 320 |
+
if not val or val in seen_vals:
|
| 321 |
+
continue
|
| 322 |
+
seen_vals.add(val)
|
| 323 |
+
kdata["_provider"] = "gemini"
|
| 324 |
+
if "name" not in kdata or not kdata.get("name"):
|
| 325 |
+
kdata["name"] = kid
|
| 326 |
+
self._keys[kid] = kdata
|
| 327 |
+
|
| 328 |
+
def _restore_state(self):
|
| 329 |
+
try:
|
| 330 |
+
state = self.db.get_gemini_state()
|
| 331 |
+
self._global_cooldown_until = state.get("global_cooldown_until", 0.0)
|
| 332 |
+
for kid, expires in state.get("per_key_cooldowns", {}).items():
|
| 333 |
+
if expires > time.time():
|
| 334 |
+
self._cooldown_until[kid] = expires
|
| 335 |
+
self._provider_index = state.get("provider_index", {})
|
| 336 |
+
perf = state.get("perf")
|
| 337 |
+
if isinstance(perf, dict) and perf.get("started_at"):
|
| 338 |
+
base = _empty_perf()
|
| 339 |
+
base.update(perf)
|
| 340 |
+
self._perf = base
|
| 341 |
+
if self._global_cooldown_until > time.time():
|
| 342 |
+
remaining = int(self._global_cooldown_until - time.time())
|
| 343 |
+
logger.info(f"Restored global cooldown: {remaining}s remaining")
|
| 344 |
+
except Exception as e:
|
| 345 |
+
logger.warning(f"Failed to restore AI state: {e}")
|
| 346 |
+
|
| 347 |
+
def _persist_state(self):
|
| 348 |
+
try:
|
| 349 |
+
now = time.time()
|
| 350 |
+
per_key = {k: v for k, v in self._cooldown_until.items() if v > now}
|
| 351 |
+
self.db.save_gemini_state({
|
| 352 |
+
"global_cooldown_until": self._global_cooldown_until,
|
| 353 |
+
"per_key_cooldowns": per_key,
|
| 354 |
+
"provider_index": self._provider_index,
|
| 355 |
+
"perf": self._perf,
|
| 356 |
+
"updated_at": int(now),
|
| 357 |
+
})
|
| 358 |
+
except Exception as e:
|
| 359 |
+
logger.warning(f"Failed to persist AI state: {e}")
|
| 360 |
+
|
| 361 |
+
def _key_name(self, key_id: str) -> str:
|
| 362 |
+
return self._keys.get(key_id, {}).get("name", key_id.upper())
|
| 363 |
+
|
| 364 |
+
def is_global_cooldown_active(self) -> bool:
|
| 365 |
+
return time.time() < self._global_cooldown_until
|
| 366 |
+
|
| 367 |
+
def set_global_cooldown(self, seconds: int = GLOBAL_COOLDOWN):
|
| 368 |
+
self._global_cooldown_until = time.time() + seconds
|
| 369 |
+
self._persist_state()
|
| 370 |
+
logger.info(f"Global Cooldown: {seconds}s (until {time.strftime('%H:%M:%S', time.localtime(self._global_cooldown_until))})")
|
| 371 |
+
|
| 372 |
+
def get_all_keys_summary(self) -> Dict[str, dict]:
|
| 373 |
+
return dict(self._keys)
|
| 374 |
+
|
| 375 |
+
def get_provider_keys(self, provider: str) -> List[Tuple[str, dict]]:
|
| 376 |
+
return [(k, v) for k, v in self._keys.items() if v.get("_provider") == provider]
|
| 377 |
+
|
| 378 |
+
def _key_usable(self, kid: str, kdata: dict, now: float) -> bool:
|
| 379 |
+
"""A key is usable only when enabled, not in cooldown, and carries a key value."""
|
| 380 |
+
if not kdata.get("enabled", True):
|
| 381 |
+
return False
|
| 382 |
+
if kid in self._cooldown_until and now < self._cooldown_until[kid]:
|
| 383 |
+
return False
|
| 384 |
+
if not kdata.get("key", ""):
|
| 385 |
+
return False
|
| 386 |
+
return True
|
| 387 |
+
|
| 388 |
+
def cooldown_remaining(self, key_id: str) -> int:
|
| 389 |
+
"""Seconds remaining until a key leaves its cooldown (0 = ready)."""
|
| 390 |
+
until = self._cooldown_until.get(key_id, 0.0)
|
| 391 |
+
if until > time.time():
|
| 392 |
+
return int(until - time.time())
|
| 393 |
+
return 0
|
| 394 |
+
|
| 395 |
+
async def record_perf(self, provider: str, ok: bool, latency_ms: int, reason: str = "", key_id: str = None):
|
| 396 |
+
"""Track rolling performance statistics (used by AIClient for every API call)."""
|
| 397 |
+
async with self._lock:
|
| 398 |
+
perf = self._perf
|
| 399 |
+
perf["requests"] += 1
|
| 400 |
+
if ok:
|
| 401 |
+
perf["success"] += 1
|
| 402 |
+
else:
|
| 403 |
+
perf["errors"] += 1
|
| 404 |
+
perf["latency_ms_total"] += latency_ms
|
| 405 |
+
if reason == "timeout":
|
| 406 |
+
perf["timeouts"] += 1
|
| 407 |
+
elif reason == "rate":
|
| 408 |
+
perf["rate_limited"] += 1
|
| 409 |
+
elif reason == "auth":
|
| 410 |
+
perf["auth_failures"] += 1
|
| 411 |
+
byp = perf["by_provider"].setdefault(provider, {
|
| 412 |
+
"requests": 0, "success": 0, "errors": 0, "timeouts": 0,
|
| 413 |
+
"rate_limited": 0, "latency_ms_total": 0,
|
| 414 |
+
})
|
| 415 |
+
byp["requests"] += 1
|
| 416 |
+
if ok:
|
| 417 |
+
byp["success"] += 1
|
| 418 |
+
else:
|
| 419 |
+
byp["errors"] += 1
|
| 420 |
+
if reason == "timeout":
|
| 421 |
+
byp["timeouts"] += 1
|
| 422 |
+
elif reason == "rate":
|
| 423 |
+
byp["rate_limited"] += 1
|
| 424 |
+
byp["latency_ms_total"] += latency_ms
|
| 425 |
+
if key_id and key_id in self._keys:
|
| 426 |
+
kd = self._keys[key_id]
|
| 427 |
+
kd["last_latency_ms"] = latency_ms
|
| 428 |
+
kd["last_error_reason"] = reason or ""
|
| 429 |
+
total_lat = kd.get("total_latency_ms", 0) + latency_ms
|
| 430 |
+
kd["total_latency_ms"] = total_lat
|
| 431 |
+
calls = kd.get("usage_count", 0) + kd.get("error_count", 0)
|
| 432 |
+
if calls > 0:
|
| 433 |
+
kd["avg_latency_ms"] = int(total_lat / calls)
|
| 434 |
+
self._persist_state()
|
| 435 |
+
|
| 436 |
+
def get_perf_stats(self) -> Dict[str, Any]:
|
| 437 |
+
perf = {k: v for k, v in self._perf.items()}
|
| 438 |
+
perf["success_rate"] = round((perf["success"] / perf["requests"] * 100), 1) if perf["requests"] else 0.0
|
| 439 |
+
perf["avg_latency_ms"] = int(perf["latency_ms_total"] / perf["requests"]) if perf["requests"] else 0
|
| 440 |
+
return perf
|
| 441 |
+
|
| 442 |
+
async def acquire_usable_key(self) -> Optional[Tuple[str, str, str]]:
|
| 443 |
+
async with self._lock:
|
| 444 |
+
self._merge_db_keys()
|
| 445 |
+
if not self._keys:
|
| 446 |
+
logger.warning("No AI keys configured")
|
| 447 |
+
return None
|
| 448 |
+
now = time.time()
|
| 449 |
+
for provider in PROVIDER_ORDER:
|
| 450 |
+
provider_keys = self.get_provider_keys(provider)
|
| 451 |
+
if not provider_keys:
|
| 452 |
+
continue
|
| 453 |
+
idx = self._provider_index.get(provider, -1)
|
| 454 |
+
for offset in range(len(provider_keys)):
|
| 455 |
+
key_idx = (idx + 1 + offset) % len(provider_keys)
|
| 456 |
+
kid, kdata = provider_keys[key_idx]
|
| 457 |
+
if not self._key_usable(kid, kdata, now):
|
| 458 |
+
continue
|
| 459 |
+
api_key = kdata.get("key", "")
|
| 460 |
+
self._provider_index[provider] = key_idx
|
| 461 |
+
name = self._key_name(kid)
|
| 462 |
+
logger.info(f"Using Provider: {provider.capitalize()}")
|
| 463 |
+
logger.info(f"Using Key: {name}")
|
| 464 |
+
return (provider, kid, api_key)
|
| 465 |
+
# All keys in this provider are in cooldown, disabled, or invalid
|
| 466 |
+
logger.warning(f"Provider {provider.capitalize()} exhausted")
|
| 467 |
+
cooldown_keys = []
|
| 468 |
+
for kid in self._keys:
|
| 469 |
+
if kid in self._cooldown_until and self._cooldown_until[kid] > now:
|
| 470 |
+
cooldown_keys.append(self._key_name(kid))
|
| 471 |
+
if cooldown_keys:
|
| 472 |
+
logger.warning(f"All keys in cooldown: {cooldown_keys}")
|
| 473 |
+
return None
|
| 474 |
+
|
| 475 |
+
def switch_to_next_key(self, current_kid: str) -> Optional[Tuple[str, str, str]]:
|
| 476 |
+
self._merge_db_keys()
|
| 477 |
+
now = time.time()
|
| 478 |
+
current_provider = self._keys.get(current_kid, {}).get("_provider", "")
|
| 479 |
+
# Try next key in same provider first
|
| 480 |
+
if current_provider:
|
| 481 |
+
provider_keys = self.get_provider_keys(current_provider)
|
| 482 |
+
if provider_keys:
|
| 483 |
+
idx = self._provider_index.get(current_provider, -1)
|
| 484 |
+
for offset in range(len(provider_keys)):
|
| 485 |
+
key_idx = (idx + 1 + offset) % len(provider_keys)
|
| 486 |
+
kid, kdata = provider_keys[key_idx]
|
| 487 |
+
if kid == current_kid:
|
| 488 |
+
continue
|
| 489 |
+
if not self._key_usable(kid, kdata, now):
|
| 490 |
+
continue
|
| 491 |
+
api_key = kdata.get("key", "")
|
| 492 |
+
self._provider_index[current_provider] = key_idx
|
| 493 |
+
logger.info(f"Switching Key: {self._key_name(kid)}")
|
| 494 |
+
return (current_provider, kid, api_key)
|
| 495 |
+
# Try next provider
|
| 496 |
+
found_current = False
|
| 497 |
+
for provider in PROVIDER_ORDER:
|
| 498 |
+
if not found_current:
|
| 499 |
+
if provider == current_provider:
|
| 500 |
+
found_current = True
|
| 501 |
+
continue
|
| 502 |
+
provider_keys = self.get_provider_keys(provider)
|
| 503 |
+
if not provider_keys:
|
| 504 |
+
continue
|
| 505 |
+
for kid, kdata in provider_keys:
|
| 506 |
+
if not self._key_usable(kid, kdata, now):
|
| 507 |
+
continue
|
| 508 |
+
api_key = kdata.get("key", "")
|
| 509 |
+
self._provider_index[provider] = 0
|
| 510 |
+
logger.info(f"Switching Provider: {provider.capitalize()}")
|
| 511 |
+
logger.info(f"Using Key: {self._key_name(kid)}")
|
| 512 |
+
return (provider, kid, api_key)
|
| 513 |
+
continue
|
| 514 |
+
logger.warning("No alternative key available")
|
| 515 |
+
return None
|
| 516 |
+
|
| 517 |
+
async def record_success(self, key_id: str):
|
| 518 |
+
async with self._lock:
|
| 519 |
+
if key_id in self._keys:
|
| 520 |
+
self._keys[key_id]["usage_count"] = self._keys[key_id].get("usage_count", 0) + 1
|
| 521 |
+
self._keys[key_id]["last_used"] = int(time.time())
|
| 522 |
+
self.db.increment_ai_key_usage(key_id)
|
| 523 |
+
self._cooldown_until.pop(key_id, None)
|
| 524 |
+
self._persist_state()
|
| 525 |
+
|
| 526 |
+
async def record_failure(self, key_id: str, cooldown: int = KEY_COOLDOWN):
|
| 527 |
+
async with self._lock:
|
| 528 |
+
if key_id in self._keys:
|
| 529 |
+
self._keys[key_id]["error_count"] = self._keys[key_id].get("error_count", 0) + 1
|
| 530 |
+
self.db.increment_ai_key_error(key_id)
|
| 531 |
+
self._cooldown_until[key_id] = time.time() + cooldown
|
| 532 |
+
self._persist_state()
|
| 533 |
+
logger.info(f"Key Cooldown: {self._key_name(key_id)} ({cooldown}s)")
|
| 534 |
+
|
| 535 |
+
async def record_quota_exhausted(self, key_id: str):
|
| 536 |
+
async with self._lock:
|
| 537 |
+
if key_id in self._keys:
|
| 538 |
+
self._keys[key_id]["error_count"] = self._keys[key_id].get("error_count", 0) + 10
|
| 539 |
+
self.db.increment_ai_key_error(key_id)
|
| 540 |
+
self._cooldown_until[key_id] = time.time() + QUOTA_COOLDOWN
|
| 541 |
+
self._persist_state()
|
| 542 |
+
logger.info(f"Key Cooldown: {self._key_name(key_id)} ({QUOTA_COOLDOWN}s) - quota exhausted")
|
| 543 |
+
|
| 544 |
+
async def mark_disabled(self, key_id: str):
|
| 545 |
+
async with self._lock:
|
| 546 |
+
if key_id in self._keys and self._keys[key_id].get("_source") == "env":
|
| 547 |
+
self._keys[key_id]["enabled"] = False
|
| 548 |
+
return
|
| 549 |
+
self.db.set_ai_key_enabled(key_id, False)
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
class AIClient:
|
| 553 |
+
def __init__(self, key_manager: AIKeyManager):
|
| 554 |
+
self.key_manager = key_manager
|
| 555 |
+
self._http = httpx.AsyncClient(timeout=TIMEOUT)
|
| 556 |
+
self._session_provider: Optional[str] = None
|
| 557 |
+
self._session_kid: Optional[str] = None
|
| 558 |
+
self._session_key: Optional[str] = None
|
| 559 |
+
self._session_model: Optional[str] = None
|
| 560 |
+
self._model_blacklist: Dict[str, float] = {}
|
| 561 |
+
|
| 562 |
+
def _model_blacklisted(self, model: str, now: float = None) -> bool:
|
| 563 |
+
now = now or time.time()
|
| 564 |
+
return model in self._model_blacklist and self._model_blacklist[model] > now
|
| 565 |
+
|
| 566 |
+
def _blacklist_model(self, model: str, reason: str = ""):
|
| 567 |
+
self._model_blacklist[model] = time.time() + MODEL_404_BLACKLIST_TTL
|
| 568 |
+
logger.warning(
|
| 569 |
+
f"Model blacklisted (temporarily {MODEL_404_BLACKLIST_TTL // 3600}h): {model} "
|
| 570 |
+
f"provider={self._session_provider}. Reason: {reason or '404/not found'}"
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
def _endpoint_for(self, provider: str, model: str) -> str:
|
| 574 |
+
if provider == "gemini":
|
| 575 |
+
return f"{PROVIDER_CONFIGS[provider]['api_base']}/{model}:generateContent"
|
| 576 |
+
return f"{PROVIDER_CONFIGS[provider]['api_base']}/chat/completions"
|
| 577 |
+
|
| 578 |
+
async def close(self):
|
| 579 |
+
await self._http.aclose()
|
| 580 |
+
|
| 581 |
+
async def acquire_session(self) -> bool:
|
| 582 |
+
if self._session_kid:
|
| 583 |
+
# A held session should be dropped if it fell into cooldown
|
| 584 |
+
# (e.g. another concurrent task exhausted it) so we grab a fresh key.
|
| 585 |
+
if self.key_manager.cooldown_remaining(self._session_kid) > 0:
|
| 586 |
+
logger.info(f"Session key {self._session_kid} now in cooldown, releasing session")
|
| 587 |
+
self.release_session()
|
| 588 |
+
else:
|
| 589 |
+
return True
|
| 590 |
+
if self._session_model:
|
| 591 |
+
models = await get_models(self._session_provider, self._http, self._session_key)
|
| 592 |
+
if self._session_model in models:
|
| 593 |
+
return True
|
| 594 |
+
invalidate_model_cache(self._session_provider)
|
| 595 |
+
logger.info(f"Model {self._session_model} absent from refreshed list, re-acquisition may happen")
|
| 596 |
+
result = await self.key_manager.acquire_usable_key()
|
| 597 |
+
if result:
|
| 598 |
+
self._session_provider, self._session_kid, self._session_key = result
|
| 599 |
+
models = await get_models(self._session_provider, self._http, self._session_key)
|
| 600 |
+
usable = [m for m in models if not self._model_blacklisted(m)]
|
| 601 |
+
if usable:
|
| 602 |
+
self._session_model = usable[0]
|
| 603 |
+
logger.info(f"Using Model: {self._session_model}")
|
| 604 |
+
return True
|
| 605 |
+
if not self.key_manager.is_global_cooldown_active():
|
| 606 |
+
self.key_manager.set_global_cooldown()
|
| 607 |
+
logger.error("All providers exhausted. Queue paused.")
|
| 608 |
+
return False
|
| 609 |
+
|
| 610 |
+
def release_session(self):
|
| 611 |
+
self._session_provider = None
|
| 612 |
+
self._session_kid = None
|
| 613 |
+
self._session_key = None
|
| 614 |
+
self._session_model = None
|
| 615 |
+
|
| 616 |
+
async def _pick_model(self) -> Optional[str]:
|
| 617 |
+
if self._session_model:
|
| 618 |
+
models = await get_models(self._session_provider, self._http, self._session_key)
|
| 619 |
+
if self._session_model in models and not self._model_blacklisted(self._session_model):
|
| 620 |
+
return self._session_model
|
| 621 |
+
invalidate_model_cache(self._session_provider)
|
| 622 |
+
logger.info(f"Model {self._session_model} not found/blacklisted, refreshing list...")
|
| 623 |
+
models = await get_models(self._session_provider, self._http, self._session_key, force=True)
|
| 624 |
+
else:
|
| 625 |
+
models = await get_models(self._session_provider, self._http, self._session_key)
|
| 626 |
+
usable = [m for m in models if not self._model_blacklisted(m)]
|
| 627 |
+
skipped = [m for m in models if self._model_blacklisted(m)]
|
| 628 |
+
if skipped:
|
| 629 |
+
logger.info(f"Skipping {len(skipped)} blacklisted model(s): {skipped[:4]}")
|
| 630 |
+
if usable:
|
| 631 |
+
self._session_model = usable[0]
|
| 632 |
+
logger.info(f"Using Model: {self._session_model}")
|
| 633 |
+
return self._session_model
|
| 634 |
+
return None
|
| 635 |
+
|
| 636 |
+
async def _call_api(self, prompt: str, system: str = None) -> Optional[str]:
|
| 637 |
+
provider = self._session_provider
|
| 638 |
+
api_key = self._session_key
|
| 639 |
+
visited_models = set()
|
| 640 |
+
while True:
|
| 641 |
+
model = await self._pick_model()
|
| 642 |
+
if not model:
|
| 643 |
+
logger.warning(f"No usable model for {provider}")
|
| 644 |
+
return None
|
| 645 |
+
if model in visited_models:
|
| 646 |
+
logger.warning(f"All models exhausted for {provider}")
|
| 647 |
+
return None
|
| 648 |
+
visited_models.add(model)
|
| 649 |
+
try:
|
| 650 |
+
started = time.time()
|
| 651 |
+
if provider == "gemini":
|
| 652 |
+
code, data = await _gemini_chat(self._http, api_key, model, prompt, system)
|
| 653 |
+
else:
|
| 654 |
+
base_url = PROVIDER_CONFIGS[provider]["api_base"]
|
| 655 |
+
code, data = await _openai_chat(self._http, base_url, api_key, model, prompt, system)
|
| 656 |
+
latency_ms = int((time.time() - started) * 1000)
|
| 657 |
+
except httpx.TimeoutException:
|
| 658 |
+
latency_ms = int((time.time() - started) * 1000)
|
| 659 |
+
await self.key_manager.record_perf(provider, False, latency_ms, "timeout", self._session_kid)
|
| 660 |
+
logger.warning(f"Timeout on {model}")
|
| 661 |
+
return None
|
| 662 |
+
except Exception as e:
|
| 663 |
+
latency_ms = int((time.time() - started) * 1000)
|
| 664 |
+
await self.key_manager.record_perf(provider, False, latency_ms, "error", self._session_kid)
|
| 665 |
+
logger.warning(f"Error: {e}")
|
| 666 |
+
return None
|
| 667 |
+
if code == 200:
|
| 668 |
+
if data:
|
| 669 |
+
await self.key_manager.record_success(self._session_kid)
|
| 670 |
+
await self.key_manager.record_perf(provider, True, latency_ms, "", self._session_kid)
|
| 671 |
+
return data
|
| 672 |
+
await self.key_manager.record_failure(self._session_kid)
|
| 673 |
+
await self.key_manager.record_perf(provider, False, latency_ms, "empty", self._session_kid)
|
| 674 |
+
logger.warning(
|
| 675 |
+
f"AI empty response: Provider={provider} Key={self.key_manager._key_name(self._session_kid)} "
|
| 676 |
+
f"Model={model} Code={code}"
|
| 677 |
+
)
|
| 678 |
+
return None
|
| 679 |
+
if isinstance(data, dict):
|
| 680 |
+
msg = data.get("message") or data.get("google_message") or data.get("google_status") or str(data)
|
| 681 |
+
else:
|
| 682 |
+
msg = str(data)
|
| 683 |
+
body_preview = (data.get("body") or data.get("message") or str(data))[:500] if isinstance(data, dict) else str(data)[:500]
|
| 684 |
+
model_not_found = code == 404 or any(x in msg.lower() for x in ("not found", "model_not_found", "model not found", "unknown model", "deprecated", "disabled"))
|
| 685 |
+
if model_not_found:
|
| 686 |
+
self._blacklist_model(model, msg)
|
| 687 |
+
logger.warning(
|
| 688 |
+
f"Model excluded (404/not found/deprecated): Provider={provider} "
|
| 689 |
+
f"Key={self.key_manager._key_name(self._session_kid)} Model={model} "
|
| 690 |
+
f"Endpoint={self._endpoint_for(provider, model)} Code={code} Body={body_preview}"
|
| 691 |
+
)
|
| 692 |
+
logger.warning("Trying next model...")
|
| 693 |
+
await self.key_manager.record_perf(provider, False, latency_ms, "model_not_found", self._session_kid)
|
| 694 |
+
invalidate_model_cache(provider)
|
| 695 |
+
continue
|
| 696 |
+
if code == 429 or any(x in msg.lower() for x in ("quota", "exhausted", "rate limit", "resource exhausted")):
|
| 697 |
+
name = self.key_manager._key_name(self._session_kid)
|
| 698 |
+
logger.warning(
|
| 699 |
+
f"Reason=429 (Quota/rate limit): Provider={provider} Key={name} Model={model} "
|
| 700 |
+
f"Code={code} Body={body_preview}"
|
| 701 |
+
)
|
| 702 |
+
await self.key_manager.record_perf(provider, False, latency_ms, "rate", self._session_kid)
|
| 703 |
+
await self.key_manager.record_quota_exhausted(self._session_kid)
|
| 704 |
+
elif code == 401:
|
| 705 |
+
logger.warning(f"Reason=401 (Invalid API key): Provider={provider} Model={model} Body={body_preview}")
|
| 706 |
+
await self.key_manager.record_perf(provider, False, latency_ms, "auth", self._session_kid)
|
| 707 |
+
await self.key_manager.mark_disabled(self._session_kid)
|
| 708 |
+
elif code == 402:
|
| 709 |
+
# Payment required (e.g. OpenRouter out of credits): the key is NOT broken.
|
| 710 |
+
# Put it on a normal cooldown and simply try the next key.
|
| 711 |
+
name = self.key_manager._key_name(self._session_kid)
|
| 712 |
+
logger.warning(
|
| 713 |
+
f"Reason=402 (Payment Required / insufficient credits): Provider={provider} Key={name} "
|
| 714 |
+
f"Model={model} Code={code} Body={body_preview}. Key intact, cooldown then next key."
|
| 715 |
+
)
|
| 716 |
+
await self.key_manager.record_perf(provider, False, latency_ms, "payment", self._session_kid)
|
| 717 |
+
await self.key_manager.record_failure(self._session_kid, KEY_COOLDOWN)
|
| 718 |
+
elif code == 403:
|
| 719 |
+
logger.warning(f"Reason=403 (Forbidden): Provider={provider} Key={self.key_manager._key_name(self._session_kid)} Model={model}")
|
| 720 |
+
await self.key_manager.record_perf(provider, False, latency_ms, "forbidden", self._session_kid)
|
| 721 |
+
await self.key_manager.record_failure(self._session_kid)
|
| 722 |
+
else:
|
| 723 |
+
logger.warning(
|
| 724 |
+
f"Reason={code}: Provider={provider} Key={self.key_manager._key_name(self._session_kid)} "
|
| 725 |
+
f"Model={model} Endpoint={self._endpoint_for(provider, model)} Body={body_preview}"
|
| 726 |
+
)
|
| 727 |
+
await self.key_manager.record_perf(provider, False, latency_ms, f"http_{code}", self._session_kid)
|
| 728 |
+
await self.key_manager.record_failure(self._session_kid, RATE_LIMIT_COOLDOWN)
|
| 729 |
+
return None
|
| 730 |
+
|
| 731 |
+
async def generate(self, prompt: str, system: str = None) -> Optional[str]:
|
| 732 |
+
visited_keys = set()
|
| 733 |
+
visited_providers = set()
|
| 734 |
+
attempt = 0
|
| 735 |
+
while attempt < 100:
|
| 736 |
+
attempt += 1
|
| 737 |
+
if not self._session_kid or not self._session_key:
|
| 738 |
+
if self.key_manager.is_global_cooldown_active():
|
| 739 |
+
logger.info("No AI Provider Available")
|
| 740 |
+
raise NoAvailableAIProvider("Global cooldown is active")
|
| 741 |
+
result = await self.key_manager.acquire_usable_key()
|
| 742 |
+
if result is None:
|
| 743 |
+
if not self.key_manager.is_global_cooldown_active():
|
| 744 |
+
self.key_manager.set_global_cooldown()
|
| 745 |
+
logger.info("No AI Provider Available")
|
| 746 |
+
raise NoAvailableAIProvider("No AI provider available")
|
| 747 |
+
if result[1] in visited_keys:
|
| 748 |
+
self.key_manager._cooldown_until[result[1]] = time.time() + 1
|
| 749 |
+
self.key_manager._persist_state()
|
| 750 |
+
continue
|
| 751 |
+
self._session_provider, self._session_kid, self._session_key = result
|
| 752 |
+
self._session_model = None
|
| 753 |
+
kid = self._session_kid
|
| 754 |
+
provider = self._session_provider
|
| 755 |
+
if kid in visited_keys:
|
| 756 |
+
self.release_session()
|
| 757 |
+
continue
|
| 758 |
+
visited_keys.add(kid)
|
| 759 |
+
visited_providers.add(provider)
|
| 760 |
+
model = await self._pick_model()
|
| 761 |
+
logger.info(f"Provider={provider}")
|
| 762 |
+
logger.info(f"Key={self.key_manager._key_name(kid)}")
|
| 763 |
+
if model:
|
| 764 |
+
logger.info(f"Model={model}")
|
| 765 |
+
logger.info(f"Attempt={attempt}")
|
| 766 |
+
result = await self._call_api(prompt, system)
|
| 767 |
+
if result is not None:
|
| 768 |
+
return result
|
| 769 |
+
switch = self.key_manager.switch_to_next_key(kid)
|
| 770 |
+
if switch:
|
| 771 |
+
if switch[1] in visited_keys:
|
| 772 |
+
self.key_manager._cooldown_until[switch[1]] = time.time() + 1
|
| 773 |
+
self.key_manager._persist_state()
|
| 774 |
+
self.release_session()
|
| 775 |
+
continue
|
| 776 |
+
old_provider = self._session_provider
|
| 777 |
+
self._session_provider, self._session_kid, self._session_key = switch
|
| 778 |
+
self._session_model = None
|
| 779 |
+
if switch[0] != old_provider:
|
| 780 |
+
logger.info(f"Finished Provider={old_provider}")
|
| 781 |
+
continue
|
| 782 |
+
logger.info("Finished Key Rotation")
|
| 783 |
+
logger.info("No AI Provider Available")
|
| 784 |
+
if not self.key_manager.is_global_cooldown_active():
|
| 785 |
+
self.key_manager.set_global_cooldown()
|
| 786 |
+
raise NoAvailableAIProvider("No AI provider available")
|
| 787 |
+
raise NoAvailableAIProvider("Max attempts exceeded")
|
| 788 |
+
|
| 789 |
+
async def generate_json(self, prompt: str, system: str = None) -> Optional[dict]:
|
| 790 |
+
text = await self.generate(prompt, system)
|
| 791 |
+
if not text:
|
| 792 |
+
return None
|
| 793 |
+
text = text.strip()
|
| 794 |
+
if text.startswith("```"):
|
| 795 |
+
for marker in ["```json", "```JSON", "```"]:
|
| 796 |
+
if text.startswith(marker):
|
| 797 |
+
text = text[len(marker):]
|
| 798 |
+
break
|
| 799 |
+
end_idx = text.rfind("```")
|
| 800 |
+
if end_idx != -1:
|
| 801 |
+
text = text[:end_idx]
|
| 802 |
+
text = text.strip()
|
| 803 |
+
try:
|
| 804 |
+
return json.loads(text)
|
| 805 |
+
except json.JSONDecodeError:
|
| 806 |
+
logger.warning(f"AI response is not valid JSON, returning raw text")
|
| 807 |
+
return {"raw": text}
|
modules/blogger/processor.py
ADDED
|
@@ -0,0 +1,857 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import time
|
| 4 |
+
import hashlib
|
| 5 |
+
import logging
|
| 6 |
+
from typing import Optional, Dict, Any, List, Tuple
|
| 7 |
+
|
| 8 |
+
from modules.blogger.ai_manager import AIClient, AIKeyManager, AllProvidersExhausted as AllKeysExhausted
|
| 9 |
+
from modules.blogger.prompts import (
|
| 10 |
+
SYSTEM_REWRITE,
|
| 11 |
+
SYSTEM_EXTRACT,
|
| 12 |
+
SYSTEM_SEO,
|
| 13 |
+
SYSTEM_HASHTAGS,
|
| 14 |
+
SYSTEM_ALT_IMAGE,
|
| 15 |
+
SYSTEM_SUMMARY,
|
| 16 |
+
SYSTEM_NOTES,
|
| 17 |
+
SYSTEM_KEYWORDS,
|
| 18 |
+
SYSTEM_METADATA,
|
| 19 |
+
make_rewrite_prompt,
|
| 20 |
+
make_extract_prompt,
|
| 21 |
+
make_seo_prompt,
|
| 22 |
+
make_hashtag_prompt,
|
| 23 |
+
make_summary_prompt,
|
| 24 |
+
make_notes_prompt,
|
| 25 |
+
make_keywords_prompt,
|
| 26 |
+
make_metadata_prompt,
|
| 27 |
+
)
|
| 28 |
+
from modules.blogger.database import BloggerDatabase
|
| 29 |
+
|
| 30 |
+
logger = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ArticleProcessor:
|
| 34 |
+
def __init__(self, db: BloggerDatabase, ai_client: AIClient, config=None):
|
| 35 |
+
self.db = db
|
| 36 |
+
self.gemini = ai_client
|
| 37 |
+
self.config = config
|
| 38 |
+
|
| 39 |
+
MAX_PENDING_ATTEMPTS = 5
|
| 40 |
+
|
| 41 |
+
async def process_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None, channel_id: str = "") -> Optional[Dict]:
|
| 42 |
+
"""Immediate/manual processing path (e.g. UI 'preview now' button).
|
| 43 |
+
Attempts Gemini processing right away. NOT used by the automatic channel
|
| 44 |
+
polling flow — that flow uses enqueue_raw_post() instead so that message
|
| 45 |
+
ingestion never depends on Gemini availability."""
|
| 46 |
+
raw_text = raw_text.strip()
|
| 47 |
+
if not raw_text:
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
fingerprint = self._fingerprint(raw_text, source_url)
|
| 51 |
+
if self.db.is_published(fingerprint):
|
| 52 |
+
logger.info(f"Article already processed: {fingerprint[:16]}...")
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
return await self._process_fresh(raw_text, source_url, media, fingerprint, channel_id)
|
| 56 |
+
|
| 57 |
+
def enqueue_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None,
|
| 58 |
+
channel_id: str = "", section: str = "") -> Optional[str]:
|
| 59 |
+
"""Save an incoming raw post straight to the Gemini pending queue, WITHOUT ever
|
| 60 |
+
calling Gemini. This is the entry point used by the automatic channel-polling
|
| 61 |
+
scheduler, so that ingesting new posts never fails or blocks because of a
|
| 62 |
+
Gemini cooldown/quota issue. Returns the fingerprint if newly queued,
|
| 63 |
+
None if it's a duplicate or already being handled."""
|
| 64 |
+
raw_text = raw_text.strip()
|
| 65 |
+
if not raw_text:
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
fingerprint = self._fingerprint(raw_text, source_url)
|
| 69 |
+
if self.db.is_published(fingerprint):
|
| 70 |
+
return None
|
| 71 |
+
existing = self.db.get_article(fingerprint)
|
| 72 |
+
if existing and existing.get("status") in ("queued", "published", "gemini_pending", "processing"):
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
self._save_to_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 76 |
+
return fingerprint
|
| 77 |
+
|
| 78 |
+
def _save_to_pending(self, raw_text: str, source_url: str, media: List[Dict], fingerprint: str,
|
| 79 |
+
channel_id: str = "", section: str = ""):
|
| 80 |
+
article = {
|
| 81 |
+
"fingerprint": fingerprint,
|
| 82 |
+
"source_text": raw_text,
|
| 83 |
+
"source_url": source_url,
|
| 84 |
+
"media": media or [],
|
| 85 |
+
"channel_id": channel_id,
|
| 86 |
+
"status": "gemini_pending",
|
| 87 |
+
"created_at": int(time.time()),
|
| 88 |
+
}
|
| 89 |
+
self._save_article(article)
|
| 90 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 91 |
+
|
| 92 |
+
def _handle_processing_failure(self, fingerprint: str, raw_text: str, source_url: str,
|
| 93 |
+
media: List[Dict], channel_id: str, error: Exception,
|
| 94 |
+
article: Dict, section: str = ""):
|
| 95 |
+
"""Called whenever an unexpected error occurs while processing an article
|
| 96 |
+
(fresh or from the pending queue). Keeps the article retry-able in the
|
| 97 |
+
pending queue instead of losing it, up to MAX_PENDING_ATTEMPTS."""
|
| 98 |
+
attempts = self.db.increment_pending_attempts(fingerprint)
|
| 99 |
+
if attempts == -1:
|
| 100 |
+
# Wasn't in the pending queue yet (e.g. failed during the "fresh" path) — add it.
|
| 101 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 102 |
+
attempts = self.db.increment_pending_attempts(fingerprint)
|
| 103 |
+
if attempts == -1:
|
| 104 |
+
attempts = 1
|
| 105 |
+
if attempts >= self.MAX_PENDING_ATTEMPTS:
|
| 106 |
+
logger.error(
|
| 107 |
+
f"Article {fingerprint[:16]} failed {attempts} times, giving up permanently: {error}"
|
| 108 |
+
)
|
| 109 |
+
article["status"] = "failed_permanent"
|
| 110 |
+
article["error"] = str(error)
|
| 111 |
+
self._save_article(article)
|
| 112 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 113 |
+
else:
|
| 114 |
+
eta = self.db.set_pending_retry_after(fingerprint, attempts)
|
| 115 |
+
logger.warning(
|
| 116 |
+
f"Article {fingerprint[:16]} processing failed (attempt {attempts}/{self.MAX_PENDING_ATTEMPTS}), "
|
| 117 |
+
f"kept in pending queue, retry in {eta}s: {error}"
|
| 118 |
+
)
|
| 119 |
+
article["status"] = "gemini_pending"
|
| 120 |
+
article["error"] = str(error)
|
| 121 |
+
self._save_article(article)
|
| 122 |
+
|
| 123 |
+
async def _process_fresh(self, raw_text: str, source_url: str, media: List[Dict], fingerprint: str, channel_id: str = "", section: str = "") -> Optional[Dict]:
|
| 124 |
+
article = {
|
| 125 |
+
"fingerprint": fingerprint,
|
| 126 |
+
"source_text": raw_text,
|
| 127 |
+
"source_url": source_url,
|
| 128 |
+
"media": media or [],
|
| 129 |
+
"channel_id": channel_id,
|
| 130 |
+
"status": "processing",
|
| 131 |
+
"created_at": int(time.time()),
|
| 132 |
+
}
|
| 133 |
+
try:
|
| 134 |
+
session_ok = await self.gemini.acquire_session()
|
| 135 |
+
if not session_ok:
|
| 136 |
+
logger.warning(f"Gemini session failed for {fingerprint[:16]}, saving to pending")
|
| 137 |
+
article["status"] = "gemini_pending"
|
| 138 |
+
self._save_article(article)
|
| 139 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 140 |
+
return None
|
| 141 |
+
|
| 142 |
+
result = await self._run_pipeline(article, raw_text, source_url, media)
|
| 143 |
+
return result
|
| 144 |
+
except AllKeysExhausted:
|
| 145 |
+
logger.warning(f"All Gemini keys exhausted processing {fingerprint[:16]}, saving to pending")
|
| 146 |
+
article["status"] = "gemini_pending"
|
| 147 |
+
self._save_article(article)
|
| 148 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 149 |
+
return None
|
| 150 |
+
except Exception as e:
|
| 151 |
+
logger.exception(f"Article processing failed: {e}")
|
| 152 |
+
self._handle_processing_failure(fingerprint, raw_text, source_url, media, channel_id, e, article, section)
|
| 153 |
+
return None
|
| 154 |
+
finally:
|
| 155 |
+
self.gemini.release_session()
|
| 156 |
+
|
| 157 |
+
async def _process_next_pending(self) -> Optional[Dict]:
|
| 158 |
+
"""Try to process the next retry-ready item in the Gemini pending queue (FIFO).
|
| 159 |
+
Items still in exponential backoff are skipped so one blocked article does
|
| 160 |
+
not stall the rest of the queue. Returns the processed article if successful,
|
| 161 |
+
None otherwise."""
|
| 162 |
+
pending = self.db.get_gemini_pending_queue()
|
| 163 |
+
if not pending:
|
| 164 |
+
return None
|
| 165 |
+
now = time.time()
|
| 166 |
+
first = None
|
| 167 |
+
first_idx = 0
|
| 168 |
+
for idx, item in enumerate(pending):
|
| 169 |
+
retry_after = item.get("retry_after", 0)
|
| 170 |
+
if retry_after and now < retry_after:
|
| 171 |
+
continue
|
| 172 |
+
first = item
|
| 173 |
+
first_idx = idx
|
| 174 |
+
break
|
| 175 |
+
if first is None:
|
| 176 |
+
logger.info("Gemini pending queue: all items in backoff, deferring")
|
| 177 |
+
return None
|
| 178 |
+
raw_text = first.get("raw_text", "").strip()
|
| 179 |
+
fingerprint = first.get("fingerprint", "")
|
| 180 |
+
if not raw_text:
|
| 181 |
+
if fingerprint:
|
| 182 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 183 |
+
else:
|
| 184 |
+
self.db.remove_from_gemini_pending(first_idx)
|
| 185 |
+
return None
|
| 186 |
+
source_url = first.get("source_url", "")
|
| 187 |
+
media = first.get("media", [])
|
| 188 |
+
channel_id = first.get("channel_id", "")
|
| 189 |
+
pending_section = first.get("section", "")
|
| 190 |
+
if not fingerprint:
|
| 191 |
+
fingerprint = self._fingerprint(raw_text, source_url)
|
| 192 |
+
|
| 193 |
+
if self.db.is_published(fingerprint):
|
| 194 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 195 |
+
return None
|
| 196 |
+
|
| 197 |
+
article = {
|
| 198 |
+
"fingerprint": fingerprint,
|
| 199 |
+
"source_text": raw_text,
|
| 200 |
+
"source_url": source_url,
|
| 201 |
+
"media": media,
|
| 202 |
+
"channel_id": channel_id,
|
| 203 |
+
"status": "processing",
|
| 204 |
+
"created_at": int(time.time()),
|
| 205 |
+
}
|
| 206 |
+
try:
|
| 207 |
+
session_ok = await self.gemini.acquire_session()
|
| 208 |
+
if not session_ok:
|
| 209 |
+
self._handle_processing_failure(
|
| 210 |
+
fingerprint, raw_text, source_url, media, channel_id,
|
| 211 |
+
AllKeysExhausted("No AI provider available"), article
|
| 212 |
+
)
|
| 213 |
+
return None
|
| 214 |
+
|
| 215 |
+
result = await self._run_pipeline(article, raw_text, source_url, media)
|
| 216 |
+
if result:
|
| 217 |
+
result["channel_id"] = channel_id
|
| 218 |
+
if pending_section and not result.get("section"):
|
| 219 |
+
result["section"] = pending_section
|
| 220 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 221 |
+
logger.info(f"Gemini pending queue: recovered article {fingerprint[:16]}")
|
| 222 |
+
return result
|
| 223 |
+
except AllKeysExhausted as e:
|
| 224 |
+
self._handle_processing_failure(
|
| 225 |
+
fingerprint, raw_text, source_url, media, channel_id, e, article
|
| 226 |
+
)
|
| 227 |
+
return None
|
| 228 |
+
except Exception as e:
|
| 229 |
+
logger.exception(f"Pending recovery failed for {fingerprint[:16]}: {e}")
|
| 230 |
+
# Keep the item in pending (up to MAX_PENDING_ATTEMPTS) instead of losing it.
|
| 231 |
+
self._handle_processing_failure(fingerprint, raw_text, source_url, media, channel_id, e, article)
|
| 232 |
+
return None
|
| 233 |
+
finally:
|
| 234 |
+
self.gemini.release_session()
|
| 235 |
+
|
| 236 |
+
async def _run_pipeline(self, article: Dict, raw_text: str, source_url: str = "", media: List[Dict] = None) -> Optional[Dict]:
|
| 237 |
+
"""Execute the full Gemini pipeline on raw_text and populate article dict."""
|
| 238 |
+
clean_text = self._clean_source_footer(raw_text)
|
| 239 |
+
rewrite = await self._rewrite(clean_text)
|
| 240 |
+
if rewrite:
|
| 241 |
+
article.update(rewrite)
|
| 242 |
+
extracted = await self._extract(clean_text)
|
| 243 |
+
if extracted:
|
| 244 |
+
article["extracted"] = extracted
|
| 245 |
+
article["labels"] = []
|
| 246 |
+
summary = await self._summary(clean_text)
|
| 247 |
+
if summary:
|
| 248 |
+
article["summary"] = summary
|
| 249 |
+
metadata = await self._metadata(
|
| 250 |
+
extracted or {},
|
| 251 |
+
article.get("title", raw_text[:60]),
|
| 252 |
+
article.get("body", raw_text),
|
| 253 |
+
)
|
| 254 |
+
if metadata:
|
| 255 |
+
keywords = metadata.get("keywords")
|
| 256 |
+
hashtags = metadata.get("hashtags")
|
| 257 |
+
notes = metadata.get("notes")
|
| 258 |
+
if keywords:
|
| 259 |
+
article["keywords"] = keywords
|
| 260 |
+
if hashtags:
|
| 261 |
+
article["hashtags"] = hashtags
|
| 262 |
+
logger.info(f"Hashtags Stored: {hashtags}")
|
| 263 |
+
else:
|
| 264 |
+
logger.warning(f"Hashtags Stored: empty or None")
|
| 265 |
+
if notes:
|
| 266 |
+
article["notes"] = notes
|
| 267 |
+
else:
|
| 268 |
+
logger.warning("Gemini _metadata returned no result")
|
| 269 |
+
body_text = article.get("body", raw_text)
|
| 270 |
+
article["reading_time"] = self._reading_time(body_text)
|
| 271 |
+
if media:
|
| 272 |
+
alt_data = await self._alt_text(
|
| 273 |
+
article.get("title", raw_text[:60]),
|
| 274 |
+
article.get("body", raw_text),
|
| 275 |
+
)
|
| 276 |
+
if alt_data:
|
| 277 |
+
article["media_alt"] = alt_data
|
| 278 |
+
article["status"] = "processed"
|
| 279 |
+
article["processed_at"] = int(time.time())
|
| 280 |
+
self._save_article(article)
|
| 281 |
+
return article
|
| 282 |
+
|
| 283 |
+
@staticmethod
|
| 284 |
+
def _clean_source_footer(text: str) -> str:
|
| 285 |
+
"""Remove source-channel footer/signature lines before contact extraction."""
|
| 286 |
+
if not text:
|
| 287 |
+
return ""
|
| 288 |
+
kept = []
|
| 289 |
+
for raw in text.splitlines():
|
| 290 |
+
line = raw.strip()
|
| 291 |
+
if not line:
|
| 292 |
+
continue
|
| 293 |
+
low = line.lower()
|
| 294 |
+
if re.search(r'(?:t\.me/|telegram\.me/|tlgrm\.me/)', low):
|
| 295 |
+
continue
|
| 296 |
+
if re.match(r'^@[\w.]+$', line):
|
| 297 |
+
continue
|
| 298 |
+
if re.search(r'castlejob|castle\s*job|قلعة الوظائف', low):
|
| 299 |
+
continue
|
| 300 |
+
if re.search(r'telegram|تلغرام|تيليجرام|تلجرام', low):
|
| 301 |
+
continue
|
| 302 |
+
if re.search(r'تابعونا|تتابعنا|متابعتنا|متابعة القناة|المزيد من الوظائف|للمزيد من الوظائف|للمزيد من الفرص|اشترك بالقناة|انضم للقناة|قناتنا|قناة الوظائف|follow us|join telegram|subscribe', low):
|
| 303 |
+
continue
|
| 304 |
+
kept.append(raw)
|
| 305 |
+
return "\n".join(kept).strip()
|
| 306 |
+
|
| 307 |
+
def _fingerprint(self, text: str, url: str = "") -> str:
|
| 308 |
+
raw = f"{url}|{text[:300]}"
|
| 309 |
+
return hashlib.md5(raw.encode("utf-8", errors="replace")).hexdigest()
|
| 310 |
+
|
| 311 |
+
def _save_article(self, article: Dict):
|
| 312 |
+
aid = article.get("fingerprint", str(int(time.time())))
|
| 313 |
+
self.db.save_article(aid, article)
|
| 314 |
+
|
| 315 |
+
async def _rewrite(self, text: str) -> Optional[Dict]:
|
| 316 |
+
prompt = make_rewrite_prompt(text)
|
| 317 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_REWRITE)
|
| 318 |
+
if not result:
|
| 319 |
+
logger.warning("Gemini _rewrite returned no result")
|
| 320 |
+
return None
|
| 321 |
+
logger.info("Gemini _rewrite succeeded")
|
| 322 |
+
return {
|
| 323 |
+
"title": result.get("title", text[:80]),
|
| 324 |
+
"body": result.get("body", f"<p>{text}</p>"),
|
| 325 |
+
"introduction": result.get("introduction", ""),
|
| 326 |
+
"faq": result.get("faq", []),
|
| 327 |
+
"conclusion": result.get("conclusion", ""),
|
| 328 |
+
"gemini_used": True,
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
async def _extract(self, text: str) -> Optional[Dict]:
|
| 332 |
+
prompt = make_extract_prompt(text)
|
| 333 |
+
return await self.gemini.generate_json(prompt, SYSTEM_EXTRACT)
|
| 334 |
+
|
| 335 |
+
async def _seo(self, title: str, body: str) -> Optional[Dict]:
|
| 336 |
+
prompt = make_seo_prompt(title, body)
|
| 337 |
+
return await self.gemini.generate_json(prompt, SYSTEM_SEO)
|
| 338 |
+
|
| 339 |
+
async def _hashtags(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]:
|
| 340 |
+
prompt = make_hashtag_prompt(extracted, title, body)
|
| 341 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_HASHTAGS)
|
| 342 |
+
if result and isinstance(result, dict):
|
| 343 |
+
tags = result.get("hashtags", [])
|
| 344 |
+
if isinstance(tags, list):
|
| 345 |
+
logger.info(f"Hashtags Generated: {tags}")
|
| 346 |
+
return tags
|
| 347 |
+
logger.warning(f"Hashtags Generated but 'hashtags' key is not list: {type(tags)}")
|
| 348 |
+
else:
|
| 349 |
+
logger.warning(f"Hashtags Generated: AI returned invalid data: {result}")
|
| 350 |
+
return []
|
| 351 |
+
|
| 352 |
+
async def _alt_text(self, title: str, body: str) -> Optional[Dict]:
|
| 353 |
+
prompt = f"""أنشئ وصف ALT وتعليق للصورة بناءً على:
|
| 354 |
+
العنوان: {title}
|
| 355 |
+
المحتوى: {body[:500]}
|
| 356 |
+
الرد JSON فقط: {{"alt": "...", "caption": "..."}}"""
|
| 357 |
+
return await self.gemini.generate_json(prompt, SYSTEM_ALT_IMAGE)
|
| 358 |
+
|
| 359 |
+
# Legacy — labels now come from section settings in scheduler
|
| 360 |
+
def _make_labels(self, extracted: Dict, seo: Dict) -> List[str]:
|
| 361 |
+
labels = set()
|
| 362 |
+
if extracted.get("type"):
|
| 363 |
+
labels.add(extracted["type"])
|
| 364 |
+
if extracted.get("ministry"):
|
| 365 |
+
labels.add(extracted["ministry"])
|
| 366 |
+
if extracted.get("province"):
|
| 367 |
+
labels.add(extracted["province"])
|
| 368 |
+
if extracted.get("city"):
|
| 369 |
+
labels.add(extracted["city"])
|
| 370 |
+
if extracted.get("company"):
|
| 371 |
+
labels.add(extracted["company"])
|
| 372 |
+
seo_labels = seo.get("labels", [])
|
| 373 |
+
if isinstance(seo_labels, list):
|
| 374 |
+
for lbl in seo_labels:
|
| 375 |
+
if lbl:
|
| 376 |
+
labels.add(str(lbl))
|
| 377 |
+
return list(labels)[:10]
|
| 378 |
+
|
| 379 |
+
async def _summary(self, text: str) -> Optional[str]:
|
| 380 |
+
prompt = make_summary_prompt(text)
|
| 381 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_SUMMARY)
|
| 382 |
+
if result and isinstance(result, dict):
|
| 383 |
+
return result.get("summary", "")
|
| 384 |
+
return None
|
| 385 |
+
|
| 386 |
+
async def _notes(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]:
|
| 387 |
+
prompt = make_notes_prompt(extracted, title, body)
|
| 388 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_NOTES)
|
| 389 |
+
if result and isinstance(result, dict):
|
| 390 |
+
notes = result.get("notes", [])
|
| 391 |
+
if isinstance(notes, list) and notes:
|
| 392 |
+
return notes
|
| 393 |
+
return None
|
| 394 |
+
|
| 395 |
+
async def _keywords(self, title: str, body: str, extracted: Dict) -> Optional[str]:
|
| 396 |
+
prompt = make_keywords_prompt(title, body, extracted)
|
| 397 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_KEYWORDS)
|
| 398 |
+
if result and isinstance(result, dict):
|
| 399 |
+
kw = result.get("keywords", "")
|
| 400 |
+
if kw and isinstance(kw, str):
|
| 401 |
+
return kw
|
| 402 |
+
return None
|
| 403 |
+
|
| 404 |
+
async def _metadata(self, extracted: Dict, title: str, body: str) -> Optional[Dict]:
|
| 405 |
+
prompt = make_metadata_prompt(extracted, title, body)
|
| 406 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_METADATA)
|
| 407 |
+
if result and isinstance(result, dict):
|
| 408 |
+
return result
|
| 409 |
+
return None
|
| 410 |
+
|
| 411 |
+
@staticmethod
|
| 412 |
+
def _reading_time(body_html: str) -> int:
|
| 413 |
+
text = re.sub(r'<[^>]+>', '', body_html)
|
| 414 |
+
word_count = len(text.split())
|
| 415 |
+
minutes = max(1, round(word_count / 150))
|
| 416 |
+
return minutes
|
| 417 |
+
|
| 418 |
+
def _add_inline_hashtags(self, body: str, extracted: Dict) -> str:
|
| 419 |
+
entities = []
|
| 420 |
+
if extracted.get("city"):
|
| 421 |
+
entities.append(extracted["city"])
|
| 422 |
+
if extracted.get("province"):
|
| 423 |
+
entities.append(extracted["province"])
|
| 424 |
+
if extracted.get("ministry"):
|
| 425 |
+
entities.append(extracted["ministry"])
|
| 426 |
+
if extracted.get("company"):
|
| 427 |
+
entities.append(extracted["company"])
|
| 428 |
+
if extracted.get("university"):
|
| 429 |
+
entities.append(extracted["university"])
|
| 430 |
+
if extracted.get("organization"):
|
| 431 |
+
entities.append(extracted["organization"])
|
| 432 |
+
if extracted.get("job_type"):
|
| 433 |
+
entities.append(extracted["job_type"])
|
| 434 |
+
if extracted.get("district"):
|
| 435 |
+
entities.append(extracted["district"])
|
| 436 |
+
result = body
|
| 437 |
+
for entity in entities:
|
| 438 |
+
if entity and len(entity) > 2:
|
| 439 |
+
tag = entity.replace(" ", "_")
|
| 440 |
+
replacement = f'<a href="https://www.blogger.com/search?q={tag}" style="text-decoration:none;color:#1a73e8;">#{tag}</a>'
|
| 441 |
+
result = result.replace(entity, replacement, 1)
|
| 442 |
+
return result
|
| 443 |
+
|
| 444 |
+
def _article_css(self) -> str:
|
| 445 |
+
return """<style>
|
| 446 |
+
html{scroll-behavior:smooth;}
|
| 447 |
+
body{font-family:'Segoe UI',Tahoma,Arial,sans-serif;}
|
| 448 |
+
h2,h3,h4{font-weight:bold!important;margin:18px 0 10px 0;clear:both;color:#1a1a2e;line-height:1.6;}
|
| 449 |
+
p{line-height:1.8;color:#3c4043;margin:8px 0;font-size:15px;}
|
| 450 |
+
a{color:#1a73e8;text-decoration:none;}
|
| 451 |
+
a:hover{text-decoration:underline;}
|
| 452 |
+
table,.job-table{width:100%;border-collapse:collapse;margin:16px 0;font-size:14px;direction:rtl;text-align:right;font-family:'Segoe UI',Tahoma,Arial,sans-serif;background:#fff;border:1px solid #dde3ea;border-radius:8px;overflow:hidden;}
|
| 453 |
+
table th,.job-table th{background:#1f3a5f;color:#fff;padding:10px 14px;border:1px solid #1f3a5f;text-align:right;font-weight:bold;font-size:14px;}
|
| 454 |
+
table td,.job-table td{padding:10px 14px;border:1px solid #e1e5ea;color:#2c3e50;vertical-align:top;line-height:1.7;font-size:14px;text-align:right;}
|
| 455 |
+
table tr:nth-child(even) td,.job-table tr:nth-child(even) td{background:#f6f8fa;}
|
| 456 |
+
table tr:hover td,.job-table tr:hover td{background:#eef4fb;}
|
| 457 |
+
.summary-box{background:#fffbea;border-right:4px solid #f5c518;padding:12px 16px;margin:15px 0;border-radius:4px;}
|
| 458 |
+
.notes-box{background:#fff3f3;border-right:4px solid #dc3545;padding:12px 16px;margin:15px 0;border-radius:4px;}
|
| 459 |
+
.toc-box{background:#f0f4ff;border:1px solid #cfe2ff;border-radius:10px;padding:14px 18px;margin:15px 0;}
|
| 460 |
+
.toc-box ul{margin:0;list-style:none;padding:0;}
|
| 461 |
+
.toc-box li{margin:4px 0;}
|
| 462 |
+
.toc-box a{color:#1a73e8;font-size:14px;display:block;padding:4px 8px;border-radius:4px;}
|
| 463 |
+
.toc-box a:hover{background:#e8f0fe;text-decoration:none;}
|
| 464 |
+
.hashtag-box{margin:15px 0;padding:12px 16px;background:#f8f9fa;border-radius:4px;text-align:center;}
|
| 465 |
+
.keywords-box{margin:15px 0;padding:12px 16px;background:#f8f9fa;border-radius:4px;text-align:center;}
|
| 466 |
+
.tag{display:inline-block;background:#e3f2fd;color:#1565c0;padding:4px 12px;margin:3px 4px;border-radius:16px;font-size:13px;border:1px solid #90caf9;}
|
| 467 |
+
.article-end{background:#f0f7ff;border:1px solid #b8d8f0;border-radius:12px;padding:18px 22px;margin:22px 0;text-align:center;}
|
| 468 |
+
.article-end p{margin:0;font-size:16px;color:#1f3a5f;line-height:1.9;}
|
| 469 |
+
.apply-section{margin:18px 0;text-align:center;direction:rtl;}
|
| 470 |
+
.apply-intro{background:#f4f7fb;border:1px solid #d5dee8;border-radius:10px;padding:14px 18px;color:#3c4043;line-height:1.9;font-size:15px;text-align:right;margin:0 0 16px 0;}
|
| 471 |
+
.apply-box{display:block;margin:14px auto;max-width:480px;border-radius:14px;padding:18px 22px;border:1px solid;text-align:center;box-shadow:0 3px 10px rgba(0,0,0,.07);}
|
| 472 |
+
.apply-box-phone{background:#0f9d58;border-color:#0f9d58;}
|
| 473 |
+
.apply-box-mail{background:#fff;border-color:#d5dee8;}
|
| 474 |
+
.apply-box-link{background:#fff;border-color:#d5dee8;}
|
| 475 |
+
.apply-box-label{font-weight:bold;font-size:14px;display:block;margin-bottom:8px;color:#5f6368;}
|
| 476 |
+
.apply-box-phone .apply-box-label{color:#e8f5e9;}
|
| 477 |
+
.apply-box-value{font-size:24px;font-weight:bold;color:#1a73e8;direction:ltr;display:inline-block;word-break:break-all;text-decoration:none!important;}
|
| 478 |
+
.apply-box-value:hover{text-decoration:underline!important;}
|
| 479 |
+
.apply-box-phone .apply-box-value{color:#fff;font-size:30px;letter-spacing:1px;}
|
| 480 |
+
.apply-box-actions{margin-top:12px;}
|
| 481 |
+
.apply-btn{display:inline-block;padding:10px 28px;border-radius:10px;font-weight:bold;font-size:15px;margin:4px;text-decoration:none!important;color:#fff!important;transition:opacity .15s;}
|
| 482 |
+
.apply-btn:hover{opacity:.88;text-decoration:none!important;}
|
| 483 |
+
.apply-btn-call{background:#1a73e8;}
|
| 484 |
+
.apply-btn-whatsapp{background:#25d366;}
|
| 485 |
+
.apply-btn-cv{background:#1a73e8;}
|
| 486 |
+
.apply-btn-now{background:#ff6d00;}
|
| 487 |
+
@media (max-width:600px){
|
| 488 |
+
table,.job-table{font-size:13px;}
|
| 489 |
+
table th,table td,.job-table th,.job-table td{padding:8px 10px;}
|
| 490 |
+
.apply-box{width:92%;padding:14px 14px;}
|
| 491 |
+
.apply-box-value{font-size:17px;}
|
| 492 |
+
.apply-box-phone .apply-box-value{font-size:22px;}
|
| 493 |
+
.apply-btn{display:block;margin:6px auto;width:70%;}
|
| 494 |
+
}
|
| 495 |
+
</style>"""
|
| 496 |
+
|
| 497 |
+
def make_article_html(self, article: Dict) -> str:
|
| 498 |
+
parts = []
|
| 499 |
+
parts.append(self._article_css())
|
| 500 |
+
|
| 501 |
+
# ── 1. Featured Image ──
|
| 502 |
+
parts.append(self._make_featured_image(article))
|
| 503 |
+
|
| 504 |
+
# ── 2. Summary Box ──
|
| 505 |
+
summary = article.get("summary", "")
|
| 506 |
+
if summary:
|
| 507 |
+
parts.append(self._make_summary_box(summary))
|
| 508 |
+
|
| 509 |
+
# ── 3. Introduction ──
|
| 510 |
+
intro = article.get("introduction", "")
|
| 511 |
+
if intro:
|
| 512 |
+
parts.append(f'<h2 id="intro">المقدمة</h2><p>{intro}</p>')
|
| 513 |
+
|
| 514 |
+
# ── 4. Table of Contents (single index, right after introduction) ──
|
| 515 |
+
body = article.get("body", "")
|
| 516 |
+
toc, processed_body = self._make_toc(body)
|
| 517 |
+
if toc:
|
| 518 |
+
parts.append(toc)
|
| 519 |
+
|
| 520 |
+
# ── 5. Full Article Body (with apply contacts injected) ──
|
| 521 |
+
body_to_process = processed_body or body
|
| 522 |
+
body_to_process = self._enhance_body_tables(body_to_process)
|
| 523 |
+
body_to_process = self._inject_apply_into_body(article, body_to_process)
|
| 524 |
+
if body_to_process:
|
| 525 |
+
parts.append(f'<div>{body_to_process}</div>')
|
| 526 |
+
|
| 527 |
+
# ── 6. Important Notes ──
|
| 528 |
+
notes = article.get("notes", [])
|
| 529 |
+
if notes:
|
| 530 |
+
parts.append(self._make_notes_box(notes))
|
| 531 |
+
|
| 532 |
+
# ── 7. FAQ ──
|
| 533 |
+
faq = article.get("faq", [])
|
| 534 |
+
if faq:
|
| 535 |
+
parts.append(self._make_faq(faq))
|
| 536 |
+
|
| 537 |
+
# ── 8. Conclusion (professional end card) ──
|
| 538 |
+
conclusion = article.get("conclusion", "")
|
| 539 |
+
if conclusion:
|
| 540 |
+
parts.append(self._make_conclusion_box(conclusion))
|
| 541 |
+
|
| 542 |
+
# ── 9. Hashtags ──
|
| 543 |
+
hashtags = article.get("hashtags", [])
|
| 544 |
+
logger.info(f"Hashtags Before HTML: {hashtags}")
|
| 545 |
+
if hashtags:
|
| 546 |
+
parts.append(self._make_hashtags_section(hashtags))
|
| 547 |
+
|
| 548 |
+
# ── 10. Source ──
|
| 549 |
+
source = article.get("source", {})
|
| 550 |
+
if source:
|
| 551 |
+
parts.append(self._make_source(source))
|
| 552 |
+
|
| 553 |
+
# ── 11. Keywords ──
|
| 554 |
+
keywords = article.get("keywords", "")
|
| 555 |
+
if keywords:
|
| 556 |
+
parts.append(self._make_keywords_section(keywords))
|
| 557 |
+
|
| 558 |
+
# ── 12. Schema JSON-LD ──
|
| 559 |
+
schema = self._make_schema(article)
|
| 560 |
+
if schema:
|
| 561 |
+
parts.append(schema)
|
| 562 |
+
|
| 563 |
+
return "\n".join(parts)
|
| 564 |
+
|
| 565 |
+
def _enhance_body_tables(self, body: str) -> str:
|
| 566 |
+
if not body:
|
| 567 |
+
return body
|
| 568 |
+
def _replace(m):
|
| 569 |
+
tag = m.group(0)
|
| 570 |
+
if "class=" not in tag:
|
| 571 |
+
return '<table class="job-table">'
|
| 572 |
+
return tag
|
| 573 |
+
return re.sub(r'<table[^>]*>', _replace, body)
|
| 574 |
+
|
| 575 |
+
def _make_conclusion_box(self, conclusion: str) -> str:
|
| 576 |
+
return f'<div class="article-end"><p>📢 {conclusion}</p></div>'
|
| 577 |
+
|
| 578 |
+
def _make_featured_image(self, article: Dict) -> str:
|
| 579 |
+
alt_text = article.get("media_alt", {}).get("alt", "")
|
| 580 |
+
caption = article.get("media_alt", {}).get("caption", "")
|
| 581 |
+
img_src = None
|
| 582 |
+
if self.config:
|
| 583 |
+
img_src = self.config.get("default_jobs_image", "")
|
| 584 |
+
if not img_src:
|
| 585 |
+
return ""
|
| 586 |
+
alt = alt_text or "صورة المقال"
|
| 587 |
+
title = article.get("title", "")[:60]
|
| 588 |
+
img = f'<p style="text-align:center;"><img src="{img_src}" alt="{alt}" title="{title}" loading="lazy" style="width:100%;max-width:100%;height:auto;border-radius:8px;" /></p>'
|
| 589 |
+
if caption:
|
| 590 |
+
img += f'<p style="text-align:center;font-size:13px;color:#666;margin-top:-10px;">{caption}</p>'
|
| 591 |
+
return img
|
| 592 |
+
|
| 593 |
+
def _make_summary_box(self, summary: str) -> str:
|
| 594 |
+
return f'<div class="summary-box"><strong style="color:#856404;">📌 ملخص المقال</strong><p style="margin:8px 0 0 0;color:#856404;font-size:15px;">{summary}</p></div>'
|
| 595 |
+
|
| 596 |
+
def _make_toc(self, body: str) -> tuple:
|
| 597 |
+
if not body:
|
| 598 |
+
return "", body
|
| 599 |
+
headings = re.findall(r'<h([23])[^>]*>(.*?)</h\1>', body, re.DOTALL)
|
| 600 |
+
if len(headings) < 2:
|
| 601 |
+
return "", body
|
| 602 |
+
icon_map = {
|
| 603 |
+
"نبذة": "ℹ️", "تفاصيل": "📋", "بيئة": "🏢", "المهام": "📌",
|
| 604 |
+
"مؤهلات": "🎓", "شروط": "📄", "تقديم": "📝", "مميزات": "⭐",
|
| 605 |
+
"أسئلة": "❓", "خلاصة": "✅", "تعليمات": "📋", "ملاحظات": "⚠️",
|
| 606 |
+
"طريقة": "📝", "شواغر": "👥", "راتب": "💰", "دوام": "🕐",
|
| 607 |
+
}
|
| 608 |
+
items = []
|
| 609 |
+
processed = body
|
| 610 |
+
idx = 0
|
| 611 |
+
for level, text in headings:
|
| 612 |
+
if "التنقل" in text:
|
| 613 |
+
processed = re.sub(
|
| 614 |
+
rf'<h{level}[^>]*>{re.escape(text)}</h{level}>.*?(?=<h[23][^>]*>|$)',
|
| 615 |
+
'', processed, count=1, flags=re.DOTALL
|
| 616 |
+
)
|
| 617 |
+
continue
|
| 618 |
+
anchor = f"sec-{idx}"
|
| 619 |
+
icon = "📌"
|
| 620 |
+
for keyword, emoji in icon_map.items():
|
| 621 |
+
if keyword in text:
|
| 622 |
+
icon = emoji
|
| 623 |
+
break
|
| 624 |
+
items.append(f'<li><a href="#{anchor}">{icon} {text}</a></li>')
|
| 625 |
+
processed = processed.replace(
|
| 626 |
+
f'<h{level}>{text}</h{level}>',
|
| 627 |
+
f'<h{level} id="{anchor}">{text}</h{level}>', 1
|
| 628 |
+
)
|
| 629 |
+
idx += 1
|
| 630 |
+
if len(items) < 2:
|
| 631 |
+
return "", processed
|
| 632 |
+
toc = f'<div class="toc-box"><strong style="font-size:16px;color:#1a73e8;display:block;margin-bottom:8px;">📋 المحتويات والتنقل السريع</strong><ul>{"".join(items)}</ul></div>'
|
| 633 |
+
return toc, processed
|
| 634 |
+
|
| 635 |
+
@staticmethod
|
| 636 |
+
def _is_iraqi_phone(clean_phone: str) -> bool:
|
| 637 |
+
digits = re.sub(r'[^\d]', '', clean_phone)
|
| 638 |
+
return digits.startswith("07") or digits.startswith("9647")
|
| 639 |
+
|
| 640 |
+
@staticmethod
|
| 641 |
+
def _to_whatsapp(clean_phone: str) -> str:
|
| 642 |
+
digits = re.sub(r'[^\d]', '', clean_phone)
|
| 643 |
+
if digits.startswith("964"):
|
| 644 |
+
return digits
|
| 645 |
+
if digits.startswith("0"):
|
| 646 |
+
return "964" + digits[1:]
|
| 647 |
+
return "964" + digits
|
| 648 |
+
|
| 649 |
+
def _make_apply_section_html(self, email: str, phone: str, apply_url: str) -> str:
|
| 650 |
+
logger.info("Apply Builder Called")
|
| 651 |
+
blocks = []
|
| 652 |
+
if phone:
|
| 653 |
+
clean_phone = re.sub(r'[^\d+]', '', phone)
|
| 654 |
+
buttons = f'<a class="apply-btn apply-btn-call" href="tel:{clean_phone}">📞 اتصال</a>'
|
| 655 |
+
if self._is_iraqi_phone(clean_phone):
|
| 656 |
+
wa = self._to_whatsapp(clean_phone)
|
| 657 |
+
buttons += f'<a class="apply-btn apply-btn-whatsapp" href="https://wa.me/{wa}" target="_blank" rel="noopener">💬 واتساب</a>'
|
| 658 |
+
blocks.append(
|
| 659 |
+
f'<div class="apply-box apply-box-phone">'
|
| 660 |
+
f'<div class="apply-box-label">📞 رقم الهاتف</div>'
|
| 661 |
+
f'<a class="apply-box-value" href="tel:{clean_phone}">{phone}</a>'
|
| 662 |
+
f'<div class="apply-box-actions">{buttons}</div>'
|
| 663 |
+
f'</div>'
|
| 664 |
+
)
|
| 665 |
+
if email:
|
| 666 |
+
blocks.append(
|
| 667 |
+
f'<div class="apply-box apply-box-mail">'
|
| 668 |
+
f'<div class="apply-box-label">✉️ البريد الإلكتروني</div>'
|
| 669 |
+
f'<a class="apply-box-value" href="mailto:{email}">{email}</a>'
|
| 670 |
+
f'<div class="apply-box-actions">'
|
| 671 |
+
f'<a class="apply-btn apply-btn-cv" href="mailto:{email}">📧 إرسال CV</a>'
|
| 672 |
+
f'</div>'
|
| 673 |
+
f'</div>'
|
| 674 |
+
)
|
| 675 |
+
if apply_url:
|
| 676 |
+
blocks.append(
|
| 677 |
+
f'<div class="apply-box apply-box-link">'
|
| 678 |
+
f'<div class="apply-box-label">🌐 رابط التقديم</div>'
|
| 679 |
+
f'<a class="apply-box-value" href="{apply_url}" target="_blank" rel="noopener">{apply_url}</a>'
|
| 680 |
+
f'<div class="apply-box-actions">'
|
| 681 |
+
f'<a class="apply-btn apply-btn-now" href="{apply_url}" target="_blank" rel="noopener">التقديم</a>'
|
| 682 |
+
f'</div>'
|
| 683 |
+
f'</div>'
|
| 684 |
+
)
|
| 685 |
+
return '<div class="apply-section">' + "".join(blocks) + '</div>'
|
| 686 |
+
|
| 687 |
+
def _inject_apply_into_body(self, article: Dict, body: str) -> str:
|
| 688 |
+
if not body:
|
| 689 |
+
return body
|
| 690 |
+
extracted = article.get("extracted", {}) or {}
|
| 691 |
+
email = str(extracted.get("email") or "").strip()
|
| 692 |
+
phone = str(extracted.get("phone") or "").strip()
|
| 693 |
+
apply_url = str(extracted.get("apply_url") or "").strip()
|
| 694 |
+
if apply_url and re.search(r'^https?://(?:t\.me|telegram\.me|tlgrm\.me)/|^@', apply_url, re.IGNORECASE):
|
| 695 |
+
apply_url = ""
|
| 696 |
+
if not (email or phone or apply_url):
|
| 697 |
+
return body
|
| 698 |
+
|
| 699 |
+
section_html = self._make_apply_section_html(email, phone, apply_url)
|
| 700 |
+
intro = ('<p class="apply-intro">يمكنك التقديم على هذه الفرصة عبر إحدى وسائل التواصل التالية:</p>')
|
| 701 |
+
|
| 702 |
+
main_patterns = [
|
| 703 |
+
r'<h[23][^>]*>(?:آلية التقديم والتواصل|طريقة التقديم والتواصل|طريقة التقديم على الوظيفة|طريقة التقديم|كيفية التقديم|التقديم على الوظيفة)</h[23]>',
|
| 704 |
+
]
|
| 705 |
+
for pattern in main_patterns:
|
| 706 |
+
match = re.search(pattern, body, re.IGNORECASE)
|
| 707 |
+
if match:
|
| 708 |
+
heading_tag = match.group(0)
|
| 709 |
+
heading_id = re.search(r'id="([^"]+)"', heading_tag)
|
| 710 |
+
anchor = heading_id.group(1) if heading_id else "apply"
|
| 711 |
+
heading_html = f'<h2 id="{anchor}">آلية التقديم والتواصل</h2>'
|
| 712 |
+
rest = body[match.end():]
|
| 713 |
+
next_m = re.search(r'<h[23][^>]*>', rest)
|
| 714 |
+
strip_end = match.end() + (next_m.start() if next_m else len(rest))
|
| 715 |
+
return body[:match.start()] + heading_html + intro + section_html + body[strip_end:]
|
| 716 |
+
fallback = re.search(r'<h[23][^>]*>(?:شروط التقديم|التقديم)</h[23]>', body, re.IGNORECASE)
|
| 717 |
+
if fallback:
|
| 718 |
+
end = fallback.end()
|
| 719 |
+
return body[:end] + intro + section_html + body[end:]
|
| 720 |
+
return body + '<h2 id="apply">آلية التقديم والتواصل</h2>' + intro + section_html
|
| 721 |
+
|
| 722 |
+
def _make_notes_box(self, notes: list) -> str:
|
| 723 |
+
lis = "".join(f"<li>{n}</li>" for n in notes)
|
| 724 |
+
return f'<div class="notes-box"><strong style="color:#721c24;">⚠️ ملاحظات مهمة</strong><ul style="margin:8px 0 0 0;color:#721c24;">{lis}</ul></div>'
|
| 725 |
+
|
| 726 |
+
def _make_faq(self, faq: list) -> str:
|
| 727 |
+
items = ""
|
| 728 |
+
for item in faq:
|
| 729 |
+
q = item.get("question", "")
|
| 730 |
+
a = item.get("answer", "")
|
| 731 |
+
if q and a:
|
| 732 |
+
items += f'<h3 itemscope itemprop="mainEntity" itemtype="https://schema.org/Question" style="font-size:16px;margin-top:15px;">{q}</h3><div itemprop="acceptedAnswer" itemscope itemtype="https://schema.org/Answer"><p itemprop="text">{a}</p></div>'
|
| 733 |
+
if not items:
|
| 734 |
+
return ""
|
| 735 |
+
return f'<h2 style="font-size:18px;font-weight:bold;margin:18px 0 10px 0;color:#222;">الأسئلة الشائعة</h2><div itemscope itemtype="https://schema.org/FAQPage">{items}</div>'
|
| 736 |
+
|
| 737 |
+
def _make_source(self, source: dict) -> str:
|
| 738 |
+
name = source.get("name", "المصدر")
|
| 739 |
+
username = source.get("username", "")
|
| 740 |
+
link = source.get("link", "")
|
| 741 |
+
if link and username and not username.startswith("private"):
|
| 742 |
+
return f'<div style="background:#f0f0f0;padding:10px 12px;border-radius:4px;margin:15px 0;font-size:13px;color:#666;"><strong>المصدر:</strong> <a href="{link}" target="_blank" rel="noopener">{name}</a></div>'
|
| 743 |
+
return f'<div style="background:#f0f0f0;padding:10px 12px;border-radius:4px;margin:15px 0;font-size:13px;color:#666;"><strong>المصدر:</strong> {name}</div>'
|
| 744 |
+
|
| 745 |
+
def _make_keywords_section(self, keywords: str) -> str:
|
| 746 |
+
parts = re.split(r'[،,\n]+', keywords)
|
| 747 |
+
tags = []
|
| 748 |
+
for p in parts:
|
| 749 |
+
t = p.strip()
|
| 750 |
+
if t:
|
| 751 |
+
tags.append(f'<span style="display:inline-block;background:#e3f2fd;color:#1565c0;padding:4px 12px;margin:3px 4px;border-radius:16px;font-size:13px;border:1px solid #90caf9;">{t}</span>')
|
| 752 |
+
if not tags:
|
| 753 |
+
return ""
|
| 754 |
+
return f'<div class="keywords-box"><strong style="display:block;font-size:15px;margin-bottom:8px;color:#333;">🏷️ الكلمات الدلالية</strong><div style="direction:rtl;text-align:center;">{"".join(tags)}</div></div>'
|
| 755 |
+
|
| 756 |
+
def _make_hashtags_section(self, hashtags: List[str]) -> str:
|
| 757 |
+
tags_items = []
|
| 758 |
+
for tag in hashtags:
|
| 759 |
+
t = tag.strip()
|
| 760 |
+
if t and not t.startswith("#"):
|
| 761 |
+
t = "#" + t
|
| 762 |
+
if t:
|
| 763 |
+
tags_items.append(t)
|
| 764 |
+
items = " ".join(tags_items)
|
| 765 |
+
return f'<div class="hashtag-box" style="direction:rtl;"><strong style="font-size:14px;display:block;margin-bottom:6px;">🏷️ الهاشتاكات</strong><p style="color:#1a73e8;margin:0;font-size:15px;line-height:1.8;">{items}</p></div>'
|
| 766 |
+
|
| 767 |
+
def _make_schema(self, article: Dict) -> str:
|
| 768 |
+
title = article.get("title", "")
|
| 769 |
+
intro = article.get("introduction", "")
|
| 770 |
+
body = article.get("body", "")
|
| 771 |
+
apply_pattern = r'<h[23][^>]*>(?:آلية التقديم والتواصل|طريقة التقديم والتواصل|طريقة التقديم على الوظيفة|طريقة التقديم|كيفية التقديم|التقديم على الوظيفة)</h[23]>.*?(?=<h[23]|$)'
|
| 772 |
+
body = re.sub(apply_pattern, '', body, flags=re.DOTALL | re.IGNORECASE)
|
| 773 |
+
text = re.sub(r'<[^>]+>', '', f"{intro} {body}")[:300]
|
| 774 |
+
section = article.get("section", "")
|
| 775 |
+
is_news = section not in ("jobs", "وظائف")
|
| 776 |
+
schema = {
|
| 777 |
+
"@context": "https://schema.org",
|
| 778 |
+
"@type": "NewsArticle" if is_news else "Article",
|
| 779 |
+
"headline": title,
|
| 780 |
+
"description": text[:160],
|
| 781 |
+
"articleBody": text,
|
| 782 |
+
"inLanguage": "ar",
|
| 783 |
+
"author": {"@type": "Organization", "name": "المدونة"},
|
| 784 |
+
"publisher": {"@type": "Organization", "name": "المدونة"},
|
| 785 |
+
"datePublished": article.get("created_at", ""),
|
| 786 |
+
"dateModified": article.get("processed_at", ""),
|
| 787 |
+
}
|
| 788 |
+
schema_str = json.dumps(schema, ensure_ascii=False)
|
| 789 |
+
return f'<script type="application/ld+json">{schema_str}</script>'
|
| 790 |
+
|
| 791 |
+
def make_preview_data(self, article: Dict) -> Tuple[Optional[str], str]:
|
| 792 |
+
html = self.make_article_html(article)
|
| 793 |
+
image = None
|
| 794 |
+
media = article.get("media", [])
|
| 795 |
+
for m in media:
|
| 796 |
+
if m.get("type") == "photo":
|
| 797 |
+
image = m.get("file_id")
|
| 798 |
+
break
|
| 799 |
+
if not image and self.config:
|
| 800 |
+
section = article.get("section", "")
|
| 801 |
+
if section in ("jobs", "وظائف", "general"):
|
| 802 |
+
image = self.config.get("default_jobs_image", "")
|
| 803 |
+
telegram_text = self.html_to_telegram(html)
|
| 804 |
+
title = article.get("title", "")
|
| 805 |
+
if title:
|
| 806 |
+
telegram_text = f"<b>{title}</b>\n\n{telegram_text}"
|
| 807 |
+
reading_time = article.get("reading_time", 0)
|
| 808 |
+
if reading_time:
|
| 809 |
+
telegram_text += f"\n⏱️ مدة القراءة: {reading_time} دقيقة"
|
| 810 |
+
labels = article.get("labels", [])
|
| 811 |
+
if labels:
|
| 812 |
+
telegram_text += f"\n🏷 {', '.join(labels)}"
|
| 813 |
+
return image, telegram_text
|
| 814 |
+
|
| 815 |
+
@staticmethod
|
| 816 |
+
def html_to_telegram(html: str) -> str:
|
| 817 |
+
html = re.sub(r'<!DOCTYPE[^>]*>', '', html, flags=re.DOTALL | re.IGNORECASE)
|
| 818 |
+
html = re.sub(r'<!--.*?-->', '', html, flags=re.DOTALL)
|
| 819 |
+
html = re.sub(r'<(script|style|noscript)[^>]*>.*?</\1>', '', html, flags=re.DOTALL | re.IGNORECASE)
|
| 820 |
+
html = re.sub(r'<head[^>]*>.*?</head>', '', html, flags=re.DOTALL | re.IGNORECASE)
|
| 821 |
+
|
| 822 |
+
def _replace_table(m):
|
| 823 |
+
rows = re.findall(r'<tr>(.*?)</tr>', m.group(1), re.DOTALL)
|
| 824 |
+
lines = []
|
| 825 |
+
for row in rows:
|
| 826 |
+
cells = re.findall(r'<t[hd][^>]*>(.*?)</t[hd]>', row, re.DOTALL)
|
| 827 |
+
if cells:
|
| 828 |
+
lines.append(' | '.join(cells))
|
| 829 |
+
return '\n'.join(lines) + '\n'
|
| 830 |
+
html = re.sub(r'<table[^>]*>(.*?)</table>', _replace_table, html, flags=re.DOTALL)
|
| 831 |
+
html = re.sub(r'<img[^>]*>', '', html)
|
| 832 |
+
html = re.sub(r'<h([23])[^>]*>(.*?)</h\1>', r'<b>\2</b>', html, flags=re.DOTALL)
|
| 833 |
+
html = re.sub(r'<li>(.*?)</li>', r'• \1', html, flags=re.DOTALL)
|
| 834 |
+
html = re.sub(r'</?u?[ol][^>]*>', '', html)
|
| 835 |
+
html = re.sub(r'<details[^>]*>', '', html)
|
| 836 |
+
html = re.sub(r'</details>', '', html)
|
| 837 |
+
html = re.sub(r'<summary[^>]*>(.*?)</summary>', r'<b>\1</b>\n', html, flags=re.DOTALL)
|
| 838 |
+
html = re.sub(r'</?div[^>]*>', '', html)
|
| 839 |
+
html = re.sub(r'</?span[^>]*>', '', html)
|
| 840 |
+
html = re.sub(r'<p>(.*?)</p>', r'\1\n', html, flags=re.DOTALL)
|
| 841 |
+
html = re.sub(r'<br\s*/?>', '\n', html)
|
| 842 |
+
html = re.sub(r'<strong>(.*?)</strong>', r'<b>\1</b>', html)
|
| 843 |
+
html = re.sub(r'<em>(.*?)</em>', r'<i>\1</i>', html)
|
| 844 |
+
html = re.sub(r'</?t[rdh][^>]*>', '', html)
|
| 845 |
+
|
| 846 |
+
def _clean_allowed_attrs(m):
|
| 847 |
+
tag = m.group(1).lower()
|
| 848 |
+
if tag == 'a':
|
| 849 |
+
href = re.search(r'href="([^"]+)"', m.group(0))
|
| 850 |
+
return f'<a href="{href.group(1)}">' if href else '<a>'
|
| 851 |
+
return f'<{tag}>'
|
| 852 |
+
html = re.sub(r'<(a|b|i|u|s|em|strong|code|pre)\b[^>]*>', _clean_allowed_attrs, html, flags=re.IGNORECASE)
|
| 853 |
+
allowed = {'b', 'i', 'u', 's', 'a', 'code', 'pre', 'em', 'strong'}
|
| 854 |
+
html = re.sub(r'<(?!/?(' + '|'.join(allowed) + r')(?:\s[^>]*)?>)[a-z]+[^>]*>', '', html, flags=re.IGNORECASE)
|
| 855 |
+
html = re.sub(r'</(?!(' + '|'.join(allowed) + r')\b)[a-z]+>', '', html, flags=re.IGNORECASE)
|
| 856 |
+
html = re.sub(r'\n{3,}', '\n\n', html)
|
| 857 |
+
return html.strip()
|