import json import re import time import hashlib import logging from typing import Optional, Dict, Any, List, Tuple from modules.blogger.ai_manager import AIClient, AIKeyManager, AllProvidersExhausted as AllKeysExhausted from modules.blogger.prompts import ( SYSTEM_REWRITE, SYSTEM_EXTRACT, SYSTEM_SEO, SYSTEM_HASHTAGS, SYSTEM_ALT_IMAGE, SYSTEM_SUMMARY, SYSTEM_NOTES, SYSTEM_KEYWORDS, SYSTEM_METADATA, make_rewrite_prompt, make_extract_prompt, make_seo_prompt, make_hashtag_prompt, make_summary_prompt, make_notes_prompt, make_keywords_prompt, make_metadata_prompt, ) from modules.blogger.database import BloggerDatabase from core.content_pipeline import ContentGate from modules.blogger.prompts import SYSTEM_ARTICLE_PACKAGE, make_article_package_prompt logger = logging.getLogger(__name__) SECTION_ICONS = { "نبذة": "ℹ️", "تفاصيل": "📋", "بيئة": "🏢", "المهام": "📌", "مؤهلات": "🎓", "شروط": "📄", "تقديم": "📝", "مميزات": "⭐", "أسئلة": "❓", "خلاصة": "✅", "تعليمات": "📋", "ملاحظات": "⚠️", "طريقة": "📝", "شواغر": "👥", "راتب": "💰", "دوام": "🕐", } class ArticleProcessor: def __init__(self, db: BloggerDatabase, ai_client: AIClient, config=None, runtime=None, section: str = "blogger"): self.db = db self.gemini = ai_client self.config = config self.gate = ContentGate(db) self.runtime = runtime self.section = section MAX_PENDING_ATTEMPTS = 5 async def process_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None, channel_id: str = "") -> Optional[Dict]: """Immediate/manual processing path (e.g. UI 'preview now' button). Attempts Gemini processing right away. NOT used by the automatic channel polling flow — that flow uses enqueue_raw_post() instead so that message ingestion never depends on Gemini availability.""" raw_text = raw_text.strip() if not raw_text: return None gate = self.gate.preflight(raw_text, source_url, channel_id) if not gate.allowed: logger.info("Article rejected before AI: reason=%s matched=%s", gate.reason, gate.matched) return None return await self._process_fresh(raw_text, source_url, media, gate.fingerprint, channel_id) def enqueue_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None, channel_id: str = "", section: str = "") -> Optional[str]: """Save an incoming raw post straight to the Gemini pending queue in blogger_data.json, WITHOUT ever calling Gemini at ingestion time.""" raw_text = raw_text.strip() if not raw_text: return None gate = self.gate.preflight(raw_text, source_url, channel_id) if not gate.allowed: logger.info("Article rejected at ingestion before AI: reason=%s matched=%s", gate.reason, gate.matched) return None fingerprint = gate.fingerprint self._save_to_pending(raw_text, source_url, media, fingerprint, channel_id, section) return fingerprint def _save_to_pending(self, raw_text: str, source_url: str, media: List[Dict], fingerprint: str, channel_id: str = "", section: str = ""): article = { "fingerprint": fingerprint, "source_text": raw_text, "source_url": source_url, "media": media or [], "channel_id": channel_id, "status": "gemini_pending", "created_at": int(time.time()), } self._save_article(article) self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section) def _handle_processing_failure(self, fingerprint: str, raw_text: str, source_url: str, media: List[Dict], channel_id: str, error: Exception, article: Dict, section: str = ""): """Called whenever an unexpected error occurs while processing an article (fresh or from the pending queue). Keeps the article retry-able in the pending queue instead of losing it, up to MAX_PENDING_ATTEMPTS.""" attempts = self.db.increment_pending_attempts(fingerprint) if attempts == -1: # Wasn't in the pending queue yet (e.g. failed during the "fresh" path) — add it. self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section) attempts = self.db.increment_pending_attempts(fingerprint) if attempts == -1: attempts = 1 if attempts >= self.MAX_PENDING_ATTEMPTS: logger.error( f"Article {fingerprint[:16]} failed {attempts} times, giving up permanently: {error}" ) article["status"] = "failed_permanent" article["error"] = str(error) self._save_article(article) self.db.remove_pending_by_fingerprint(fingerprint) else: eta = self.db.set_pending_retry_after(fingerprint, attempts) logger.warning( f"Article {fingerprint[:16]} processing failed (attempt {attempts}/{self.MAX_PENDING_ATTEMPTS}), " f"kept in pending queue, retry in {eta}s: {error}" ) article["status"] = "gemini_pending" article["error"] = str(error) self._save_article(article) async def _process_fresh(self, raw_text: str, source_url: str, media: List[Dict], fingerprint: str, channel_id: str = "", section: str = "") -> Optional[Dict]: article = { "fingerprint": fingerprint, "source_text": raw_text, "source_url": source_url, "media": media or [], "channel_id": channel_id, "status": "processing", "created_at": int(time.time()), } try: session_ok = await self.gemini.acquire_session() if not session_ok: logger.warning(f"Gemini session failed for {fingerprint[:16]}, saving to pending") article["status"] = "gemini_pending" self._save_article(article) self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section) return None result = await self._run_pipeline(article, raw_text, source_url, media) return result except AllKeysExhausted: logger.warning(f"All Gemini keys exhausted processing {fingerprint[:16]}, saving to pending") article["status"] = "gemini_pending" self._save_article(article) self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section) return None except Exception as e: logger.exception(f"Article processing failed: {e}") self._handle_processing_failure(fingerprint, raw_text, source_url, media, channel_id, e, article, section) return None finally: self.gemini.release_session() async def _process_next_pending(self) -> Optional[Dict]: """Try to process the next retry-ready item in the Gemini pending queue (FIFO). Items still in exponential backoff are skipped so one blocked article does not stall the rest of the queue. Returns the processed article if successful, None otherwise.""" pending = self.db.get_gemini_pending_queue() if not pending: return None now = time.time() first = None first_idx = 0 for idx, item in enumerate(pending): retry_after = item.get("retry_after", 0) if retry_after and now < retry_after: continue first = item first_idx = idx break if first is None: logger.info("Gemini pending queue: all items in backoff, deferring") return None raw_text = first.get("raw_text", "").strip() fingerprint = first.get("fingerprint", "") if not raw_text: if fingerprint: self.db.remove_pending_by_fingerprint(fingerprint) else: self.db.remove_from_gemini_pending(first_idx) return None source_url = first.get("source_url", "") media = first.get("media", []) channel_id = first.get("channel_id", "") pending_section = first.get("section", "") if not fingerprint: fingerprint = self._fingerprint(raw_text, source_url) if self.db.is_published(fingerprint): self.db.remove_pending_by_fingerprint(fingerprint) return None article = { "fingerprint": fingerprint, "source_text": raw_text, "source_url": source_url, "media": media, "channel_id": channel_id, "status": "processing", "created_at": int(time.time()), } try: session_ok = await self.gemini.acquire_session() if not session_ok: self._handle_processing_failure( fingerprint, raw_text, source_url, media, channel_id, AllKeysExhausted("No AI provider available"), article ) return None result = await self._run_pipeline(article, raw_text, source_url, media) if result: result["channel_id"] = channel_id if pending_section and not result.get("section"): result["section"] = pending_section self.db.remove_pending_by_fingerprint(fingerprint) logger.info(f"Gemini pending queue: recovered article {fingerprint[:16]}") return result except AllKeysExhausted as e: self._handle_processing_failure( fingerprint, raw_text, source_url, media, channel_id, e, article ) return None except Exception as e: logger.exception(f"Pending recovery failed for {fingerprint[:16]}: {e}") # Keep the item in pending (up to MAX_PENDING_ATTEMPTS) instead of losing it. self._handle_processing_failure(fingerprint, raw_text, source_url, media, channel_id, e, article) return None finally: self.gemini.release_session() async def _run_pipeline(self, article: Dict, raw_text: str, source_url: str = "", media: List[Dict] = None) -> Optional[Dict]: """Execute the full Gemini pipeline on raw_text and populate article dict.""" clean_text = self._clean_source_footer(raw_text) # One AI request for the whole article package. package = await self.gemini.generate_json( make_article_package_prompt(clean_text, bool(media)), SYSTEM_ARTICLE_PACKAGE, ) if not package or "raw" in package: raise RuntimeError("AI returned invalid article package JSON") article.update({k: v for k, v in package.items() if v is not None}) article["labels"] = (package.get("seo") or {}).get("labels", []) article["reading_time"] = self._reading_time(article.get("body", clean_text)) # Never let AI rewrite bypass the same content safety gates. post = self.gate.postflight(article, article.get("channel_id", "")) if not post.allowed: article["status"] = "discarded" article["discard_reason"] = post.reason article["matched_blocked_words"] = list(post.matched) self._save_article(article) logger.warning("AI output discarded by postflight: %s %s", post.reason, post.matched) return None article["status"] = "processed" article["processed_at"] = int(time.time()) self._save_article(article) return article @staticmethod def _clean_source_footer(text: str) -> str: """Remove source-channel footer/signature lines before contact extraction.""" if not text: return "" kept = [] for raw in text.splitlines(): line = raw.strip() if not line: continue low = line.lower() if re.search(r'(?:t\.me/|telegram\.me/|tlgrm\.me/)', low): continue if re.match(r'^@[\w.]+$', line): continue if re.search(r'castlejob|castle\s*job|قلعة الوظائف', low): continue if re.search(r'telegram|تلغرام|تيليجرام|تلجرام', low): continue if re.search(r'تابعونا|تتابعنا|متابعتنا|متابعة القناة|المزيد من الوظائف|للمزيد من الوظائف|للمزيد من الفرص|اشترك بالقناة|انضم للقناة|قناتنا|قناة الوظائف|follow us|join telegram|subscribe', low): continue kept.append(raw) return "\n".join(kept).strip() def _fingerprint(self, text: str, url: str = "") -> str: raw = f"{url}|{text[:300]}" return hashlib.md5(raw.encode("utf-8", errors="replace")).hexdigest() def _save_article(self, article: Dict): aid = article.get("fingerprint", str(int(time.time()))) self.db.save_article(aid, article) async def _rewrite(self, text: str) -> Optional[Dict]: prompt = make_rewrite_prompt(text) result = await self.gemini.generate_json(prompt, SYSTEM_REWRITE) if not result: logger.warning("Gemini _rewrite returned no result") return None logger.info("Gemini _rewrite succeeded") return { "title": result.get("title", text[:80]), "body": result.get("body", f"
{text}
"), "introduction": result.get("introduction", ""), "faq": result.get("faq", []), "conclusion": result.get("conclusion", ""), "gemini_used": True, } async def _extract(self, text: str) -> Optional[Dict]: prompt = make_extract_prompt(text) return await self.gemini.generate_json(prompt, SYSTEM_EXTRACT) async def _seo(self, title: str, body: str) -> Optional[Dict]: prompt = make_seo_prompt(title, body) return await self.gemini.generate_json(prompt, SYSTEM_SEO) async def _hashtags(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]: prompt = make_hashtag_prompt(extracted, title, body) result = await self.gemini.generate_json(prompt, SYSTEM_HASHTAGS) if result and isinstance(result, dict): tags = result.get("hashtags", []) if isinstance(tags, list): logger.info(f"Hashtags Generated: {tags}") return tags logger.warning(f"Hashtags Generated but 'hashtags' key is not list: {type(tags)}") else: logger.warning(f"Hashtags Generated: AI returned invalid data: {result}") return [] async def _alt_text(self, title: str, body: str) -> Optional[Dict]: prompt = f"""أنشئ وصف ALT وتعليق للصورة بناءً على: العنوان: {title} المحتوى: {body[:500]} الرد JSON فقط: {{"alt": "...", "caption": "..."}}""" return await self.gemini.generate_json(prompt, SYSTEM_ALT_IMAGE) # Legacy — labels now come from section settings in scheduler def _make_labels(self, extracted: Dict, seo: Dict) -> List[str]: labels = set() if extracted.get("type"): labels.add(extracted["type"]) if extracted.get("ministry"): labels.add(extracted["ministry"]) if extracted.get("province"): labels.add(extracted["province"]) if extracted.get("city"): labels.add(extracted["city"]) if extracted.get("company"): labels.add(extracted["company"]) seo_labels = seo.get("labels", []) if isinstance(seo_labels, list): for lbl in seo_labels: if lbl: labels.add(str(lbl)) return list(labels)[:10] async def _summary(self, text: str) -> Optional[str]: prompt = make_summary_prompt(text) result = await self.gemini.generate_json(prompt, SYSTEM_SUMMARY) if result and isinstance(result, dict): return result.get("summary", "") return None async def _notes(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]: prompt = make_notes_prompt(extracted, title, body) result = await self.gemini.generate_json(prompt, SYSTEM_NOTES) if result and isinstance(result, dict): notes = result.get("notes", []) if isinstance(notes, list) and notes: return notes return None async def _keywords(self, title: str, body: str, extracted: Dict) -> Optional[str]: prompt = make_keywords_prompt(title, body, extracted) result = await self.gemini.generate_json(prompt, SYSTEM_KEYWORDS) if result and isinstance(result, dict): kw = result.get("keywords", "") if kw and isinstance(kw, str): return kw return None async def _metadata(self, extracted: Dict, title: str, body: str) -> Optional[Dict]: prompt = make_metadata_prompt(extracted, title, body) result = await self.gemini.generate_json(prompt, SYSTEM_METADATA) if result and isinstance(result, dict): return result return None @staticmethod def _reading_time(body_html: str) -> int: text = re.sub(r'<[^>]+>', '', body_html) word_count = len(text.split()) minutes = max(1, round(word_count / 150)) return minutes def _add_inline_hashtags(self, body: str, extracted: Dict) -> str: entities = [] if extracted.get("city"): entities.append(extracted["city"]) if extracted.get("province"): entities.append(extracted["province"]) if extracted.get("ministry"): entities.append(extracted["ministry"]) if extracted.get("company"): entities.append(extracted["company"]) if extracted.get("university"): entities.append(extracted["university"]) if extracted.get("organization"): entities.append(extracted["organization"]) if extracted.get("job_type"): entities.append(extracted["job_type"]) if extracted.get("district"): entities.append(extracted["district"]) result = body for entity in entities: if entity and len(entity) > 2: tag = entity.replace(" ", "_") replacement = f'#{tag}' result = result.replace(entity, replacement, 1) return result def _article_css(self) -> str: return """""" def make_article_html(self, article: Dict) -> str: parts = [] parts.append(self._article_css()) # ── 0. Article Title ── title = article.get("title", "").strip() if title: parts.append(f'{intro}
(.*?)
', r'\1\n', html, flags=re.DOTALL) html = re.sub(r'