Alialdlfy1 commited on
Commit
3cee0f0
·
verified ·
1 Parent(s): a9f973e

Upload processor.py

Browse files
Files changed (1) hide show
  1. modules/blogger/processor.py +915 -0
modules/blogger/processor.py ADDED
@@ -0,0 +1,915 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-intro{background:#fff9e6;border:1px solid #f5dd9c;border-radius:12px;padding:14px 18px;color:#5a4a10;line-height:1.9;font-size:15px;text-align:right;margin:0 0 16px 0;}
502
+ .apply-box{display:block;margin:14px auto;max-width:480px;border-radius:14px;padding:16px 22px;border:1px solid;text-align:center;box-shadow:0 3px 10px rgba(120,90,0,.10);}
503
+ .apply-box-phone{background:linear-gradient(135deg,#fffbe6,#fff3a8);border-color:#f2d47c;}
504
+ .apply-box-mail{background:#fffdf2;border-color:#f2e17c;}
505
+ .apply-box-link{background:#fffdf2;border-color:#f2e17c;}
506
+ .apply-box-label{font-weight:bold;font-size:14px;display:block;margin-bottom:8px;color:#7a5c00;}
507
+ .apply-box-phone .apply-box-label{color:#6b5300;}
508
+ .apply-box-value{font-size:24px;font-weight:bold;color:#8a5a00;direction:ltr;display:inline-block;word-break:break-all;text-decoration:none!important;}
509
+ .apply-box-value:hover{text-decoration:underline!important;}
510
+ .apply-box-phone .apply-box-value{color:#5a4400;font-size:30px;letter-spacing:1px;}
511
+ .apply-box-actions{margin-top:12px;}
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
+ @media (max-width:768px){
519
+ .blog-article{font-size:15px;}
520
+ .sec-card{padding:14px 14px;margin:12px 0;}
521
+ .apply-btn{padding:9px 20px;}
522
+ }
523
+ @media (max-width:600px){
524
+ .blog-article{font-size:14px;}
525
+ table,.job-table{font-size:13px;}
526
+ table th,table td,.job-table th,.job-table td{padding:8px 10px;}
527
+ .apply-box{width:92%;padding:14px 14px;}
528
+ .apply-box-value{font-size:17px;}
529
+ .apply-box-phone .apply-box-value{font-size:22px;}
530
+ .apply-btn{display:block;margin:6px auto;width:70%;}
531
+ .tg-card-btn{display:block;width:80%;margin:0 auto;}
532
+ }
533
+ </style>"""
534
+
535
+ def make_article_html(self, article: Dict) -> str:
536
+ parts = []
537
+ parts.append(self._article_css())
538
+
539
+ # ── 1. Featured Image ──
540
+ parts.append(self._make_featured_image(article))
541
+
542
+ # ── 2. Summary Box ──
543
+ summary = article.get("summary", "")
544
+ if summary:
545
+ parts.append(self._make_summary_box(summary))
546
+
547
+ # ── 3. Introduction ──
548
+ intro = article.get("introduction", "")
549
+ if intro:
550
+ parts.append(f'<div class="sec-card"><h2 id="intro">المقدمة</h2><p>{intro}</p></div>')
551
+
552
+ # ── 4. Table of Contents (single index, right after introduction) ──
553
+ body = article.get("body", "")
554
+ toc, processed_body = self._make_toc(body)
555
+ if toc:
556
+ parts.append(toc)
557
+
558
+ # ── 5. Full Article Body (with apply contacts injected) ──
559
+ body_to_process = processed_body or body
560
+ body_to_process = self._enhance_body_tables(body_to_process)
561
+ body_to_process = self._inject_apply_into_body(article, body_to_process)
562
+ body_to_process = self._wrap_sections(body_to_process)
563
+ if body_to_process:
564
+ parts.append(body_to_process)
565
+
566
+ # ── 6. Important Notes ──
567
+ notes = article.get("notes", [])
568
+ if notes:
569
+ parts.append(self._make_notes_box(notes))
570
+
571
+ # ── 7. FAQ ──
572
+ faq = article.get("faq", [])
573
+ if faq:
574
+ parts.append(self._make_faq(faq))
575
+
576
+ # ── 8. Conclusion (professional end card) ──
577
+ conclusion = article.get("conclusion", "")
578
+ if conclusion:
579
+ parts.append(self._make_conclusion_box(conclusion))
580
+
581
+ # ── 8.5 Telegram channel CTA (reads channel identity from source, never hardcoded) ──
582
+ source = article.get("source", {})
583
+ if source:
584
+ parts.append(self._make_telegram_section(source))
585
+
586
+ # ── 9. Hashtags ──
587
+ hashtags = article.get("hashtags", [])
588
+ logger.info(f"Hashtags Before HTML: {hashtags}")
589
+ if hashtags:
590
+ parts.append(self._make_hashtags_section(hashtags))
591
+
592
+ # ── 10. Keywords ──
593
+ keywords = article.get("keywords", "")
594
+ if keywords:
595
+ parts.append(self._make_keywords_section(keywords))
596
+
597
+ # ── 12. Schema JSON-LD ──
598
+ schema = self._make_schema(article)
599
+ if schema:
600
+ parts.append(schema)
601
+
602
+ return '<div class="blog-article">\n' + "\n".join(parts) + '\n</div>'
603
+
604
+ def _enhance_body_tables(self, body: str) -> str:
605
+ if not body:
606
+ return body
607
+ def _replace(m):
608
+ tag = m.group(0)
609
+ if "class=" not in tag:
610
+ return '<table class="job-table">'
611
+ return tag
612
+ return re.sub(r'<table[^>]*>', _replace, body)
613
+
614
+ def _wrap_sections(self, body: str) -> str:
615
+ """Wrap each h2 section of the body into a styled card (presentation only)."""
616
+ if not body or "<h2" not in body:
617
+ return body
618
+ pieces = re.split(r'(?=<h2[^>]*>)', body)
619
+ head = pieces[0]
620
+ cards = []
621
+ for piece in pieces[1:]:
622
+ m = re.match(r'<h2([^>]*)>(.*?)</h2>(.*)$', piece, re.DOTALL)
623
+ if not m:
624
+ cards.append(piece)
625
+ continue
626
+ attrs, text, rest = m.group(1), m.group(2), m.group(3)
627
+ icon = SECTION_ICONS.get(next((k for k in SECTION_ICONS if k in text), ""), "📌")
628
+ if 'class="' in attrs:
629
+ attrs = re.sub(r'class="([^"]*)"', r'class="sec-title \1"', attrs, count=1)
630
+ else:
631
+ attrs += ' class="sec-title"'
632
+ cards.append(f'<div class="sec-card"><h2{attrs}>{icon} {text}</h2>{rest}</div>')
633
+ return head + "".join(cards)
634
+
635
+ def _make_conclusion_box(self, conclusion: str) -> str:
636
+ return f'<div class="article-end"><p>📢 {conclusion}</p></div>'
637
+
638
+ def _make_featured_image(self, article: Dict) -> str:
639
+ alt_text = article.get("media_alt", {}).get("alt", "")
640
+ caption = article.get("media_alt", {}).get("caption", "")
641
+ img_src = None
642
+ if self.config:
643
+ img_src = self.config.get("default_jobs_image", "")
644
+ if not img_src:
645
+ return ""
646
+ alt = alt_text or "صورة المقال"
647
+ title = article.get("title", "")[:60]
648
+ 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>'
649
+ if caption:
650
+ img += f'<p style="text-align:center;font-size:13px;color:#666;margin-top:-10px;">{caption}</p>'
651
+ return img
652
+
653
+ def _make_summary_box(self, summary: str) -> str:
654
+ return f'<div class="summary-box"><div class="sec-head sum-head">📌 ملخص المقال</div><p>{summary}</p></div>'
655
+
656
+ def _make_toc(self, body: str) -> tuple:
657
+ if not body:
658
+ return "", body
659
+ headings = re.findall(r'<h([23])[^>]*>(.*?)</h\1>', body, re.DOTALL)
660
+ if len(headings) < 2:
661
+ return "", body
662
+ items = []
663
+ processed = body
664
+ idx = 0
665
+ for level, text in headings:
666
+ if "التنقل" in text:
667
+ processed = re.sub(
668
+ rf'<h{level}[^>]*>{re.escape(text)}</h{level}>.*?(?=<h[23][^>]*>|$)',
669
+ '', processed, count=1, flags=re.DOTALL
670
+ )
671
+ continue
672
+ anchor = f"sec-{idx}"
673
+ icon = SECTION_ICONS.get(next((k for k in SECTION_ICONS if k in text), ""), "📌")
674
+ items.append(f'<li><a href="#{anchor}">{icon} {text}</a></li>')
675
+ processed = processed.replace(
676
+ f'<h{level}>{text}</h{level}>',
677
+ f'<h{level} id="{anchor}">{text}</h{level}>', 1
678
+ )
679
+ idx += 1
680
+ if len(items) < 2:
681
+ return "", processed
682
+ toc = f'<div class="toc-box"><div class="sec-head toc-head">📑 المحتويات</div><ul>{"".join(items)}</ul></div>'
683
+ return toc, processed
684
+
685
+ @staticmethod
686
+ def _is_iraqi_phone(clean_phone: str) -> bool:
687
+ digits = re.sub(r'[^\d]', '', clean_phone)
688
+ return digits.startswith("07") or digits.startswith("9647")
689
+
690
+ @staticmethod
691
+ def _to_whatsapp(clean_phone: str) -> str:
692
+ digits = re.sub(r'[^\d]', '', clean_phone)
693
+ if digits.startswith("964"):
694
+ return digits
695
+ if digits.startswith("0"):
696
+ return "964" + digits[1:]
697
+ return "964" + digits
698
+
699
+ def _make_apply_section_html(self, email: str, phone: str, apply_url: str) -> str:
700
+ logger.info("Apply Builder Called")
701
+ blocks = []
702
+ if phone:
703
+ clean_phone = re.sub(r'[^\d+]', '', phone)
704
+ buttons = f'<a class="apply-btn apply-btn-call" href="tel:{clean_phone}">📞 اتصال</a>'
705
+ if self._is_iraqi_phone(clean_phone):
706
+ wa = self._to_whatsapp(clean_phone)
707
+ buttons += f'<a class="apply-btn apply-btn-whatsapp" href="https://wa.me/{wa}" target="_blank" rel="noopener">💬 واتساب</a>'
708
+ blocks.append(
709
+ f'<div class="apply-box apply-box-phone">'
710
+ f'<div class="apply-box-label">📞 رقم الهاتف</div>'
711
+ f'<a class="apply-box-value" href="tel:{clean_phone}">{phone}</a>'
712
+ f'<div class="apply-box-actions">{buttons}</div>'
713
+ f'</div>'
714
+ )
715
+ if email:
716
+ blocks.append(
717
+ f'<div class="apply-box apply-box-mail">'
718
+ f'<div class="apply-box-label">✉️ البريد الإلكتروني</div>'
719
+ f'<a class="apply-box-value" href="mailto:{email}">{email}</a>'
720
+ f'<div class="apply-box-actions">'
721
+ f'<a class="apply-btn apply-btn-cv" href="mailto:{email}">📧 إرسال CV</a>'
722
+ f'</div>'
723
+ f'</div>'
724
+ )
725
+ if apply_url:
726
+ blocks.append(
727
+ f'<div class="apply-box apply-box-link">'
728
+ f'<div class="apply-box-label">🌐 رابط التقديم</div>'
729
+ f'<a class="apply-box-value" href="{apply_url}" target="_blank" rel="noopener">{apply_url}</a>'
730
+ f'<div class="apply-box-actions">'
731
+ f'<a class="apply-btn apply-btn-now" href="{apply_url}" target="_blank" rel="noopener">التقديم</a>'
732
+ f'</div>'
733
+ f'</div>'
734
+ )
735
+ return '<div class="apply-section">' + "".join(blocks) + '</div>'
736
+
737
+ def _inject_apply_into_body(self, article: Dict, body: str) -> str:
738
+ if not body:
739
+ return body
740
+ extracted = article.get("extracted", {}) or {}
741
+ email = str(extracted.get("email") or "").strip()
742
+ phone = str(extracted.get("phone") or "").strip()
743
+ apply_url = str(extracted.get("apply_url") or "").strip()
744
+ if apply_url and re.search(r'^https?://(?:t\.me|telegram\.me|tlgrm\.me)/|^@', apply_url, re.IGNORECASE):
745
+ apply_url = ""
746
+ if not (email or phone or apply_url):
747
+ return body
748
+
749
+ section_html = self._make_apply_section_html(email, phone, apply_url)
750
+ intro = ('<p class="apply-intro">يمكنك التقديم على هذه الفرصة عبر إحدى وسائل التواصل التالية:</p>')
751
+
752
+ main_patterns = [
753
+ r'<h[23][^>]*>(?:آلية التقديم والتواصل|طريقة التقديم والتواصل|طريقة التقديم على الوظيفة|طريقة التقديم|كيفية التقديم|التقديم على الوظيفة)</h[23]>',
754
+ ]
755
+ for pattern in main_patterns:
756
+ match = re.search(pattern, body, re.IGNORECASE)
757
+ if match:
758
+ heading_tag = match.group(0)
759
+ heading_id = re.search(r'id="([^"]+)"', heading_tag)
760
+ anchor = heading_id.group(1) if heading_id else "apply"
761
+ heading_html = f'<h2 id="{anchor}">آلية التقديم والتواصل</h2>'
762
+ rest = body[match.end():]
763
+ next_m = re.search(r'<h[23][^>]*>', rest)
764
+ strip_end = match.end() + (next_m.start() if next_m else len(rest))
765
+ return body[:match.start()] + heading_html + intro + section_html + body[strip_end:]
766
+ fallback = re.search(r'<h[23][^>]*>(?:شروط التقديم|التقديم)</h[23]>', body, re.IGNORECASE)
767
+ if fallback:
768
+ end = fallback.end()
769
+ return body[:end] + intro + section_html + body[end:]
770
+ return body + '<h2 id="apply">آلية التقديم والتواصل</h2>' + intro + section_html
771
+
772
+ def _make_notes_box(self, notes: list) -> str:
773
+ lis = "".join(f"<li>{n}</li>" for n in notes)
774
+ return f'<div class="notes-box"><div class="sec-head notes-head">⚠️ ملاحظات مهمة</div><ul class="notes-list">{lis}</ul></div>'
775
+
776
+ def _make_faq(self, faq: list) -> str:
777
+ items = ""
778
+ for item in faq:
779
+ q = item.get("question", "")
780
+ a = item.get("answer", "")
781
+ if q and a:
782
+ 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>'
783
+ if not items:
784
+ return ""
785
+ return f'<div class="faq-card"><h2 class="faq-h">الأسئلة الشائعة</h2><div itemscope itemtype="https://schema.org/FAQPage">{items}</div></div>'
786
+
787
+ def _make_telegram_section(self, source: dict) -> str:
788
+ username = str(source.get("username") or "").strip()
789
+ link = str(source.get("link") or "").strip()
790
+ target = ""
791
+ if link and re.search(r'https?://(?:t\.me|telegram\.me|tlgrm\.me)/', link, re.IGNORECASE):
792
+ target = link
793
+ elif username and not username.lower().startswith("private"):
794
+ target = "https://t.me/" + username.lstrip("@")
795
+ if not target:
796
+ return ""
797
+ return (f'<div class="tg-card">'
798
+ f'<div class="tg-card-h">📢 للمزيد من الوظائف</div>'
799
+ f'<p class="tg-card-p">وظائف يومية وفرص عمل جديدة تُنشر مباشرة على قناة تيليجرام الرسمية. تابعنا حتى لا تفوتك أي فرصة:</p>'
800
+ f'<a class="tg-card-btn" href="{target}" target="_blank" rel="noopener">🚀 انضم الآن</a>'
801
+ f'</div>')
802
+
803
+ def _make_keywords_section(self, keywords: str) -> str:
804
+ parts = re.split(r'[،,\n]+', keywords)
805
+ tags = []
806
+ for p in parts:
807
+ t = p.strip()
808
+ if t:
809
+ tags.append(f'<span class="kw-chip">{t}</span>')
810
+ if not tags:
811
+ return ""
812
+ return f'<div class="keywords-box"><div class="sec-head kw-head">🏷️ الكلمات الدلالية</div><div class="kw-wrap">{"".join(tags)}</div></div>'
813
+
814
+ def _make_hashtags_section(self, hashtags: List[str]) -> str:
815
+ tags_items = []
816
+ for tag in hashtags:
817
+ t = tag.strip()
818
+ if t and not t.startswith("#"):
819
+ t = "#" + t
820
+ if t:
821
+ tags_items.append(f'<span class="ht-chip">{t}</span>')
822
+ items = "".join(tags_items)
823
+ return f'<div class="hashtag-box"><div class="sec-head has-head">🏷️ الهاشتاكات</div><div class="ht-wrap">{items}</div></div>'
824
+
825
+ def _make_schema(self, article: Dict) -> str:
826
+ title = article.get("title", "")
827
+ intro = article.get("introduction", "")
828
+ body = article.get("body", "")
829
+ apply_pattern = r'<h[23][^>]*>(?:آلية التقديم والتواصل|طريقة التقديم والتواصل|طريقة التقديم على الوظيفة|طريقة التقديم|كيفية التقديم|التقديم على الوظيفة)</h[23]>.*?(?=<h[23]|$)'
830
+ body = re.sub(apply_pattern, '', body, flags=re.DOTALL | re.IGNORECASE)
831
+ text = re.sub(r'<[^>]+>', '', f"{intro} {body}")[:300]
832
+ section = article.get("section", "")
833
+ is_news = section not in ("jobs", "وظائف")
834
+ schema = {
835
+ "@context": "https://schema.org",
836
+ "@type": "NewsArticle" if is_news else "Article",
837
+ "headline": title,
838
+ "description": text[:160],
839
+ "articleBody": text,
840
+ "inLanguage": "ar",
841
+ "author": {"@type": "Organization", "name": "المدونة"},
842
+ "publisher": {"@type": "Organization", "name": "المدونة"},
843
+ "datePublished": article.get("created_at", ""),
844
+ "dateModified": article.get("processed_at", ""),
845
+ }
846
+ schema_str = json.dumps(schema, ensure_ascii=False)
847
+ return f'<script type="application/ld+json">{schema_str}</script>'
848
+
849
+ def make_preview_data(self, article: Dict) -> Tuple[Optional[str], str]:
850
+ html = self.make_article_html(article)
851
+ image = None
852
+ media = article.get("media", [])
853
+ for m in media:
854
+ if m.get("type") == "photo":
855
+ image = m.get("file_id")
856
+ break
857
+ if not image and self.config:
858
+ section = article.get("section", "")
859
+ if section in ("jobs", "وظائف", "general"):
860
+ image = self.config.get("default_jobs_image", "")
861
+ telegram_text = self.html_to_telegram(html)
862
+ title = article.get("title", "")
863
+ if title:
864
+ telegram_text = f"<b>{title}</b>\n\n{telegram_text}"
865
+ reading_time = article.get("reading_time", 0)
866
+ if reading_time:
867
+ telegram_text += f"\n⏱️ مدة القراءة: {reading_time} دقيقة"
868
+ labels = article.get("labels", [])
869
+ if labels:
870
+ telegram_text += f"\n🏷 {', '.join(labels)}"
871
+ return image, telegram_text
872
+
873
+ @staticmethod
874
+ def html_to_telegram(html: str) -> str:
875
+ html = re.sub(r'<!DOCTYPE[^>]*>', '', html, flags=re.DOTALL | re.IGNORECASE)
876
+ html = re.sub(r'<!--.*?-->', '', html, flags=re.DOTALL)
877
+ html = re.sub(r'<(script|style|noscript)[^>]*>.*?</\1>', '', html, flags=re.DOTALL | re.IGNORECASE)
878
+ html = re.sub(r'<head[^>]*>.*?</head>', '', html, flags=re.DOTALL | re.IGNORECASE)
879
+
880
+ def _replace_table(m):
881
+ rows = re.findall(r'<tr>(.*?)</tr>', m.group(1), re.DOTALL)
882
+ lines = []
883
+ for row in rows:
884
+ cells = re.findall(r'<t[hd][^>]*>(.*?)</t[hd]>', row, re.DOTALL)
885
+ if cells:
886
+ lines.append(' | '.join(cells))
887
+ return '\n'.join(lines) + '\n'
888
+ html = re.sub(r'<table[^>]*>(.*?)</table>', _replace_table, html, flags=re.DOTALL)
889
+ html = re.sub(r'<img[^>]*>', '', html)
890
+ html = re.sub(r'<h([23])[^>]*>(.*?)</h\1>', r'<b>\2</b>', html, flags=re.DOTALL)
891
+ html = re.sub(r'<li>(.*?)</li>', r'• \1', html, flags=re.DOTALL)
892
+ html = re.sub(r'</?u?[ol][^>]*>', '', html)
893
+ html = re.sub(r'<details[^>]*>', '', html)
894
+ html = re.sub(r'</details>', '', html)
895
+ html = re.sub(r'<summary[^>]*>(.*?)</summary>', r'<b>\1</b>\n', html, flags=re.DOTALL)
896
+ html = re.sub(r'</?div[^>]*>', '', html)
897
+ html = re.sub(r'</?span[^>]*>', '', html)
898
+ html = re.sub(r'<p>(.*?)</p>', r'\1\n', html, flags=re.DOTALL)
899
+ html = re.sub(r'<br\s*/?>', '\n', html)
900
+ html = re.sub(r'<strong>(.*?)</strong>', r'<b>\1</b>', html)
901
+ html = re.sub(r'<em>(.*?)</em>', r'<i>\1</i>', html)
902
+ html = re.sub(r'</?t[rdh][^>]*>', '', html)
903
+
904
+ def _clean_allowed_attrs(m):
905
+ tag = m.group(1).lower()
906
+ if tag == 'a':
907
+ href = re.search(r'href="([^"]+)"', m.group(0))
908
+ return f'<a href="{href.group(1)}">' if href else '<a>'
909
+ return f'<{tag}>'
910
+ html = re.sub(r'<(a|b|i|u|s|em|strong|code|pre)\b[^>]*>', _clean_allowed_attrs, html, flags=re.IGNORECASE)
911
+ allowed = {'b', 'i', 'u', 's', 'a', 'code', 'pre', 'em', 'strong'}
912
+ html = re.sub(r'<(?!/?(' + '|'.join(allowed) + r')(?:\s[^>]*)?>)[a-z]+[^>]*>', '', html, flags=re.IGNORECASE)
913
+ html = re.sub(r'</(?!(' + '|'.join(allowed) + r')\b)[a-z]+>', '', html, flags=re.IGNORECASE)
914
+ html = re.sub(r'\n{3,}', '\n\n', html)
915
+ return html.strip()