Spaces:
Running
Running
Upload processor.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714import jsonimport reimport timeimport hashlibimport loggingfrom typing import Optional, Dict, Any, List, Tuple
from modules.blogger.ai_manager import AIClient, AIKeyManager, AllProvidersExhausted as AllKeysExhaustedfrom modules.blogger.prompts import ( SYSTEM_REWRITE, SYSTEM_EXTRACT, SYSTEM_SEO, SYSTEM_HASHTAGS, SYSTEM_ALT_IMAGE, SYSTEM_SUMMARY, SYSTEM_NOTES, SYSTEM_KEYWORDS, make_rewrite_prompt, make_extract_prompt, make_seo_prompt, make_hashtag_prompt, make_summary_prompt, make_notes_prompt, make_keywords_prompt,)from modules.blogger.database import BloggerDatabase
logger = logging.getLogger(__name__)
class ArticleProcessor: def __init__(self, db: BloggerDatabase, ai_client: AIClient, config=None): self.db = db self.gemini = ai_client self.config = config
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
fingerprint = self._fingerprint(raw_text, source_url) if self.db.is_published(fingerprint): logger.info(f"Article already processed: {fingerprint[:16]}...") return None
return await self._process_fresh(raw_text, source_url, media, fingerprint, channel_id)
def enqueue_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None, channel_id: str = "") -> Optional[str]: """Save an incoming raw post straight to the Gemini pending queue, WITHOUT ever calling Gemini. This is the entry point used by the automatic channel-polling scheduler, so that ingesting new posts never fails or blocks because of a Gemini cooldown/quota issue. Returns the fingerprint if newly queued, None if it's a duplicate or already being handled.""" raw_text = raw_text.strip() if not raw_text: return None
fingerprint = self._fingerprint(raw_text, source_url) if self.db.is_published(fingerprint): return None existing = self.db.get_article(fingerprint) if existing and existing.get("status") in ("queued", "published", "gemini_pending", "processing"): return None
self._save_to_pending(raw_text, source_url, media, fingerprint, channel_id) return fingerprint
def _save_to_pending(self, raw_text: str, source_url: str, media: List[Dict], fingerprint: str, channel_id: 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)
def _handle_processing_failure(self, fingerprint: str, raw_text: str, source_url: str, media: List[Dict], channel_id: str, error: Exception, article: Dict): """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) 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: logger.warning( f"Article {fingerprint[:16]} processing failed (attempt {attempts}/{self.MAX_PENDING_ATTEMPTS}), " f"kept in pending queue for retry: {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 = "") -> 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) 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) 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) return None finally: self.gemini.release_session()
async def _process_next_pending(self) -> Optional[Dict]: """Try to process the first item in Gemini pending queue (FIFO). Returns the processed article if successful, None otherwise.""" pending = self.db.get_gemini_pending_queue() if not pending: return None first = pending[0] 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(0) return None source_url = first.get("source_url", "") media = first.get("media", []) channel_id = first.get("channel_id", "") 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: return None
result = await self._run_pipeline(article, raw_text, source_url, media) if result: result["channel_id"] = channel_id self.db.remove_pending_by_fingerprint(fingerprint) logger.info(f"Gemini pending queue: recovered article {fingerprint[:16]}") return result except AllKeysExhausted: 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.""" links = self._extract_links(raw_text) rewrite = await self._rewrite(raw_text) if rewrite: article.update(rewrite) body_text = article.get("body", "") if body_text and links: body_text = self._restore_links(body_text, links) article["body"] = body_text extracted = await self._extract(raw_text) if extracted: article["extracted"] = extracted article["labels"] = [] summary = await self._summary(raw_text) if summary: article["summary"] = summary notes = await self._notes( extracted or {}, article.get("title", raw_text[:60]), article.get("body", raw_text), ) if notes: article["notes"] = notes keywords = await self._keywords( article.get("title", raw_text[:60]), article.get("body", raw_text), extracted or {}, ) if keywords: article["keywords"] = keywords hashtags = await self._hashtags( extracted or {}, article.get("title", raw_text[:60]), article.get("body", raw_text), ) if hashtags: article["hashtags"] = hashtags logger.info(f"Hashtags Stored: {hashtags}") else: logger.warning(f"Hashtags Stored: empty or None") body_text = article.get("body", raw_text) article["reading_time"] = self._reading_time(body_text) if media: alt_data = await self._alt_text( article.get("title", raw_text[:60]), article.get("body", raw_text), ) if alt_data: article["media_alt"] = alt_data article["status"] = "processed" article["processed_at"] = int(time.time()) self._save_article(article) return article
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"<p>{text}</p>"), "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
@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
@staticmethod def _extract_links(text: str) -> List[str]: return re.findall(r'https?://[^\s<>"\']+', text)
def _restore_links(self, body: str, links: List[str]) -> str: app_links = [] restored = body for link in links: if link not in restored: if any(kw in link.lower() for kw in ["apply", "form", "jobs", "تقديم", "قدم", "تسجيل"]): app_links.append(link) elif any(kw in link.lower() for kw in ["t.me", "telegram", "docs.google", "forms"]): if link not in restored: restored += f'\n<p><a href="{link}">🔗 رابط خارجي</a></p>' else: if link not in restored: restored += f'\n<p><a href="{link}">🔗 رابط خارجي</a></p>' if app_links: app_section = '<div style="background:#e8f5e9;border-right:4px solid #4caf50;padding:12px 16px;margin:15px 0;border-radius:4px;">' app_section += '<strong style="color:#2e7d32;">🔗 رابط التقديم</strong>' for al in app_links: app_section += f'<p style="margin:5px 0 0 0;"><a href="{al}" target="_blank" rel="noopener" style="color:#1a73e8;font-weight:bold;">{al[:80]}</a></p>' app_section += '</div>' restored = restored + '\n' + app_section return restored
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'<a href="https://www.blogger.com/search?q={tag}" style="text-decoration:none;color:#1a73e8;">#{tag}</a>' result = result.replace(entity, replacement, 1) return result
def make_article_html(self, article: Dict) -> str: parts = [] section = article.get("section", "")
# ── 1. Featured Image ── parts.append(self._make_featured_image(article))
# ── 2. Summary Box ── summary = article.get("summary", "") if summary: parts.append(self._make_summary_box(summary))
# ── 3. Quick Information Card (enhanced for jobs) ── info_card = self._make_info_card(article) if info_card: parts.append(info_card)
# ── 4. Table of Contents ── body = article.get("body", "") toc, processed_body = self._make_toc(body) if toc: parts.append(toc)
# ── 5. Introduction ── intro = article.get("introduction", "") if intro: parts.append(f'<h2 id="intro">المقدمة</h2><p>{intro}</p>')
# ── 6. Read More + Full Article Body ── body_to_process = processed_body or body if body_to_process: parts.append(self._make_read_more(body_to_process))
# ── 8. Important Notes ── notes = article.get("notes", []) if notes: parts.append(self._make_notes_box(notes))
# ── 9. FAQ ── faq = article.get("faq", []) if faq: parts.append(self._make_faq(faq))
# ── 10. Conclusion ── conclusion = article.get("conclusion", "") if conclusion: parts.append(f'<p>{conclusion}</p>')
# ── 11. Hashtags ── hashtags = article.get("hashtags", []) logger.info(f"Hashtags Before HTML: {hashtags}") if hashtags: parts.append(self._make_hashtags_section(hashtags))
# ── 12. Source ── source = article.get("source", {}) if source: parts.append(self._make_source(source))
# ── 12. Keywords ── keywords = article.get("keywords", "") if keywords: parts.append(self._make_keywords_section(keywords))
# ── 13. Schema JSON-LD ── schema = self._make_schema(article) if schema: parts.append(schema)
return "\n".join(parts)
def _make_featured_image(self, article: Dict) -> str: alt_text = article.get("media_alt", {}).get("alt", "") caption = article.get("media_alt", {}).get("caption", "") img_src = None if self.config: img_src = self.config.get("default_jobs_image", "") if not img_src: return "" alt = alt_text or "صورة المقال" title = article.get("title", "")[:60] 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>' if caption: img += f'<p style="text-align:center;font-size:13px;color:#666;margin-top:-10px;">{caption}</p>' return img
def _make_info_card(self, article: Dict) -> str: extracted = article.get("extracted", {}) if not extracted: return "" section = article.get("section", "") is_job = section in ("jobs", "وظائف") or bool(extracted.get("salary")) rows = [] if is_job: if extracted.get("company"): rows.append(("🏢 الشركة", extracted["company"])) elif extracted.get("ministry"): rows.append(("🏛️ الجهة", extracted["ministry"])) if extracted.get("province"): rows.append(("📍 المحافظة", extracted["province"])) if extracted.get("city"): rows.append(("📍 المدينة", extracted["city"])) if extracted.get("job_type"): rows.append(("💼 نوع الوظيفة", extracted["job_type"])) if extracted.get("qualification"): rows.append(("🎓 المؤهل", extracted["qualification"])) if extracted.get("salary"): rows.append(("💰 الراتب", extracted["salary"])) if extracted.get("experience"): rows.append(("⏳ الخبرة", extracted["experience"])) if extracted.get("deadline"): rows.append(("📅 آخر موعد", extracted["deadline"])) if extracted.get("gender"): rows.append(("👤 الجنس", extracted["gender"])) if extracted.get("positions"): rows.append(("👥 عدد الشواغر", extracted["positions"])) if extracted.get("apply_method"): rows.append(("📝 طريقة التقديم", extracted["apply_method"])) else: if extracted.get("ministry"): rows.append(("🏛️ الجهة", extracted["ministry"])) elif extracted.get("company"): rows.append(("🏢 الشركة", extracted["company"])) if extracted.get("province"): rows.append(("📍 المحافظة", extracted["province"])) if extracted.get("city"): rows.append(("📍 المدينة", extracted["city"])) reading_time = article.get("reading_time", self._reading_time(article.get("body", ""))) rows.append(("⏱️ مدة القراءة", f"{reading_time} دقيقة")) rows.append(("📂 القسم", section or "عام")) thead = '<tr style="background:#2c3e50;color:#fff;"><th style="padding:10px 14px;border:1px solid #2c3e50;text-align:right;font-size:15px;">المعلومة</th><th style="padding:10px 14px;border:1px solid #2c3e50;text-align:right;font-size:15px;">التفاصيل</th></tr>' trows = "".join(f'<tr style="background:{ "#fff" if i%2==0 else "#f8f9fa" };"><td style="padding:8px 14px;border:1px solid #dee2e6;font-weight:bold;white-space:nowrap;color:#2c3e50;">{k}</td><td style="padding:8px 14px;border:1px solid #dee2e6;color:#495057;">{v}</td></tr>' for i, (k, v) in enumerate(rows)) return f'<div style="margin:15px 0;font-size:14px;direction:rtl;text-align:right;overflow-x:auto;"><table style="width:100%;border-collapse:collapse;font-family:Tahoma,Arial,sans-serif;">{thead}{trows}</table></div>'
def _make_summary_box(self, summary: str) -> str: return f'<div style="background:#fffbea;border-right:4px solid #f5c518;padding:12px 16px;margin:15px 0;border-radius:4px;"><strong style="color:#856404;">📌 ملخص المقال</strong><p style="margin:8px 0 0 0;color:#856404;font-size:15px;">{summary}</p></div>'
def _make_toc(self, body: str) -> tuple: if not body: return "", body headings = re.findall(r'<h([23])[^>]*>(.*?)</h\1>', body, re.DOTALL) if len(headings) < 2: return "", body items = [] processed = body for i, (level, text) in enumerate(headings): anchor = f"sec-{i}" items.append(f'<li><a href="#{anchor}" style="text-decoration:none;">{text}</a></li>') processed = processed.replace( f'<h{level}>{text}</h{level}>', f'<h{level} id="{anchor}">{text}</h{level}>', 1 ) toc = f'<div style="background:#f8f9fa;border-radius:8px;padding:12px 16px;margin:15px 0;"><strong style="font-size:16px;">📋 المحتويات</strong><ul style="margin:8px 0 0 0;list-style:none;padding:0;">{"".join(items)}</ul></div>' return toc, processed
def _make_read_more(self, body: str) -> str: parts = re.split(r'(<(?:p|h[23]|div|ul|ol|table)[^>]*>)', body, maxsplit=8) if len(parts) < 6: return body preview = parts[0] for i in range(1, min(6, len(parts))): preview += parts[i] rest = "".join(parts[6:]) if not rest.strip(): return body return f'<div>{preview}</div><details style="margin:10px 0;"><summary style="cursor:pointer;background:#1a73e8;color:#fff;font-weight:bold;padding:8px 20px;border-radius:6px;display:inline-block;">📖 متابعة قراءة المقال</summary><div style="margin-top:12px;">{rest}</div></details>'
def _make_extracted_table(self, extracted: Dict) -> str: table_rows = [] labels_map = { "ministry": "الوزارة", "company": "الشركة", "province": "المحافظة", "city": "المدينة", "salary": "الراتب", "qualification": "المؤهل", "gender": "الجنس", "age": "العمر", "experience": "الخبرة", "deadline": "آخر موعد", "apply_url": "رابط التقديم", "email": "البريد الإلكتروني", "phone": "الهاتف", } for key, label in labels_map.items(): val = extracted.get(key) if val: val_str = str(val) if key == "apply_url" and val_str.startswith("http"): val_str = f'<a href="{val_str}">رابط التقديم</a>' table_rows.append(f'<tr><td>{label}</td><td>{val_str}</td></tr>') if not table_rows: return "" return f'<h2>معلومات إضافية</h2><table>{"".join(table_rows)}</table>'
def _make_notes_box(self, notes: list) -> str: lis = "".join(f"<li>{n}</li>" for n in notes) return f'<div style="background:#fff3f3;border-right:4px solid #dc3545;padding:12px 16px;margin:15px 0;border-radius:4px;"><strong style="color:#721c24;">⚠️ ملاحظات مهمة</strong><ul style="margin:8px 0 0 0;color:#721c24;">{lis}</ul></div>'
def _make_faq(self, faq: list) -> str: items = "" for item in faq: q = item.get("question", "") a = item.get("answer", "") if q and a: 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>' if not items: return "" return f'<h2>الأسئلة الشائعة</h2><div itemscope itemtype="https://schema.org/FAQPage">{items}</div>'
def _make_source(self, source: dict) -> str: name = source.get("name", "المصدر") username = source.get("username", "") link = source.get("link", "") if link and username and not username.startswith("private"): 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>' return f'<div style="background:#f0f0f0;padding:10px 12px;border-radius:4px;margin:15px 0;font-size:13px;color:#666;"><strong>المصدر:</strong> {name}</div>'
def _make_keywords_section(self, keywords: str) -> str: return f'<div style="margin:15px 0;padding:10px 12px;background:#f8f9fa;border-radius:4px;"><strong style="font-size:14px;">🏷️ الكلمات الدلالية:</strong><p style="color:#666;margin:5px 0 0 0;font-size:13px;">{keywords}</p></div>'
def _make_hashtags_section(self, hashtags: List[str]) -> str: tags_str = " | ".join(hashtags) return f'<div style="margin:15px 0;padding:10px 12px;background:#f8f9fa;border-radius:4px;"><strong style="font-size:14px;">🏷️ الهاشتاكات:</strong><p style="color:#666;margin:5px 0 0 0;font-size:13px;direction:rtl;text-align:right;">{tags_str}</p></div>'
def _make_schema(self, article: Dict) -> str: title = article.get("title", "") intro = article.get("introduction", "") body = article.get("body", "") text = re.sub(r'<[^>]+>', '', f"{intro} {body}")[:300] section = article.get("section", "") is_news = section not in ("jobs", "وظائف") schema = { "@context": "https://schema.org", "@type": "NewsArticle" if is_news else "Article", "headline": title, "description": text[:160], "articleBody": text, "inLanguage": "ar", "author": {"@type": "Organization", "name": "المدونة"}, "publisher": {"@type": "Organization", "name": "المدونة"}, "datePublished": article.get("created_at", ""), "dateModified": article.get("processed_at", ""), } schema_str = json.dumps(schema, ensure_ascii=False) return f'<script type="application/ld+json">{schema_str}</script>'
def make_preview_data(self, article: Dict) -> Tuple[Optional[str], str]: html = self.make_article_html(article) image = None media = article.get("media", []) for m in media: if m.get("type") == "photo": image = m.get("file_id") break if not image and self.config: section = article.get("section", "") if section in ("jobs", "وظائف", "general"): image = self.config.get("default_jobs_image", "") telegram_text = self.html_to_telegram(html) title = article.get("title", "") if title: telegram_text = f"<b>{title}</b>\n\n{telegram_text}" reading_time = article.get("reading_time", 0) if reading_time: telegram_text += f"\n⏱️ مدة القراءة: {reading_time} دقيقة" labels = article.get("labels", []) if labels: telegram_text += f"\n🏷 {', '.join(labels)}" return image, telegram_text
@staticmethod def html_to_telegram(html: str) -> str: html = re.sub(r'<script[^>]*>.*?</script>', '', html, flags=re.DOTALL)
def _replace_table(m): rows = re.findall(r'<tr>(.*?)</tr>', m.group(1), re.DOTALL) lines = [] for row in rows: cells = re.findall(r'<td[^>]*>(.*?)</td>', row, re.DOTALL) if cells: lines.append(' | '.join(cells)) return '\n'.join(lines) + '\n' html = re.sub(r'<table>(.*?)</table>', _replace_table, html, flags=re.DOTALL) html = re.sub(r'<img[^>]*>', '', html) html = re.sub(r'<h([23])[^>]*>(.*?)</h\1>', r'<b>\2</b>', html, flags=re.DOTALL) html = re.sub(r'<li>(.*?)</li>', r'• \1', html, flags=re.DOTALL) html = re.sub(r'</?u?[ol][^>]*>', '', html) html = re.sub(r'<details[^>]*>', '', html) html = re.sub(r'</details>', '', html) html = re.sub(r'<summary[^>]*>(.*?)</summary>', r'<b>\1</b>\n', html, flags=re.DOTALL) html = re.sub(r'</?div[^>]*>', '', html) html = re.sub(r'</?span[^>]*>', '', html) html = re.sub(r'<p>(.*?)</p>', r'\1\n', html, flags=re.DOTALL) html = re.sub(r'<br\s*/?>', '\n', html) html = re.sub(r'<strong>(.*?)</strong>', r'<b>\1</b>', html) html = re.sub(r'<em>(.*?)</em>', r'<i>\1</i>', html) html = re.sub(r'</?t[rdh][^>]*>', '', html) allowed = {'b', 'i', 'u', 's', 'a', 'code', 'pre', 'em', 'strong'} html = re.sub(r'<(?!/?(' + '|'.join(allowed) + r')(?:\s[^>]*)?>)[a-z]+[^>]*>', '', html, flags=re.IGNORECASE) html = re.sub(r'</(?!(' + '|'.join(allowed) + r')\b)[a-z]+>', '', html, flags=re.IGNORECASE) html = re.sub(r'\n{3,}', '\n\n', html) return html.strip()modules/blogger/processor.pyAdded+714