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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 |
+
SECTION_ICONS = {
|
| 33 |
+
"ูุจุฐุฉ": "โน๏ธ", "ุชูุงุตูู": "๐", "ุจูุฆุฉ": "๐ข", "ุงูู
ูุงู
": "๐",
|
| 34 |
+
"ู
ุคููุงุช": "๐", "ุดุฑูุท": "๐", "ุชูุฏูู
": "๐", "ู
ู
ูุฒุงุช": "โญ",
|
| 35 |
+
"ุฃุณุฆูุฉ": "โ", "ุฎูุงุตุฉ": "โ
", "ุชุนููู
ุงุช": "๐", "ู
ูุงุญุธุงุช": "โ ๏ธ",
|
| 36 |
+
"ุทุฑููุฉ": "๐", "ุดูุงุบุฑ": "๐ฅ", "ุฑุงุชุจ": "๐ฐ", "ุฏูุงู
": "๐",
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class ArticleProcessor:
|
| 41 |
+
def __init__(self, db: BloggerDatabase, ai_client: AIClient, config=None):
|
| 42 |
+
self.db = db
|
| 43 |
+
self.gemini = ai_client
|
| 44 |
+
self.config = config
|
| 45 |
+
|
| 46 |
+
MAX_PENDING_ATTEMPTS = 5
|
| 47 |
+
|
| 48 |
+
async def process_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None, channel_id: str = "") -> Optional[Dict]:
|
| 49 |
+
"""Immediate/manual processing path (e.g. UI 'preview now' button).
|
| 50 |
+
Attempts Gemini processing right away. NOT used by the automatic channel
|
| 51 |
+
polling flow โ that flow uses enqueue_raw_post() instead so that message
|
| 52 |
+
ingestion never depends on Gemini availability."""
|
| 53 |
+
raw_text = raw_text.strip()
|
| 54 |
+
if not raw_text:
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
fingerprint = self._fingerprint(raw_text, source_url)
|
| 58 |
+
if self.db.is_published(fingerprint):
|
| 59 |
+
logger.info(f"Article already processed: {fingerprint[:16]}...")
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
return await self._process_fresh(raw_text, source_url, media, fingerprint, channel_id)
|
| 63 |
+
|
| 64 |
+
def enqueue_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None,
|
| 65 |
+
channel_id: str = "", section: str = "") -> Optional[str]:
|
| 66 |
+
"""Save an incoming raw post straight to the Gemini pending queue, WITHOUT ever
|
| 67 |
+
calling Gemini. This is the entry point used by the automatic channel-polling
|
| 68 |
+
scheduler, so that ingesting new posts never fails or blocks because of a
|
| 69 |
+
Gemini cooldown/quota issue. Returns the fingerprint if newly queued,
|
| 70 |
+
None if it's a duplicate or already being handled."""
|
| 71 |
+
raw_text = raw_text.strip()
|
| 72 |
+
if not raw_text:
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
fingerprint = self._fingerprint(raw_text, source_url)
|
| 76 |
+
if self.db.is_published(fingerprint):
|
| 77 |
+
return None
|
| 78 |
+
existing = self.db.get_article(fingerprint)
|
| 79 |
+
if existing and existing.get("status") in ("queued", "published", "gemini_pending", "processing"):
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
self._save_to_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 83 |
+
return fingerprint
|
| 84 |
+
|
| 85 |
+
def _save_to_pending(self, raw_text: str, source_url: str, media: List[Dict], fingerprint: str,
|
| 86 |
+
channel_id: str = "", section: str = ""):
|
| 87 |
+
article = {
|
| 88 |
+
"fingerprint": fingerprint,
|
| 89 |
+
"source_text": raw_text,
|
| 90 |
+
"source_url": source_url,
|
| 91 |
+
"media": media or [],
|
| 92 |
+
"channel_id": channel_id,
|
| 93 |
+
"status": "gemini_pending",
|
| 94 |
+
"created_at": int(time.time()),
|
| 95 |
+
}
|
| 96 |
+
self._save_article(article)
|
| 97 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 98 |
+
|
| 99 |
+
def _handle_processing_failure(self, fingerprint: str, raw_text: str, source_url: str,
|
| 100 |
+
media: List[Dict], channel_id: str, error: Exception,
|
| 101 |
+
article: Dict, section: str = ""):
|
| 102 |
+
"""Called whenever an unexpected error occurs while processing an article
|
| 103 |
+
(fresh or from the pending queue). Keeps the article retry-able in the
|
| 104 |
+
pending queue instead of losing it, up to MAX_PENDING_ATTEMPTS."""
|
| 105 |
+
attempts = self.db.increment_pending_attempts(fingerprint)
|
| 106 |
+
if attempts == -1:
|
| 107 |
+
# Wasn't in the pending queue yet (e.g. failed during the "fresh" path) โ add it.
|
| 108 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 109 |
+
attempts = self.db.increment_pending_attempts(fingerprint)
|
| 110 |
+
if attempts == -1:
|
| 111 |
+
attempts = 1
|
| 112 |
+
if attempts >= self.MAX_PENDING_ATTEMPTS:
|
| 113 |
+
logger.error(
|
| 114 |
+
f"Article {fingerprint[:16]} failed {attempts} times, giving up permanently: {error}"
|
| 115 |
+
)
|
| 116 |
+
article["status"] = "failed_permanent"
|
| 117 |
+
article["error"] = str(error)
|
| 118 |
+
self._save_article(article)
|
| 119 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 120 |
+
else:
|
| 121 |
+
eta = self.db.set_pending_retry_after(fingerprint, attempts)
|
| 122 |
+
logger.warning(
|
| 123 |
+
f"Article {fingerprint[:16]} processing failed (attempt {attempts}/{self.MAX_PENDING_ATTEMPTS}), "
|
| 124 |
+
f"kept in pending queue, retry in {eta}s: {error}"
|
| 125 |
+
)
|
| 126 |
+
article["status"] = "gemini_pending"
|
| 127 |
+
article["error"] = str(error)
|
| 128 |
+
self._save_article(article)
|
| 129 |
+
|
| 130 |
+
async def _process_fresh(self, raw_text: str, source_url: str, media: List[Dict], fingerprint: str, channel_id: str = "", section: str = "") -> Optional[Dict]:
|
| 131 |
+
article = {
|
| 132 |
+
"fingerprint": fingerprint,
|
| 133 |
+
"source_text": raw_text,
|
| 134 |
+
"source_url": source_url,
|
| 135 |
+
"media": media or [],
|
| 136 |
+
"channel_id": channel_id,
|
| 137 |
+
"status": "processing",
|
| 138 |
+
"created_at": int(time.time()),
|
| 139 |
+
}
|
| 140 |
+
try:
|
| 141 |
+
session_ok = await self.gemini.acquire_session()
|
| 142 |
+
if not session_ok:
|
| 143 |
+
logger.warning(f"Gemini session failed for {fingerprint[:16]}, saving to pending")
|
| 144 |
+
article["status"] = "gemini_pending"
|
| 145 |
+
self._save_article(article)
|
| 146 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 147 |
+
return None
|
| 148 |
+
|
| 149 |
+
result = await self._run_pipeline(article, raw_text, source_url, media)
|
| 150 |
+
return result
|
| 151 |
+
except AllKeysExhausted:
|
| 152 |
+
logger.warning(f"All Gemini keys exhausted processing {fingerprint[:16]}, saving to pending")
|
| 153 |
+
article["status"] = "gemini_pending"
|
| 154 |
+
self._save_article(article)
|
| 155 |
+
self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
|
| 156 |
+
return None
|
| 157 |
+
except Exception as e:
|
| 158 |
+
logger.exception(f"Article processing failed: {e}")
|
| 159 |
+
self._handle_processing_failure(fingerprint, raw_text, source_url, media, channel_id, e, article, section)
|
| 160 |
+
return None
|
| 161 |
+
finally:
|
| 162 |
+
self.gemini.release_session()
|
| 163 |
+
|
| 164 |
+
async def _process_next_pending(self) -> Optional[Dict]:
|
| 165 |
+
"""Try to process the next retry-ready item in the Gemini pending queue (FIFO).
|
| 166 |
+
Items still in exponential backoff are skipped so one blocked article does
|
| 167 |
+
not stall the rest of the queue. Returns the processed article if successful,
|
| 168 |
+
None otherwise."""
|
| 169 |
+
pending = self.db.get_gemini_pending_queue()
|
| 170 |
+
if not pending:
|
| 171 |
+
return None
|
| 172 |
+
now = time.time()
|
| 173 |
+
first = None
|
| 174 |
+
first_idx = 0
|
| 175 |
+
for idx, item in enumerate(pending):
|
| 176 |
+
retry_after = item.get("retry_after", 0)
|
| 177 |
+
if retry_after and now < retry_after:
|
| 178 |
+
continue
|
| 179 |
+
first = item
|
| 180 |
+
first_idx = idx
|
| 181 |
+
break
|
| 182 |
+
if first is None:
|
| 183 |
+
logger.info("Gemini pending queue: all items in backoff, deferring")
|
| 184 |
+
return None
|
| 185 |
+
raw_text = first.get("raw_text", "").strip()
|
| 186 |
+
fingerprint = first.get("fingerprint", "")
|
| 187 |
+
if not raw_text:
|
| 188 |
+
if fingerprint:
|
| 189 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 190 |
+
else:
|
| 191 |
+
self.db.remove_from_gemini_pending(first_idx)
|
| 192 |
+
return None
|
| 193 |
+
source_url = first.get("source_url", "")
|
| 194 |
+
media = first.get("media", [])
|
| 195 |
+
channel_id = first.get("channel_id", "")
|
| 196 |
+
pending_section = first.get("section", "")
|
| 197 |
+
if not fingerprint:
|
| 198 |
+
fingerprint = self._fingerprint(raw_text, source_url)
|
| 199 |
+
|
| 200 |
+
if self.db.is_published(fingerprint):
|
| 201 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 202 |
+
return None
|
| 203 |
+
|
| 204 |
+
article = {
|
| 205 |
+
"fingerprint": fingerprint,
|
| 206 |
+
"source_text": raw_text,
|
| 207 |
+
"source_url": source_url,
|
| 208 |
+
"media": media,
|
| 209 |
+
"channel_id": channel_id,
|
| 210 |
+
"status": "processing",
|
| 211 |
+
"created_at": int(time.time()),
|
| 212 |
+
}
|
| 213 |
+
try:
|
| 214 |
+
session_ok = await self.gemini.acquire_session()
|
| 215 |
+
if not session_ok:
|
| 216 |
+
self._handle_processing_failure(
|
| 217 |
+
fingerprint, raw_text, source_url, media, channel_id,
|
| 218 |
+
AllKeysExhausted("No AI provider available"), article
|
| 219 |
+
)
|
| 220 |
+
return None
|
| 221 |
+
|
| 222 |
+
result = await self._run_pipeline(article, raw_text, source_url, media)
|
| 223 |
+
if result:
|
| 224 |
+
result["channel_id"] = channel_id
|
| 225 |
+
if pending_section and not result.get("section"):
|
| 226 |
+
result["section"] = pending_section
|
| 227 |
+
self.db.remove_pending_by_fingerprint(fingerprint)
|
| 228 |
+
logger.info(f"Gemini pending queue: recovered article {fingerprint[:16]}")
|
| 229 |
+
return result
|
| 230 |
+
except AllKeysExhausted as e:
|
| 231 |
+
self._handle_processing_failure(
|
| 232 |
+
fingerprint, raw_text, source_url, media, channel_id, e, article
|
| 233 |
+
)
|
| 234 |
+
return None
|
| 235 |
+
except Exception as e:
|
| 236 |
+
logger.exception(f"Pending recovery failed for {fingerprint[:16]}: {e}")
|
| 237 |
+
# Keep the item in pending (up to MAX_PENDING_ATTEMPTS) instead of losing it.
|
| 238 |
+
self._handle_processing_failure(fingerprint, raw_text, source_url, media, channel_id, e, article)
|
| 239 |
+
return None
|
| 240 |
+
finally:
|
| 241 |
+
self.gemini.release_session()
|
| 242 |
+
|
| 243 |
+
async def _run_pipeline(self, article: Dict, raw_text: str, source_url: str = "", media: List[Dict] = None) -> Optional[Dict]:
|
| 244 |
+
"""Execute the full Gemini pipeline on raw_text and populate article dict."""
|
| 245 |
+
clean_text = self._clean_source_footer(raw_text)
|
| 246 |
+
rewrite = await self._rewrite(clean_text)
|
| 247 |
+
if rewrite:
|
| 248 |
+
article.update(rewrite)
|
| 249 |
+
extracted = await self._extract(clean_text)
|
| 250 |
+
if extracted:
|
| 251 |
+
article["extracted"] = extracted
|
| 252 |
+
article["labels"] = []
|
| 253 |
+
summary = await self._summary(clean_text)
|
| 254 |
+
if summary:
|
| 255 |
+
article["summary"] = summary
|
| 256 |
+
metadata = await self._metadata(
|
| 257 |
+
extracted or {},
|
| 258 |
+
article.get("title", raw_text[:60]),
|
| 259 |
+
article.get("body", raw_text),
|
| 260 |
+
)
|
| 261 |
+
if metadata:
|
| 262 |
+
keywords = metadata.get("keywords")
|
| 263 |
+
hashtags = metadata.get("hashtags")
|
| 264 |
+
notes = metadata.get("notes")
|
| 265 |
+
if keywords:
|
| 266 |
+
article["keywords"] = keywords
|
| 267 |
+
if hashtags:
|
| 268 |
+
article["hashtags"] = hashtags
|
| 269 |
+
logger.info(f"Hashtags Stored: {hashtags}")
|
| 270 |
+
else:
|
| 271 |
+
logger.warning(f"Hashtags Stored: empty or None")
|
| 272 |
+
if notes:
|
| 273 |
+
article["notes"] = notes
|
| 274 |
+
else:
|
| 275 |
+
logger.warning("Gemini _metadata returned no result")
|
| 276 |
+
body_text = article.get("body", raw_text)
|
| 277 |
+
article["reading_time"] = self._reading_time(body_text)
|
| 278 |
+
if media:
|
| 279 |
+
alt_data = await self._alt_text(
|
| 280 |
+
article.get("title", raw_text[:60]),
|
| 281 |
+
article.get("body", raw_text),
|
| 282 |
+
)
|
| 283 |
+
if alt_data:
|
| 284 |
+
article["media_alt"] = alt_data
|
| 285 |
+
article["status"] = "processed"
|
| 286 |
+
article["processed_at"] = int(time.time())
|
| 287 |
+
self._save_article(article)
|
| 288 |
+
return article
|
| 289 |
+
|
| 290 |
+
@staticmethod
|
| 291 |
+
def _clean_source_footer(text: str) -> str:
|
| 292 |
+
"""Remove source-channel footer/signature lines before contact extraction."""
|
| 293 |
+
if not text:
|
| 294 |
+
return ""
|
| 295 |
+
kept = []
|
| 296 |
+
for raw in text.splitlines():
|
| 297 |
+
line = raw.strip()
|
| 298 |
+
if not line:
|
| 299 |
+
continue
|
| 300 |
+
low = line.lower()
|
| 301 |
+
if re.search(r'(?:t\.me/|telegram\.me/|tlgrm\.me/)', low):
|
| 302 |
+
continue
|
| 303 |
+
if re.match(r'^@[\w.]+$', line):
|
| 304 |
+
continue
|
| 305 |
+
if re.search(r'castlejob|castle\s*job|ููุนุฉ ุงููุธุงุฆู', low):
|
| 306 |
+
continue
|
| 307 |
+
if re.search(r'telegram|ุชูุบุฑุงู
|ุชูููุฌุฑุงู
|ุชูุฌุฑุงู
', low):
|
| 308 |
+
continue
|
| 309 |
+
if re.search(r'ุชุงุจุนููุง|ุชุชุงุจุนูุง|ู
ุชุงุจุนุชูุง|ู
ุชุงุจุนุฉ ุงูููุงุฉ|ุงูู
ุฒูุฏ ู
ู ุงููุธุงุฆู|ููู
ุฒูุฏ ู
ู ุงููุธุงุฆู|ููู
ุฒูุฏ ู
ู ุงููุฑุต|ุงุดุชุฑู ุจุงูููุงุฉ|ุงูุถู
ููููุงุฉ|ููุงุชูุง|ููุงุฉ ุงููุธุงุฆู|follow us|join telegram|subscribe', low):
|
| 310 |
+
continue
|
| 311 |
+
kept.append(raw)
|
| 312 |
+
return "\n".join(kept).strip()
|
| 313 |
+
|
| 314 |
+
def _fingerprint(self, text: str, url: str = "") -> str:
|
| 315 |
+
raw = f"{url}|{text[:300]}"
|
| 316 |
+
return hashlib.md5(raw.encode("utf-8", errors="replace")).hexdigest()
|
| 317 |
+
|
| 318 |
+
def _save_article(self, article: Dict):
|
| 319 |
+
aid = article.get("fingerprint", str(int(time.time())))
|
| 320 |
+
self.db.save_article(aid, article)
|
| 321 |
+
|
| 322 |
+
async def _rewrite(self, text: str) -> Optional[Dict]:
|
| 323 |
+
prompt = make_rewrite_prompt(text)
|
| 324 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_REWRITE)
|
| 325 |
+
if not result:
|
| 326 |
+
logger.warning("Gemini _rewrite returned no result")
|
| 327 |
+
return None
|
| 328 |
+
logger.info("Gemini _rewrite succeeded")
|
| 329 |
+
return {
|
| 330 |
+
"title": result.get("title", text[:80]),
|
| 331 |
+
"body": result.get("body", f"<p>{text}</p>"),
|
| 332 |
+
"introduction": result.get("introduction", ""),
|
| 333 |
+
"faq": result.get("faq", []),
|
| 334 |
+
"conclusion": result.get("conclusion", ""),
|
| 335 |
+
"gemini_used": True,
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
async def _extract(self, text: str) -> Optional[Dict]:
|
| 339 |
+
prompt = make_extract_prompt(text)
|
| 340 |
+
return await self.gemini.generate_json(prompt, SYSTEM_EXTRACT)
|
| 341 |
+
|
| 342 |
+
async def _seo(self, title: str, body: str) -> Optional[Dict]:
|
| 343 |
+
prompt = make_seo_prompt(title, body)
|
| 344 |
+
return await self.gemini.generate_json(prompt, SYSTEM_SEO)
|
| 345 |
+
|
| 346 |
+
async def _hashtags(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]:
|
| 347 |
+
prompt = make_hashtag_prompt(extracted, title, body)
|
| 348 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_HASHTAGS)
|
| 349 |
+
if result and isinstance(result, dict):
|
| 350 |
+
tags = result.get("hashtags", [])
|
| 351 |
+
if isinstance(tags, list):
|
| 352 |
+
logger.info(f"Hashtags Generated: {tags}")
|
| 353 |
+
return tags
|
| 354 |
+
logger.warning(f"Hashtags Generated but 'hashtags' key is not list: {type(tags)}")
|
| 355 |
+
else:
|
| 356 |
+
logger.warning(f"Hashtags Generated: AI returned invalid data: {result}")
|
| 357 |
+
return []
|
| 358 |
+
|
| 359 |
+
async def _alt_text(self, title: str, body: str) -> Optional[Dict]:
|
| 360 |
+
prompt = f"""ุฃูุดุฆ ูุตู ALT ูุชุนููู ููุตูุฑุฉ ุจูุงุกู ุนูู:
|
| 361 |
+
ุงูุนููุงู: {title}
|
| 362 |
+
ุงูู
ุญุชูู: {body[:500]}
|
| 363 |
+
ุงูุฑุฏ JSON ููุท: {{"alt": "...", "caption": "..."}}"""
|
| 364 |
+
return await self.gemini.generate_json(prompt, SYSTEM_ALT_IMAGE)
|
| 365 |
+
|
| 366 |
+
# Legacy โ labels now come from section settings in scheduler
|
| 367 |
+
def _make_labels(self, extracted: Dict, seo: Dict) -> List[str]:
|
| 368 |
+
labels = set()
|
| 369 |
+
if extracted.get("type"):
|
| 370 |
+
labels.add(extracted["type"])
|
| 371 |
+
if extracted.get("ministry"):
|
| 372 |
+
labels.add(extracted["ministry"])
|
| 373 |
+
if extracted.get("province"):
|
| 374 |
+
labels.add(extracted["province"])
|
| 375 |
+
if extracted.get("city"):
|
| 376 |
+
labels.add(extracted["city"])
|
| 377 |
+
if extracted.get("company"):
|
| 378 |
+
labels.add(extracted["company"])
|
| 379 |
+
seo_labels = seo.get("labels", [])
|
| 380 |
+
if isinstance(seo_labels, list):
|
| 381 |
+
for lbl in seo_labels:
|
| 382 |
+
if lbl:
|
| 383 |
+
labels.add(str(lbl))
|
| 384 |
+
return list(labels)[:10]
|
| 385 |
+
|
| 386 |
+
async def _summary(self, text: str) -> Optional[str]:
|
| 387 |
+
prompt = make_summary_prompt(text)
|
| 388 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_SUMMARY)
|
| 389 |
+
if result and isinstance(result, dict):
|
| 390 |
+
return result.get("summary", "")
|
| 391 |
+
return None
|
| 392 |
+
|
| 393 |
+
async def _notes(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]:
|
| 394 |
+
prompt = make_notes_prompt(extracted, title, body)
|
| 395 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_NOTES)
|
| 396 |
+
if result and isinstance(result, dict):
|
| 397 |
+
notes = result.get("notes", [])
|
| 398 |
+
if isinstance(notes, list) and notes:
|
| 399 |
+
return notes
|
| 400 |
+
return None
|
| 401 |
+
|
| 402 |
+
async def _keywords(self, title: str, body: str, extracted: Dict) -> Optional[str]:
|
| 403 |
+
prompt = make_keywords_prompt(title, body, extracted)
|
| 404 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_KEYWORDS)
|
| 405 |
+
if result and isinstance(result, dict):
|
| 406 |
+
kw = result.get("keywords", "")
|
| 407 |
+
if kw and isinstance(kw, str):
|
| 408 |
+
return kw
|
| 409 |
+
return None
|
| 410 |
+
|
| 411 |
+
async def _metadata(self, extracted: Dict, title: str, body: str) -> Optional[Dict]:
|
| 412 |
+
prompt = make_metadata_prompt(extracted, title, body)
|
| 413 |
+
result = await self.gemini.generate_json(prompt, SYSTEM_METADATA)
|
| 414 |
+
if result and isinstance(result, dict):
|
| 415 |
+
return result
|
| 416 |
+
return None
|
| 417 |
+
|
| 418 |
+
@staticmethod
|
| 419 |
+
def _reading_time(body_html: str) -> int:
|
| 420 |
+
text = re.sub(r'<[^>]+>', '', body_html)
|
| 421 |
+
word_count = len(text.split())
|
| 422 |
+
minutes = max(1, round(word_count / 150))
|
| 423 |
+
return minutes
|
| 424 |
+
|
| 425 |
+
def _add_inline_hashtags(self, body: str, extracted: Dict) -> str:
|
| 426 |
+
entities = []
|
| 427 |
+
if extracted.get("city"):
|
| 428 |
+
entities.append(extracted["city"])
|
| 429 |
+
if extracted.get("province"):
|
| 430 |
+
entities.append(extracted["province"])
|
| 431 |
+
if extracted.get("ministry"):
|
| 432 |
+
entities.append(extracted["ministry"])
|
| 433 |
+
if extracted.get("company"):
|
| 434 |
+
entities.append(extracted["company"])
|
| 435 |
+
if extracted.get("university"):
|
| 436 |
+
entities.append(extracted["university"])
|
| 437 |
+
if extracted.get("organization"):
|
| 438 |
+
entities.append(extracted["organization"])
|
| 439 |
+
if extracted.get("job_type"):
|
| 440 |
+
entities.append(extracted["job_type"])
|
| 441 |
+
if extracted.get("district"):
|
| 442 |
+
entities.append(extracted["district"])
|
| 443 |
+
result = body
|
| 444 |
+
for entity in entities:
|
| 445 |
+
if entity and len(entity) > 2:
|
| 446 |
+
tag = entity.replace(" ", "_")
|
| 447 |
+
replacement = f'<a href="https://www.blogger.com/search?q={tag}" style="text-decoration:none;color:#1a73e8;">#{tag}</a>'
|
| 448 |
+
result = result.replace(entity, replacement, 1)
|
| 449 |
+
return result
|
| 450 |
+
|
| 451 |
+
def _article_css(self) -> str:
|
| 452 |
+
return """<style>
|
| 453 |
+
html{scroll-behavior:smooth;}
|
| 454 |
+
.blog-article{font-family:'Segoe UI',Tahoma,Arial,sans-serif;color:#2b3440;font-size:16px;line-height:1.9;direction:rtl;text-align:right;}
|
| 455 |
+
.blog-article h2,.blog-article h3,.blog-article h4{font-weight:bold!important;clear:both;color:#1a1a2e;line-height:1.6;}
|
| 456 |
+
.blog-article h2{font-size:19px;}
|
| 457 |
+
.blog-article h3{font-size:17px;}
|
| 458 |
+
.blog-article p{line-height:1.9;color:#374151;margin:8px 0;font-size:15px;}
|
| 459 |
+
.blog-article a{color:#1a73e8;text-decoration:none;}
|
| 460 |
+
.blog-article a:hover{text-decoration:underline;}
|
| 461 |
+
.blog-article img{max-width:100%;height:auto;}
|
| 462 |
+
table,.job-table{width:100%;border-collapse:separate;border-spacing:0;margin:16px 0;font-size:14px;direction:rtl;text-align:right;font-family:'Segoe UI',Tahoma,Arial,sans-serif;background:#fff;border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;box-shadow:0 1px 3px rgba(30,60,120,.06);}
|
| 463 |
+
table th,.job-table th{background:#1f3a5f;color:#fff;padding:11px 14px;border:1px solid #1f3a5f;text-align:right;font-weight:bold;font-size:14px;}
|
| 464 |
+
table td,.job-table td{padding:11px 14px;border:1px solid #e7ebf1;color:#2c3e50;vertical-align:top;line-height:1.7;font-size:14px;text-align:right;}
|
| 465 |
+
table tr:nth-child(even) td,.job-table tr:nth-child(even) td{background:#f6f8fb;}
|
| 466 |
+
table tr:hover td,.job-table tr:hover td{background:#eef4fb;}
|
| 467 |
+
.sec-card{background:#ffffff;border:1px solid #e6ebf2;border-radius:14px;padding:18px 20px;margin:16px 0;box-shadow:0 2px 8px rgba(30,60,120,.05);}
|
| 468 |
+
.sec-title{background:linear-gradient(135deg,#eef4ff,#fafcff)!important;color:#1a4f9e!important;border-right:4px solid #2f7cf6;padding:10px 14px;border-radius:10px;margin:0 0 12px 0!important;}
|
| 469 |
+
.summary-box{background:linear-gradient(135deg,#fffdf6,#fff6d6);border:1px solid #f3dca2;border-right:4px solid #f5b301;border-radius:12px;padding:14px 18px;margin:16px 0;}
|
| 470 |
+
.summary-box p{color:#6b5300!important;margin:8px 0 0 0;}
|
| 471 |
+
.notes-box{background:linear-gradient(135deg,#fff7f7,#ffecec);border:1px solid #f3cccc;border-right:4px solid #e74c4c;border-radius:12px;padding:14px 18px;margin:16px 0;}
|
| 472 |
+
.notes-box ul{color:#7f1d1d!important;margin:8px 0 0 0;padding-right:20px;}
|
| 473 |
+
.toc-box{background:#f7fbff;border:1px solid #d3e4fa;border-radius:14px;padding:16px 18px;margin:16px 0;box-shadow:0 1px 4px rgba(26,80,232,.08);}
|
| 474 |
+
.toc-box ul{margin:8px 0 0 0;list-style:none;padding:0;}
|
| 475 |
+
.toc-box li{margin:5px 0;}
|
| 476 |
+
.toc-box a{color:#1a73e8;font-size:14px;display:block;padding:5px 10px;border-radius:8px;}
|
| 477 |
+
.toc-box a:hover{background:#e8f0fe;text-decoration:none;}
|
| 478 |
+
.hashtag-box,.keywords-box{margin:16px 0;padding:14px 18px;background:#ffffff;border:1px solid #e6ebf2;border-radius:14px;box-shadow:0 1px 4px rgba(30,60,120,.05);}
|
| 479 |
+
.ht-wrap,.kw-wrap{text-align:center;margin-top:8px;}
|
| 480 |
+
.ht-chip{display:inline-block;background:linear-gradient(135deg,#e3f2fd,#d6ebff);color:#0d47a1;border:1px solid #90caf9;padding:4px 14px;margin:4px;border-radius:20px;font-size:13px;font-weight:bold;line-height:1.5;}
|
| 481 |
+
.kw-chip{display:inline-block;background:linear-gradient(135deg,#f4ecfd,#efe4ff);color:#6a1b9a;border:1px solid #d3b5f2;padding:4px 14px;margin:4px;border-radius:20px;font-size:13px;line-height:1.5;}
|
| 482 |
+
.tag{display:inline-block;background:#e3f2fd;color:#1565c0;padding:4px 12px;margin:3px 4px;border-radius:16px;font-size:13px;border:1px solid #90caf9;}
|
| 483 |
+
.sec-head{font-size:15px;font-weight:bold;margin-bottom:8px;display:block;}
|
| 484 |
+
.toc-head{color:#1a4f9e;}
|
| 485 |
+
.has-head{color:#0d47a1;}
|
| 486 |
+
.kw-head{color:#6a1b9a;}
|
| 487 |
+
.sum-head{color:#8a6d1a;}
|
| 488 |
+
.notes-head{color:#7f1d1d;}
|
| 489 |
+
.faq-card{background:#f8fbff;border:1px solid #d3e4fa;border-radius:14px;padding:16px 20px;margin:16px 0;}
|
| 490 |
+
.faq-h{color:#1a4f9e;margin:0 0 12px 0;}
|
| 491 |
+
.faq-q{font-size:16px;margin-top:15px;color:#1a1a2e;}
|
| 492 |
+
.faq-a p{color:#374151;}
|
| 493 |
+
.article-end{background:linear-gradient(135deg,#e8f4fd,#dff0ff);border:1px solid #b9dcf7;border-right:4px solid #1a73e8;border-radius:14px;padding:18px 22px;margin:22px 0;text-align:center;box-shadow:0 2px 8px rgba(26,80,232,.08);}
|
| 494 |
+
.article-end p{margin:0;font-size:16px;color:#0b3d66;line-height:1.9;}
|
| 495 |
+
.tg-card{background:linear-gradient(135deg,#e7f3ff,#dbefff);border:1px solid #a9d4f7;border-radius:16px;padding:18px;margin:20px 0;text-align:center;box-shadow:0 2px 10px rgba(26,112,232,.10);}
|
| 496 |
+
.tg-card-h{font-size:17px;font-weight:bold;color:#0b5fa5;margin-bottom:8px;}
|
| 497 |
+
.tg-card-p{font-size:14px;color:#2e4a70;margin:0 0 14px 0;line-height:1.9;}
|
| 498 |
+
.tg-card-btn{display:inline-block;background:linear-gradient(135deg,#1e8ff0,#1a73e8);color:#ffffff!important;padding:11px 26px;border-radius:26px;font-size:15px;font-weight:bold;text-decoration:none!important;box-shadow:0 2px 8px rgba(26,115,232,.35);}
|
| 499 |
+
.tg-card-btn:hover{opacity:.92;text-decoration:none!important;}
|
| 500 |
+
.apply-section{margin:18px 0;text-align:center;direction:rtl;}
|
| 501 |
+
.apply-box{display:block;margin:14px auto;max-width:520px;background:linear-gradient(135deg,#fffdf3,#fff6d6);border:1px solid #f2d47c;border-radius:14px;padding:18px 22px;text-align:right;box-shadow:0 3px 10px rgba(120,90,0,.10);}
|
| 502 |
+
.apply-box-title{font-size:17px;font-weight:bold;color:#7a5c00;margin-bottom:12px;text-align:center;border-bottom:1px dashed #f0d48a;padding-bottom:8px;}
|
| 503 |
+
.apply-row{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;padding:9px 0;border-bottom:1px solid #faf0ce;}
|
| 504 |
+
.apply-row:last-child{border-bottom:0;}
|
| 505 |
+
.apply-row-label{font-weight:bold;font-size:14px;color:#7a5c00;}
|
| 506 |
+
.apply-box-phone .apply-row-label{color:#6b5300;}
|
| 507 |
+
.apply-box-phone{color:#6b5300;}
|
| 508 |
+
.apply-box-value{font-size:18px;font-weight:bold;color:#8a5a00;direction:ltr;display:inline-block;word-break:break-all;text-decoration:none!important;background:#fffce8;border:1px solid #f0d48a;border-radius:8px;padding:5px 12px;}
|
| 509 |
+
.apply-box-value:hover{text-decoration:underline!important;}
|
| 510 |
+
.apply-box-phone .apply-box-value{color:#5a4400;font-size:22px;}
|
| 511 |
+
.apply-box-actions{margin-top:14px;text-align:center;}
|
| 512 |
+
.apply-btn{display:inline-block;padding:10px 28px;border-radius:24px;font-weight:bold;font-size:15px;margin:4px;text-decoration:none!important;color:#fff!important;box-shadow:0 2px 6px rgba(0,0,0,.14);transition:transform .12s,opacity .15s;}
|
| 513 |
+
.apply-btn:hover{opacity:.92;text-decoration:none!important;transform:translateY(-1px);}
|
| 514 |
+
.apply-btn-call{background:linear-gradient(135deg,#1a73e8,#1557b0);}
|
| 515 |
+
.apply-btn-whatsapp{background:linear-gradient(135deg,#25d366,#1da851);}
|
| 516 |
+
.apply-btn-cv{background:linear-gradient(135deg,#8e24aa,#6a1b9a);}
|
| 517 |
+
.apply-btn-now{background:linear-gradient(135deg,#ffb300,#f57c00);}
|
| 518 |
+
.article-title{font-size:26px;font-weight:bold!important;color:#1a1a2e;line-height:1.5;margin:6px 0 4px 0;}
|
| 519 |
+
@media (max-width:768px){
|
| 520 |
+
.blog-article{font-size:15px;}
|
| 521 |
+
.sec-card{padding:14px 14px;margin:12px 0;}
|
| 522 |
+
.apply-btn{padding:9px 20px;}
|
| 523 |
+
}
|
| 524 |
+
@media (max-width:600px){
|
| 525 |
+
.blog-article{font-size:14px;}
|
| 526 |
+
table,.job-table{font-size:13px;}
|
| 527 |
+
table th,table td,.job-table th,.job-table td{padding:8px 10px;}
|
| 528 |
+
.apply-box{width:92%;padding:14px 14px;}
|
| 529 |
+
.apply-box-value{font-size:17px;}
|
| 530 |
+
.apply-box-phone .apply-box-value{font-size:22px;}
|
| 531 |
+
.apply-btn{display:block;margin:6px auto;width:70%;}
|
| 532 |
+
.tg-card-btn{display:block;width:80%;margin:0 auto;}
|
| 533 |
+
}
|
| 534 |
+
</style>"""
|
| 535 |
+
|
| 536 |
+
def make_article_html(self, article: Dict) -> str:
|
| 537 |
+
parts = []
|
| 538 |
+
parts.append(self._article_css())
|
| 539 |
+
|
| 540 |
+
# โโ 0. Article Title โโ
|
| 541 |
+
title = article.get("title", "").strip()
|
| 542 |
+
if title:
|
| 543 |
+
parts.append(f'<h1 class="article-title">{title}</h1>')
|
| 544 |
+
|
| 545 |
+
# โโ 1. Featured Image โโ
|
| 546 |
+
parts.append(self._make_featured_image(article))
|
| 547 |
+
|
| 548 |
+
# โโ 2. Summary Box โโ
|
| 549 |
+
summary = article.get("summary", "")
|
| 550 |
+
if summary:
|
| 551 |
+
parts.append(self._make_summary_box(summary))
|
| 552 |
+
|
| 553 |
+
# โโ 3. Introduction โโ
|
| 554 |
+
intro = article.get("introduction", "")
|
| 555 |
+
if intro:
|
| 556 |
+
parts.append(f'<div class="sec-card"><h2 id="intro">ุงูู
ูุฏู
ุฉ</h2><p>{intro}</p></div>')
|
| 557 |
+
|
| 558 |
+
# โโ 4. Table of Contents (single index, right after introduction) โโ
|
| 559 |
+
body = article.get("body", "")
|
| 560 |
+
toc, processed_body = self._make_toc(body)
|
| 561 |
+
if toc:
|
| 562 |
+
parts.append(toc)
|
| 563 |
+
|
| 564 |
+
# โโ 5. Full Article Body (apply duplicates stripped, sections as cards) โโ
|
| 565 |
+
body_to_process = processed_body if processed_body is not None else body
|
| 566 |
+
body_to_process = self._enhance_body_tables(body_to_process)
|
| 567 |
+
body_to_process = self._inject_apply_into_body(article, body_to_process)
|
| 568 |
+
body_to_process = self._wrap_sections(body_to_process)
|
| 569 |
+
if body_to_process:
|
| 570 |
+
parts.append(body_to_process)
|
| 571 |
+
|
| 572 |
+
# โโ 5.5 Contact box (real extracted data only, single yellow box) โโ
|
| 573 |
+
extracted = article.get("extracted", {}) or {}
|
| 574 |
+
email = str(extracted.get("email") or "").strip()
|
| 575 |
+
phone = str(extracted.get("phone") or "").strip()
|
| 576 |
+
apply_url = str(extracted.get("apply_url") or "").strip()
|
| 577 |
+
if apply_url and re.search(r'^https?://(?:t\.me|telegram\.me|tlgrm\.me)/|^@', apply_url, re.IGNORECASE):
|
| 578 |
+
apply_url = ""
|
| 579 |
+
if email or phone or apply_url:
|
| 580 |
+
parts.append(self._make_apply_section_html(email, phone, apply_url))
|
| 581 |
+
|
| 582 |
+
# โโ 6. Important Notes โโ
|
| 583 |
+
notes = article.get("notes", [])
|
| 584 |
+
if notes:
|
| 585 |
+
parts.append(self._make_notes_box(notes))
|
| 586 |
+
|
| 587 |
+
# โโ 7. FAQ โโ
|
| 588 |
+
faq = article.get("faq", [])
|
| 589 |
+
if faq:
|
| 590 |
+
parts.append(self._make_faq(faq))
|
| 591 |
+
|
| 592 |
+
# โโ 8. Conclusion (professional end card) โโ
|
| 593 |
+
conclusion = article.get("conclusion", "")
|
| 594 |
+
if conclusion:
|
| 595 |
+
parts.append(self._make_conclusion_box(conclusion))
|
| 596 |
+
|
| 597 |
+
# โโ 8.5 Telegram channel CTA (right before hashtags) โโ
|
| 598 |
+
parts.append(self._make_telegram_section())
|
| 599 |
+
|
| 600 |
+
# โโ 9. Hashtags โโ
|
| 601 |
+
hashtags = article.get("hashtags", [])
|
| 602 |
+
logger.info(f"Hashtags Before HTML: {hashtags}")
|
| 603 |
+
if hashtags:
|
| 604 |
+
parts.append(self._make_hashtags_section(hashtags))
|
| 605 |
+
|
| 606 |
+
# โโ 10. Keywords โโ
|
| 607 |
+
keywords = article.get("keywords", "")
|
| 608 |
+
if keywords:
|
| 609 |
+
parts.append(self._make_keywords_section(keywords))
|
| 610 |
+
|
| 611 |
+
# โโ 12. Schema JSON-LD โโ
|
| 612 |
+
schema = self._make_schema(article)
|
| 613 |
+
if schema:
|
| 614 |
+
parts.append(schema)
|
| 615 |
+
|
| 616 |
+
return '<div class="blog-article">\n' + "\n".join(parts) + '\n</div>'
|
| 617 |
+
|
| 618 |
+
def _enhance_body_tables(self, body: str) -> str:
|
| 619 |
+
if not body:
|
| 620 |
+
return body
|
| 621 |
+
def _replace(m):
|
| 622 |
+
tag = m.group(0)
|
| 623 |
+
if "class=" not in tag:
|
| 624 |
+
return '<table class="job-table">'
|
| 625 |
+
return tag
|
| 626 |
+
return re.sub(r'<table[^>]*>', _replace, body)
|
| 627 |
+
|
| 628 |
+
def _wrap_sections(self, body: str) -> str:
|
| 629 |
+
"""Wrap each h2 section of the body into a styled card (presentation only)."""
|
| 630 |
+
if not body or "<h2" not in body:
|
| 631 |
+
return body
|
| 632 |
+
pieces = re.split(r'(?=<h2[^>]*>)', body)
|
| 633 |
+
head = pieces[0]
|
| 634 |
+
cards = []
|
| 635 |
+
for piece in pieces[1:]:
|
| 636 |
+
m = re.match(r'<h2([^>]*)>(.*?)</h2>(.*)$', piece, re.DOTALL)
|
| 637 |
+
if not m:
|
| 638 |
+
cards.append(piece)
|
| 639 |
+
continue
|
| 640 |
+
attrs, text, rest = m.group(1), m.group(2), m.group(3)
|
| 641 |
+
icon = SECTION_ICONS.get(next((k for k in SECTION_ICONS if k in text), ""), "๐")
|
| 642 |
+
if 'class="' in attrs:
|
| 643 |
+
attrs = re.sub(r'class="([^"]*)"', r'class="sec-title \1"', attrs, count=1)
|
| 644 |
+
else:
|
| 645 |
+
attrs += ' class="sec-title"'
|
| 646 |
+
cards.append(f'<div class="sec-card"><h2{attrs}>{icon} {text}</h2>{rest}</div>')
|
| 647 |
+
return head + "".join(cards)
|
| 648 |
+
|
| 649 |
+
def _make_conclusion_box(self, conclusion: str) -> str:
|
| 650 |
+
return f'<div class="article-end"><p>๐ข {conclusion}</p></div>'
|
| 651 |
+
|
| 652 |
+
def _make_featured_image(self, article: Dict) -> str:
|
| 653 |
+
alt_text = article.get("media_alt", {}).get("alt", "")
|
| 654 |
+
caption = article.get("media_alt", {}).get("caption", "")
|
| 655 |
+
img_src = None
|
| 656 |
+
if self.config:
|
| 657 |
+
img_src = self.config.get("default_jobs_image", "")
|
| 658 |
+
if not img_src:
|
| 659 |
+
return ""
|
| 660 |
+
alt = alt_text or "ุตูุฑุฉ ุงูู
ูุงู"
|
| 661 |
+
title = article.get("title", "")[:60]
|
| 662 |
+
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>'
|
| 663 |
+
if caption:
|
| 664 |
+
img += f'<p style="text-align:center;font-size:13px;color:#666;margin-top:-10px;">{caption}</p>'
|
| 665 |
+
return img
|
| 666 |
+
|
| 667 |
+
def _make_summary_box(self, summary: str) -> str:
|
| 668 |
+
return f'<div class="summary-box"><div class="sec-head sum-head">๐ ู
ูุฎุต ุงูู
ูุงู</div><p>{summary}</p></div>'
|
| 669 |
+
|
| 670 |
+
def _make_toc(self, body: str) -> tuple:
|
| 671 |
+
if not body:
|
| 672 |
+
return "", body
|
| 673 |
+
headings = re.findall(r'<h([23])[^>]*>(.*?)</h\1>', body, re.DOTALL)
|
| 674 |
+
items = []
|
| 675 |
+
processed = body
|
| 676 |
+
idx = 0
|
| 677 |
+
for level, text in headings:
|
| 678 |
+
if re.search(r'ุงูุชููู|navigation', text, re.IGNORECASE):
|
| 679 |
+
processed = re.sub(
|
| 680 |
+
rf'<h{level}[^>]*>{re.escape(text)}</h{level}>.*?(?=<h[23][^>]*>|$)',
|
| 681 |
+
'', processed, count=1, flags=re.DOTALL
|
| 682 |
+
)
|
| 683 |
+
continue
|
| 684 |
+
anchor = f"sec-{idx}"
|
| 685 |
+
icon = SECTION_ICONS.get(next((k for k in SECTION_ICONS if k in text), ""), "๐")
|
| 686 |
+
items.append(f'<li><a href="#{anchor}">{icon} {text}</a></li>')
|
| 687 |
+
processed = processed.replace(
|
| 688 |
+
f'<h{level}>{text}</h{level}>',
|
| 689 |
+
f'<h{level} id="{anchor}">{text}</h{level}>', 1
|
| 690 |
+
)
|
| 691 |
+
idx += 1
|
| 692 |
+
if len(items) < 2:
|
| 693 |
+
return "", processed
|
| 694 |
+
toc = f'<div class="toc-box"><div class="sec-head toc-head">๐ ุงูู
ุญุชููุงุช</div><ul>{"".join(items)}</ul></div>'
|
| 695 |
+
return toc, processed
|
| 696 |
+
|
| 697 |
+
@staticmethod
|
| 698 |
+
def _is_iraqi_phone(clean_phone: str) -> bool:
|
| 699 |
+
digits = re.sub(r'[^\d]', '', clean_phone)
|
| 700 |
+
return digits.startswith("07") or digits.startswith("9647")
|
| 701 |
+
|
| 702 |
+
@staticmethod
|
| 703 |
+
def _to_whatsapp(clean_phone: str) -> str:
|
| 704 |
+
digits = re.sub(r'[^\d]', '', clean_phone)
|
| 705 |
+
if digits.startswith("964"):
|
| 706 |
+
return digits
|
| 707 |
+
if digits.startswith("0"):
|
| 708 |
+
return "964" + digits[1:]
|
| 709 |
+
return "964" + digits
|
| 710 |
+
|
| 711 |
+
def _make_apply_section_html(self, email: str, phone: str, apply_url: str) -> str:
|
| 712 |
+
logger.info("Apply Builder Called")
|
| 713 |
+
rows = ""
|
| 714 |
+
actions = ""
|
| 715 |
+
if phone:
|
| 716 |
+
clean_phone = re.sub(r'[^\d+]', '', phone)
|
| 717 |
+
rows += (f'<div class="apply-row"><span class="apply-row-label">๐ ุฑูู
ุงููุงุชู</span>'
|
| 718 |
+
f'<a class="apply-box-value" href="tel:{clean_phone}">{phone}</a></div>')
|
| 719 |
+
actions += f'<a class="apply-btn apply-btn-call" href="tel:{clean_phone}">๐ ุงุชุตุงู</a>'
|
| 720 |
+
if self._is_iraqi_phone(clean_phone):
|
| 721 |
+
wa = self._to_whatsapp(clean_phone)
|
| 722 |
+
actions += f'<a class="apply-btn apply-btn-whatsapp" href="https://wa.me/{wa}" target="_blank" rel="noopener">๐ฌ ูุงุชุณุงุจ</a>'
|
| 723 |
+
if email:
|
| 724 |
+
rows += (f'<div class="apply-row"><span class="apply-row-label">โ๏ธ ุงูุจุฑูุฏ ุงูุฅููุชุฑููู</span>'
|
| 725 |
+
f'<a class="apply-box-value" href="mailto:{email}">{email}</a></div>')
|
| 726 |
+
actions += f'<a class="apply-btn apply-btn-cv" href="mailto:{email}">๐ง ุฅุฑุณุงู CV</a>'
|
| 727 |
+
if apply_url:
|
| 728 |
+
rows += (f'<div class="apply-row"><span class="apply-row-label">๐ ุฑุงุจุท ุงูุชูุฏูู
</span>'
|
| 729 |
+
f'<a class="apply-box-value" href="{apply_url}" target="_blank" rel="noopener">{apply_url}</a></div>')
|
| 730 |
+
actions += f'<a class="apply-btn apply-btn-now" href="{apply_url}" target="_blank" rel="noopener">ุงูุชูุฏูู
</a>'
|
| 731 |
+
if not rows:
|
| 732 |
+
return ""
|
| 733 |
+
return (f'<div class="apply-section">'
|
| 734 |
+
f'<div class="apply-box">'
|
| 735 |
+
f'<div class="apply-box-title">๐ ู
ุนููู
ุงุช ุงูุชูุงุตู</div>'
|
| 736 |
+
f'{rows}'
|
| 737 |
+
f'<div class="apply-box-actions">{actions}</div>'
|
| 738 |
+
f'</div>'
|
| 739 |
+
f'</div>')
|
| 740 |
+
|
| 741 |
+
def _inject_apply_into_body(self, article: Dict, body: str) -> str:
|
| 742 |
+
"""Remove any AI-authored apply section from the body so the contact
|
| 743 |
+
details appear only once, inside the dedicated contact box."""
|
| 744 |
+
if not body:
|
| 745 |
+
return body
|
| 746 |
+
extracted = article.get("extracted", {}) or {}
|
| 747 |
+
email = str(extracted.get("email") or "").strip()
|
| 748 |
+
phone = str(extracted.get("phone") or "").strip()
|
| 749 |
+
apply_url = str(extracted.get("apply_url") or "").strip()
|
| 750 |
+
if apply_url and re.search(r'^https?://(?:t\.me|telegram\.me|tlgrm\.me)/|^@', apply_url, re.IGNORECASE):
|
| 751 |
+
apply_url = ""
|
| 752 |
+
if not (email or phone or apply_url):
|
| 753 |
+
return body
|
| 754 |
+
|
| 755 |
+
patterns = [
|
| 756 |
+
r'<h[23][^>]*>(?:ุขููุฉ ุงูุชูุฏูู
ูุงูุชูุงุตู|ุทุฑููุฉ ุงูุชูุฏูู
ูุงูุชูุงุตู|ุทุฑููุฉ ุงูุชูุฏูู
ุนูู ุงููุธููุฉ|ุทุฑููุฉ ุงูุชูุฏูู
|ููููุฉ ุงูุชูุฏูู
|ุงูุชูุฏูู
ุนูู ุงููุธููุฉ|ุดุฑูุท ุงูุชูุฏูู
|ุงูุชูุฏูู
)</h[23]>',
|
| 757 |
+
]
|
| 758 |
+
for pattern in patterns:
|
| 759 |
+
body = re.sub(
|
| 760 |
+
pattern + r'.*?(?=<h[23][^>]*>|$)',
|
| 761 |
+
'', body, count=1, flags=re.DOTALL | re.IGNORECASE
|
| 762 |
+
)
|
| 763 |
+
return body
|
| 764 |
+
|
| 765 |
+
def _make_notes_box(self, notes: list) -> str:
|
| 766 |
+
lis = "".join(f"<li>{n}</li>" for n in notes)
|
| 767 |
+
return f'<div class="notes-box"><div class="sec-head notes-head">โ ๏ธ ู
ูุงุญุธุงุช ู
ูู
ุฉ</div><ul class="notes-list">{lis}</ul></div>'
|
| 768 |
+
|
| 769 |
+
def _make_faq(self, faq: list) -> str:
|
| 770 |
+
items = ""
|
| 771 |
+
for item in faq:
|
| 772 |
+
q = item.get("question", "")
|
| 773 |
+
a = item.get("answer", "")
|
| 774 |
+
if q and a:
|
| 775 |
+
items += f'<h3 itemscope itemprop="mainEntity" itemtype="https://schema.org/Question" class="faq-q">{q}</h3><div itemprop="acceptedAnswer" itemscope itemtype="https://schema.org/Answer" class="faq-a"><p itemprop="text">{a}</p></div>'
|
| 776 |
+
if not items:
|
| 777 |
+
return ""
|
| 778 |
+
return f'<div class="faq-card"><h2 class="faq-h">ุงูุฃุณุฆูุฉ ุงูุดุงุฆุนุฉ</h2><div itemscope itemtype="https://schema.org/FAQPage">{items}</div></div>'
|
| 779 |
+
|
| 780 |
+
def _make_telegram_section(self) -> str:
|
| 781 |
+
return (f'<div class="tg-card">'
|
| 782 |
+
f'<div class="tg-card-h">๐ข ููู
ุฒูุฏ ู
ู ุงููุธุงุฆู</div>'
|
| 783 |
+
f'<p class="tg-card-p">ููู
ุฒูุฏ ู
ู ุงููุธุงุฆู ููุฑุต ุงูุนู
ูุ ุชุงุจุน ููุงุฉ ุงููุธุงุฆู ุนูู ุชูููุฌุฑุงู
.</p>'
|
| 784 |
+
f'<a class="tg-card-btn" href="https://t.me/CastleJobiq" target="_blank" rel="noopener">๐ต ุงุดุชุฑู ูู ููุงุฉ ุงููุธุงุฆู ุนูู ุชูููุฌุฑุงู
</a>'
|
| 785 |
+
f'</div>')
|
| 786 |
+
|
| 787 |
+
def _make_keywords_section(self, keywords: str) -> str:
|
| 788 |
+
parts = re.split(r'[ุ,\n]+', keywords)
|
| 789 |
+
tags = []
|
| 790 |
+
for p in parts:
|
| 791 |
+
t = p.strip()
|
| 792 |
+
if t:
|
| 793 |
+
tags.append(f'<span class="kw-chip">{t}</span>')
|
| 794 |
+
if not tags:
|
| 795 |
+
return ""
|
| 796 |
+
return f'<div class="keywords-box"><div class="sec-head kw-head">๐ท๏ธ ุงูููู
ุงุช ุงูุฏูุงููุฉ</div><div class="kw-wrap">{"".join(tags)}</div></div>'
|
| 797 |
+
|
| 798 |
+
def _make_hashtags_section(self, hashtags: List[str]) -> str:
|
| 799 |
+
tags_items = []
|
| 800 |
+
for tag in hashtags:
|
| 801 |
+
t = tag.strip()
|
| 802 |
+
if t and not t.startswith("#"):
|
| 803 |
+
t = "#" + t
|
| 804 |
+
if t:
|
| 805 |
+
tags_items.append(f'<span class="ht-chip">{t}</span>')
|
| 806 |
+
items = "".join(tags_items)
|
| 807 |
+
return f'<div class="hashtag-box"><div class="sec-head has-head">๐ท๏ธ ุงููุงุดุชุงูุงุช</div><div class="ht-wrap">{items}</div></div>'
|
| 808 |
+
|
| 809 |
+
def _make_schema(self, article: Dict) -> str:
|
| 810 |
+
title = article.get("title", "")
|
| 811 |
+
intro = article.get("introduction", "")
|
| 812 |
+
body = article.get("body", "")
|
| 813 |
+
apply_pattern = r'<h[23][^>]*>(?:ุขููุฉ ุงูุชูุฏูู
ูุงูุชูุงุตู|ุทุฑููุฉ ุงูุชูุฏูู
ูุงูุชูุงุตู|ุทุฑููุฉ ุงูุชูุฏูู
ุนูู ุงููุธููุฉ|ุทุฑููุฉ ุงูุชูุฏูู
|ููููุฉ ุงูุชูุฏูู
|ุงูุชูุฏูู
ุนูู ุงููุธููุฉ)</h[23]>.*?(?=<h[23]|$)'
|
| 814 |
+
body = re.sub(apply_pattern, '', body, flags=re.DOTALL | re.IGNORECASE)
|
| 815 |
+
nav_pattern = r'<h[23][^>]*>[^<]*(?:ุงูุชููู|navigation)[^<]*</h[23]>.*?(?=<h[23]|$)'
|
| 816 |
+
body = re.sub(nav_pattern, '', body, flags=re.DOTALL | re.IGNORECASE)
|
| 817 |
+
text = re.sub(r'<[^>]+>', '', f"{intro} {body}")[:300]
|
| 818 |
+
section = article.get("section", "")
|
| 819 |
+
is_news = section not in ("jobs", "ูุธุงุฆู")
|
| 820 |
+
schema = {
|
| 821 |
+
"@context": "https://schema.org",
|
| 822 |
+
"@type": "NewsArticle" if is_news else "Article",
|
| 823 |
+
"headline": title,
|
| 824 |
+
"description": text[:160],
|
| 825 |
+
"articleBody": text,
|
| 826 |
+
"inLanguage": "ar",
|
| 827 |
+
"author": {"@type": "Organization", "name": "ุงูู
ุฏููุฉ"},
|
| 828 |
+
"publisher": {"@type": "Organization", "name": "ุงูู
ุฏููุฉ"},
|
| 829 |
+
"datePublished": article.get("created_at", ""),
|
| 830 |
+
"dateModified": article.get("processed_at", ""),
|
| 831 |
+
}
|
| 832 |
+
schema_str = json.dumps(schema, ensure_ascii=False)
|
| 833 |
+
return f'<script type="application/ld+json">{schema_str}</script>'
|
| 834 |
+
|
| 835 |
+
def make_preview_data(self, article: Dict) -> Tuple[Optional[str], str]:
|
| 836 |
+
html = self.make_article_html(article)
|
| 837 |
+
image = None
|
| 838 |
+
media = article.get("media", [])
|
| 839 |
+
for m in media:
|
| 840 |
+
if m.get("type") == "photo":
|
| 841 |
+
image = m.get("file_id")
|
| 842 |
+
break
|
| 843 |
+
if not image and self.config:
|
| 844 |
+
section = article.get("section", "")
|
| 845 |
+
if section in ("jobs", "ูุธุงุฆู", "general"):
|
| 846 |
+
image = self.config.get("default_jobs_image", "")
|
| 847 |
+
telegram_text = self.html_to_telegram(html)
|
| 848 |
+
title = article.get("title", "")
|
| 849 |
+
if title:
|
| 850 |
+
telegram_text = f"<b>{title}</b>\n\n{telegram_text}"
|
| 851 |
+
reading_time = article.get("reading_time", 0)
|
| 852 |
+
if reading_time:
|
| 853 |
+
telegram_text += f"\nโฑ๏ธ ู
ุฏุฉ ุงููุฑุงุกุฉ: {reading_time} ุฏูููุฉ"
|
| 854 |
+
labels = article.get("labels", [])
|
| 855 |
+
if labels:
|
| 856 |
+
telegram_text += f"\n๐ท {', '.join(labels)}"
|
| 857 |
+
return image, telegram_text
|
| 858 |
+
|
| 859 |
+
@staticmethod
|
| 860 |
+
def html_to_telegram(html: str) -> str:
|
| 861 |
+
html = re.sub(r'<!DOCTYPE[^>]*>', '', html, flags=re.DOTALL | re.IGNORECASE)
|
| 862 |
+
html = re.sub(r'<!--.*?-->', '', html, flags=re.DOTALL)
|
| 863 |
+
html = re.sub(r'<(script|style|noscript)[^>]*>.*?</\1>', '', html, flags=re.DOTALL | re.IGNORECASE)
|
| 864 |
+
html = re.sub(r'<head[^>]*>.*?</head>', '', html, flags=re.DOTALL | re.IGNORECASE)
|
| 865 |
+
|
| 866 |
+
def _replace_table(m):
|
| 867 |
+
rows = re.findall(r'<tr>(.*?)</tr>', m.group(1), re.DOTALL)
|
| 868 |
+
lines = []
|
| 869 |
+
for row in rows:
|
| 870 |
+
cells = re.findall(r'<t[hd][^>]*>(.*?)</t[hd]>', row, re.DOTALL)
|
| 871 |
+
if cells:
|
| 872 |
+
lines.append(' | '.join(cells))
|
| 873 |
+
return '\n'.join(lines) + '\n'
|
| 874 |
+
html = re.sub(r'<table[^>]*>(.*?)</table>', _replace_table, html, flags=re.DOTALL)
|
| 875 |
+
html = re.sub(r'<img[^>]*>', '', html)
|
| 876 |
+
html = re.sub(r'<h([23])[^>]*>(.*?)</h\1>', r'<b>\2</b>', html, flags=re.DOTALL)
|
| 877 |
+
html = re.sub(r'<li>(.*?)</li>', r'โข \1', html, flags=re.DOTALL)
|
| 878 |
+
html = re.sub(r'</?u?[ol][^>]*>', '', html)
|
| 879 |
+
html = re.sub(r'<details[^>]*>', '', html)
|
| 880 |
+
html = re.sub(r'</details>', '', html)
|
| 881 |
+
html = re.sub(r'<summary[^>]*>(.*?)</summary>', r'<b>\1</b>\n', html, flags=re.DOTALL)
|
| 882 |
+
html = re.sub(r'</?div[^>]*>', '', html)
|
| 883 |
+
html = re.sub(r'</?span[^>]*>', '', html)
|
| 884 |
+
html = re.sub(r'<p>(.*?)</p>', r'\1\n', html, flags=re.DOTALL)
|
| 885 |
+
html = re.sub(r'<br\s*/?>', '\n', html)
|
| 886 |
+
html = re.sub(r'<strong>(.*?)</strong>', r'<b>\1</b>', html)
|
| 887 |
+
html = re.sub(r'<em>(.*?)</em>', r'<i>\1</i>', html)
|
| 888 |
+
html = re.sub(r'</?t[rdh][^>]*>', '', html)
|
| 889 |
+
|
| 890 |
+
def _clean_allowed_attrs(m):
|
| 891 |
+
tag = m.group(1).lower()
|
| 892 |
+
if tag == 'a':
|
| 893 |
+
href = re.search(r'href="([^"]+)"', m.group(0))
|
| 894 |
+
return f'<a href="{href.group(1)}">' if href else '<a>'
|
| 895 |
+
return f'<{tag}>'
|
| 896 |
+
html = re.sub(r'<(a|b|i|u|s|em|strong|code|pre)\b[^>]*>', _clean_allowed_attrs, html, flags=re.IGNORECASE)
|
| 897 |
+
allowed = {'b', 'i', 'u', 's', 'a', 'code', 'pre', 'em', 'strong'}
|
| 898 |
+
html = re.sub(r'<(?!/?(' + '|'.join(allowed) + r')(?:\s[^>]*)?>)[a-z]+[^>]*>', '', html, flags=re.IGNORECASE)
|
| 899 |
+
html = re.sub(r'</(?!(' + '|'.join(allowed) + r')\b)[a-z]+>', '', html, flags=re.IGNORECASE)
|
| 900 |
+
html = re.sub(r'\n{3,}', '\n\n', html)
|
| 901 |
+
return html.strip()
|