Alialdlfy1 commited on
Commit
d9415a8
·
verified ·
1 Parent(s): ccfcddc

Delete modules/blogger/processor.py

Browse files
Files changed (1) hide show
  1. modules/blogger/processor.py +0 -849
modules/blogger/processor.py DELETED
@@ -1,849 +0,0 @@
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
- make_rewrite_prompt,
19
- make_extract_prompt,
20
- make_seo_prompt,
21
- make_hashtag_prompt,
22
- make_summary_prompt,
23
- make_notes_prompt,
24
- make_keywords_prompt,
25
- )
26
- from modules.blogger.database import BloggerDatabase
27
-
28
- logger = logging.getLogger(__name__)
29
-
30
-
31
- class ArticleProcessor:
32
- def __init__(self, db: BloggerDatabase, ai_client: AIClient, config=None):
33
- self.db = db
34
- self.gemini = ai_client
35
- self.config = config
36
-
37
- MAX_PENDING_ATTEMPTS = 5
38
-
39
- async def process_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None, channel_id: str = "") -> Optional[Dict]:
40
- """Immediate/manual processing path (e.g. UI 'preview now' button).
41
- Attempts Gemini processing right away. NOT used by the automatic channel
42
- polling flow — that flow uses enqueue_raw_post() instead so that message
43
- ingestion never depends on Gemini availability."""
44
- raw_text = raw_text.strip()
45
- if not raw_text:
46
- return None
47
-
48
- fingerprint = self._fingerprint(raw_text, source_url)
49
- if self.db.is_published(fingerprint):
50
- logger.info(f"Article already processed: {fingerprint[:16]}...")
51
- return None
52
-
53
- return await self._process_fresh(raw_text, source_url, media, fingerprint, channel_id)
54
-
55
- def enqueue_raw_post(self, raw_text: str, source_url: str = "", media: List[Dict] = None,
56
- channel_id: str = "", section: str = "") -> Optional[str]:
57
- """Save an incoming raw post straight to the Gemini pending queue, WITHOUT ever
58
- calling Gemini. This is the entry point used by the automatic channel-polling
59
- scheduler, so that ingesting new posts never fails or blocks because of a
60
- Gemini cooldown/quota issue. Returns the fingerprint if newly queued,
61
- None if it's a duplicate or already being handled."""
62
- raw_text = raw_text.strip()
63
- if not raw_text:
64
- return None
65
-
66
- fingerprint = self._fingerprint(raw_text, source_url)
67
- if self.db.is_published(fingerprint):
68
- return None
69
- existing = self.db.get_article(fingerprint)
70
- if existing and existing.get("status") in ("queued", "published", "gemini_pending", "processing"):
71
- return None
72
-
73
- self._save_to_pending(raw_text, source_url, media, fingerprint, channel_id, section)
74
- return fingerprint
75
-
76
- def _save_to_pending(self, raw_text: str, source_url: str, media: List[Dict], fingerprint: str,
77
- channel_id: str = "", section: str = ""):
78
- article = {
79
- "fingerprint": fingerprint,
80
- "source_text": raw_text,
81
- "source_url": source_url,
82
- "media": media or [],
83
- "channel_id": channel_id,
84
- "status": "gemini_pending",
85
- "created_at": int(time.time()),
86
- }
87
- self._save_article(article)
88
- self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
89
-
90
- def _handle_processing_failure(self, fingerprint: str, raw_text: str, source_url: str,
91
- media: List[Dict], channel_id: str, error: Exception,
92
- article: Dict, section: str = ""):
93
- """Called whenever an unexpected error occurs while processing an article
94
- (fresh or from the pending queue). Keeps the article retry-able in the
95
- pending queue instead of losing it, up to MAX_PENDING_ATTEMPTS."""
96
- attempts = self.db.increment_pending_attempts(fingerprint)
97
- if attempts == -1:
98
- # Wasn't in the pending queue yet (e.g. failed during the "fresh" path) — add it.
99
- self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
100
- attempts = self.db.increment_pending_attempts(fingerprint)
101
- if attempts == -1:
102
- attempts = 1
103
- if attempts >= self.MAX_PENDING_ATTEMPTS:
104
- logger.error(
105
- f"Article {fingerprint[:16]} failed {attempts} times, giving up permanently: {error}"
106
- )
107
- article["status"] = "failed_permanent"
108
- article["error"] = str(error)
109
- self._save_article(article)
110
- self.db.remove_pending_by_fingerprint(fingerprint)
111
- else:
112
- logger.warning(
113
- f"Article {fingerprint[:16]} processing failed (attempt {attempts}/{self.MAX_PENDING_ATTEMPTS}), "
114
- f"kept in pending queue for retry: {error}"
115
- )
116
- article["status"] = "gemini_pending"
117
- article["error"] = str(error)
118
- self._save_article(article)
119
-
120
- async def _process_fresh(self, raw_text: str, source_url: str, media: List[Dict], fingerprint: str, channel_id: str = "", section: str = "") -> Optional[Dict]:
121
- article = {
122
- "fingerprint": fingerprint,
123
- "source_text": raw_text,
124
- "source_url": source_url,
125
- "media": media or [],
126
- "channel_id": channel_id,
127
- "status": "processing",
128
- "created_at": int(time.time()),
129
- }
130
- try:
131
- session_ok = await self.gemini.acquire_session()
132
- if not session_ok:
133
- logger.warning(f"Gemini session failed for {fingerprint[:16]}, saving to pending")
134
- article["status"] = "gemini_pending"
135
- self._save_article(article)
136
- self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
137
- return None
138
-
139
- result = await self._run_pipeline(article, raw_text, source_url, media)
140
- return result
141
- except AllKeysExhausted:
142
- logger.warning(f"All Gemini keys exhausted processing {fingerprint[:16]}, saving to pending")
143
- article["status"] = "gemini_pending"
144
- self._save_article(article)
145
- self.db.add_to_gemini_pending(raw_text, source_url, media, fingerprint, channel_id, section)
146
- return None
147
- except Exception as e:
148
- logger.exception(f"Article processing failed: {e}")
149
- self._handle_processing_failure(fingerprint, raw_text, source_url, media, channel_id, e, article, section)
150
- return None
151
- finally:
152
- self.gemini.release_session()
153
-
154
- async def _process_next_pending(self) -> Optional[Dict]:
155
- """Try to process the first item in Gemini pending queue (FIFO).
156
- Returns the processed article if successful, None otherwise."""
157
- pending = self.db.get_gemini_pending_queue()
158
- if not pending:
159
- return None
160
- first = pending[0]
161
- raw_text = first.get("raw_text", "").strip()
162
- fingerprint = first.get("fingerprint", "")
163
- if not raw_text:
164
- if fingerprint:
165
- self.db.remove_pending_by_fingerprint(fingerprint)
166
- else:
167
- self.db.remove_from_gemini_pending(0)
168
- return None
169
- source_url = first.get("source_url", "")
170
- media = first.get("media", [])
171
- channel_id = first.get("channel_id", "")
172
- pending_section = first.get("section", "")
173
- if not fingerprint:
174
- fingerprint = self._fingerprint(raw_text, source_url)
175
-
176
- if self.db.is_published(fingerprint):
177
- self.db.remove_pending_by_fingerprint(fingerprint)
178
- return None
179
-
180
- article = {
181
- "fingerprint": fingerprint,
182
- "source_text": raw_text,
183
- "source_url": source_url,
184
- "media": media,
185
- "channel_id": channel_id,
186
- "status": "processing",
187
- "created_at": int(time.time()),
188
- }
189
- try:
190
- session_ok = await self.gemini.acquire_session()
191
- if not session_ok:
192
- return None
193
-
194
- result = await self._run_pipeline(article, raw_text, source_url, media)
195
- if result:
196
- result["channel_id"] = channel_id
197
- if pending_section and not result.get("section"):
198
- result["section"] = pending_section
199
- self.db.remove_pending_by_fingerprint(fingerprint)
200
- logger.info(f"Gemini pending queue: recovered article {fingerprint[:16]}")
201
- return result
202
- except AllKeysExhausted:
203
- return None
204
- except Exception as e:
205
- logger.exception(f"Pending recovery failed for {fingerprint[:16]}: {e}")
206
- # Keep the item in pending (up to MAX_PENDING_ATTEMPTS) instead of losing it.
207
- self._handle_processing_failure(fingerprint, raw_text, source_url, media, channel_id, e, article)
208
- return None
209
- finally:
210
- self.gemini.release_session()
211
-
212
- async def _run_pipeline(self, article: Dict, raw_text: str, source_url: str = "", media: List[Dict] = None) -> Optional[Dict]:
213
- """Execute the full Gemini pipeline on raw_text and populate article dict."""
214
- rewrite = await self._rewrite(raw_text)
215
- if rewrite:
216
- article.update(rewrite)
217
- extracted = await self._extract(raw_text)
218
- if extracted:
219
- article["extracted"] = extracted
220
- article["labels"] = []
221
- summary = await self._summary(raw_text)
222
- if summary:
223
- article["summary"] = summary
224
- notes = await self._notes(
225
- extracted or {},
226
- article.get("title", raw_text[:60]),
227
- article.get("body", raw_text),
228
- )
229
- if notes:
230
- article["notes"] = notes
231
- keywords = await self._keywords(
232
- article.get("title", raw_text[:60]),
233
- article.get("body", raw_text),
234
- extracted or {},
235
- )
236
- if keywords:
237
- article["keywords"] = keywords
238
- hashtags = await self._hashtags(
239
- extracted or {},
240
- article.get("title", raw_text[:60]),
241
- article.get("body", raw_text),
242
- )
243
- if hashtags:
244
- article["hashtags"] = hashtags
245
- logger.info(f"Hashtags Stored: {hashtags}")
246
- else:
247
- logger.warning(f"Hashtags Stored: empty or None")
248
- body_text = article.get("body", raw_text)
249
- article["reading_time"] = self._reading_time(body_text)
250
- if media:
251
- alt_data = await self._alt_text(
252
- article.get("title", raw_text[:60]),
253
- article.get("body", raw_text),
254
- )
255
- if alt_data:
256
- article["media_alt"] = alt_data
257
- article["status"] = "processed"
258
- article["processed_at"] = int(time.time())
259
- self._save_article(article)
260
- return article
261
-
262
- def _fingerprint(self, text: str, url: str = "") -> str:
263
- raw = f"{url}|{text[:300]}"
264
- return hashlib.md5(raw.encode("utf-8", errors="replace")).hexdigest()
265
-
266
- def _save_article(self, article: Dict):
267
- aid = article.get("fingerprint", str(int(time.time())))
268
- self.db.save_article(aid, article)
269
-
270
- async def _rewrite(self, text: str) -> Optional[Dict]:
271
- prompt = make_rewrite_prompt(text)
272
- result = await self.gemini.generate_json(prompt, SYSTEM_REWRITE)
273
- if not result:
274
- logger.warning("Gemini _rewrite returned no result")
275
- return None
276
- logger.info("Gemini _rewrite succeeded")
277
- return {
278
- "title": result.get("title", text[:80]),
279
- "body": result.get("body", f"<p>{text}</p>"),
280
- "introduction": result.get("introduction", ""),
281
- "faq": result.get("faq", []),
282
- "conclusion": result.get("conclusion", ""),
283
- "gemini_used": True,
284
- }
285
-
286
- async def _extract(self, text: str) -> Optional[Dict]:
287
- prompt = make_extract_prompt(text)
288
- return await self.gemini.generate_json(prompt, SYSTEM_EXTRACT)
289
-
290
- async def _seo(self, title: str, body: str) -> Optional[Dict]:
291
- prompt = make_seo_prompt(title, body)
292
- return await self.gemini.generate_json(prompt, SYSTEM_SEO)
293
-
294
- async def _hashtags(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]:
295
- prompt = make_hashtag_prompt(extracted, title, body)
296
- result = await self.gemini.generate_json(prompt, SYSTEM_HASHTAGS)
297
- if result and isinstance(result, dict):
298
- tags = result.get("hashtags", [])
299
- if isinstance(tags, list):
300
- logger.info(f"Hashtags Generated: {tags}")
301
- return tags
302
- logger.warning(f"Hashtags Generated but 'hashtags' key is not list: {type(tags)}")
303
- else:
304
- logger.warning(f"Hashtags Generated: AI returned invalid data: {result}")
305
- return []
306
-
307
- async def _alt_text(self, title: str, body: str) -> Optional[Dict]:
308
- prompt = f"""أنشئ وصف ALT وتعليق للصورة بناءً على:
309
- العنوان: {title}
310
- المحتوى: {body[:500]}
311
- الرد JSON فقط: {{"alt": "...", "caption": "..."}}"""
312
- return await self.gemini.generate_json(prompt, SYSTEM_ALT_IMAGE)
313
-
314
- # Legacy — labels now come from section settings in scheduler
315
- def _make_labels(self, extracted: Dict, seo: Dict) -> List[str]:
316
- labels = set()
317
- if extracted.get("type"):
318
- labels.add(extracted["type"])
319
- if extracted.get("ministry"):
320
- labels.add(extracted["ministry"])
321
- if extracted.get("province"):
322
- labels.add(extracted["province"])
323
- if extracted.get("city"):
324
- labels.add(extracted["city"])
325
- if extracted.get("company"):
326
- labels.add(extracted["company"])
327
- seo_labels = seo.get("labels", [])
328
- if isinstance(seo_labels, list):
329
- for lbl in seo_labels:
330
- if lbl:
331
- labels.add(str(lbl))
332
- return list(labels)[:10]
333
-
334
- async def _summary(self, text: str) -> Optional[str]:
335
- prompt = make_summary_prompt(text)
336
- result = await self.gemini.generate_json(prompt, SYSTEM_SUMMARY)
337
- if result and isinstance(result, dict):
338
- return result.get("summary", "")
339
- return None
340
-
341
- async def _notes(self, extracted: Dict, title: str, body: str) -> Optional[List[str]]:
342
- prompt = make_notes_prompt(extracted, title, body)
343
- result = await self.gemini.generate_json(prompt, SYSTEM_NOTES)
344
- if result and isinstance(result, dict):
345
- notes = result.get("notes", [])
346
- if isinstance(notes, list) and notes:
347
- return notes
348
- return None
349
-
350
- async def _keywords(self, title: str, body: str, extracted: Dict) -> Optional[str]:
351
- prompt = make_keywords_prompt(title, body, extracted)
352
- result = await self.gemini.generate_json(prompt, SYSTEM_KEYWORDS)
353
- if result and isinstance(result, dict):
354
- kw = result.get("keywords", "")
355
- if kw and isinstance(kw, str):
356
- return kw
357
- return None
358
-
359
- @staticmethod
360
- def _reading_time(body_html: str) -> int:
361
- text = re.sub(r'<[^>]+>', '', body_html)
362
- word_count = len(text.split())
363
- minutes = max(1, round(word_count / 150))
364
- return minutes
365
-
366
- def _add_inline_hashtags(self, body: str, extracted: Dict) -> str:
367
- entities = []
368
- if extracted.get("city"):
369
- entities.append(extracted["city"])
370
- if extracted.get("province"):
371
- entities.append(extracted["province"])
372
- if extracted.get("ministry"):
373
- entities.append(extracted["ministry"])
374
- if extracted.get("company"):
375
- entities.append(extracted["company"])
376
- if extracted.get("university"):
377
- entities.append(extracted["university"])
378
- if extracted.get("organization"):
379
- entities.append(extracted["organization"])
380
- if extracted.get("job_type"):
381
- entities.append(extracted["job_type"])
382
- if extracted.get("district"):
383
- entities.append(extracted["district"])
384
- result = body
385
- for entity in entities:
386
- if entity and len(entity) > 2:
387
- tag = entity.replace(" ", "_")
388
- replacement = f'<a href="https://www.blogger.com/search?q={tag}" style="text-decoration:none;color:#1a73e8;">#{tag}</a>'
389
- result = result.replace(entity, replacement, 1)
390
- return result
391
-
392
- def _article_css(self) -> str:
393
- return """<style>
394
- html{scroll-behavior:smooth;}
395
- body{font-family:'Segoe UI',Tahoma,Arial,sans-serif;}
396
- h2,h3,h4{font-weight:bold!important;margin:18px 0 10px 0;clear:both;color:#1a1a2e;line-height:1.6;}
397
- p{line-height:1.8;color:#3c4043;margin:8px 0;font-size:15px;}
398
- a{color:#1a73e8;text-decoration:none;}
399
- a:hover{text-decoration:underline;}
400
- table,.job-table{width:100%;border-collapse:collapse;margin:16px 0;font-size:14px;direction:rtl;text-align:right;font-family:'Segoe UI',Tahoma,Arial,sans-serif;background:#fff;border:1px solid #dde3ea;border-radius:8px;overflow:hidden;}
401
- table th,.job-table th{background:#1f3a5f;color:#fff;padding:10px 14px;border:1px solid #1f3a5f;text-align:right;font-weight:bold;font-size:14px;}
402
- table td,.job-table td{padding:10px 14px;border:1px solid #e1e5ea;color:#2c3e50;vertical-align:top;line-height:1.7;font-size:14px;text-align:right;}
403
- table tr:nth-child(even) td,.job-table tr:nth-child(even) td{background:#f6f8fa;}
404
- table tr:hover td,.job-table tr:hover td{background:#eef4fb;}
405
- .details-table-wrap{overflow-x:auto;margin:16px 0;border-radius:12px;box-shadow:0 2px 6px rgba(0,0,0,.08);}
406
- .details-table{width:100%;border-collapse:separate;border-spacing:0;direction:rtl;text-align:right;font-family:'Segoe UI',Tahoma,Arial,sans-serif;background:#fff;border:1px solid #c8d2e0;border-radius:12px;overflow:hidden;font-size:14px;}
407
- .details-table th{background:#0b2e5b;color:#fff;font-weight:bold;width:35%;padding:14px 16px;border:1px solid #0b2e5b;text-align:right;white-space:nowrap;font-size:14px;}
408
- .details-table td{background:#fff;color:#1f2937;padding:14px 16px;border:1px solid #d8dfe9;text-align:right;line-height:1.7;font-size:14px;}
409
- .summary-box{background:#fffbea;border-right:4px solid #f5c518;padding:12px 16px;margin:15px 0;border-radius:4px;}
410
- .notes-box{background:#fff3f3;border-right:4px solid #dc3545;padding:12px 16px;margin:15px 0;border-radius:4px;}
411
- .toc-box{background:#f0f4ff;border:1px solid #cfe2ff;border-radius:10px;padding:14px 18px;margin:15px 0;}
412
- .toc-box ul{margin:0;list-style:none;padding:0;}
413
- .toc-box li{margin:4px 0;}
414
- .toc-box a{color:#1a73e8;font-size:14px;display:block;padding:4px 8px;border-radius:4px;}
415
- .toc-box a:hover{background:#e8f0fe;text-decoration:none;}
416
- .hashtag-box{margin:15px 0;padding:12px 16px;background:#f8f9fa;border-radius:4px;text-align:center;}
417
- .keywords-box{margin:15px 0;padding:12px 16px;background:#f8f9fa;border-radius:4px;text-align:center;}
418
- .tag{display:inline-block;background:#e3f2fd;color:#1565c0;padding:4px 12px;margin:3px 4px;border-radius:16px;font-size:13px;border:1px solid #90caf9;}
419
- .article-end{background:#f0f7ff;border:1px solid #b8d8f0;border-radius:12px;padding:18px 22px;margin:22px 0;text-align:center;}
420
- .article-end p{margin:0;font-size:16px;color:#1f3a5f;line-height:1.9;}
421
- .apply-section{margin:18px 0;text-align:center;direction:rtl;}
422
- .apply-intro{background:#f4f7fb;border:1px solid #d5dee8;border-radius:10px;padding:14px 18px;color:#3c4043;line-height:1.9;font-size:15px;text-align:right;margin:0 0 16px 0;}
423
- .apply-box{display:block;margin:14px auto;max-width:480px;border-radius:14px;padding:18px 22px;border:1px solid;text-align:center;box-shadow:0 3px 10px rgba(0,0,0,.07);}
424
- .apply-box-phone{background:#0f9d58;border-color:#0f9d58;}
425
- .apply-box-mail{background:#fff;border-color:#d5dee8;}
426
- .apply-box-link{background:#fff;border-color:#d5dee8;}
427
- .apply-box-label{font-weight:bold;font-size:14px;display:block;margin-bottom:8px;color:#5f6368;}
428
- .apply-box-phone .apply-box-label{color:#e8f5e9;}
429
- .apply-box-value{font-size:24px;font-weight:bold;color:#1a73e8;direction:ltr;display:inline-block;word-break:break-all;text-decoration:none!important;}
430
- .apply-box-value:hover{text-decoration:underline!important;}
431
- .apply-box-phone .apply-box-value{color:#fff;font-size:30px;letter-spacing:1px;}
432
- .apply-box-actions{margin-top:12px;}
433
- .apply-btn{display:inline-block;padding:10px 28px;border-radius:10px;font-weight:bold;font-size:15px;margin:4px;text-decoration:none!important;color:#fff!important;transition:opacity .15s;}
434
- .apply-btn:hover{opacity:.88;text-decoration:none!important;}
435
- .apply-btn-call{background:#1a73e8;}
436
- .apply-btn-whatsapp{background:#25d366;}
437
- .apply-btn-cv{background:#1a73e8;}
438
- .apply-btn-now{background:#ff6d00;}
439
- @media (max-width:600px){
440
- table,.job-table{font-size:13px;}
441
- table th,table td,.job-table th,.job-table td{padding:8px 10px;}
442
- .details-table th{width:40%;font-size:13px;padding:10px 10px;}
443
- .details-table td{font-size:13px;padding:10px 10px;}
444
- .apply-box{width:92%;padding:14px 14px;}
445
- .apply-box-value{font-size:17px;}
446
- .apply-box-phone .apply-box-value{font-size:22px;}
447
- .apply-btn{display:block;margin:6px auto;width:70%;}
448
- }
449
- </style>"""
450
-
451
- def make_article_html(self, article: Dict) -> str:
452
- parts = []
453
- parts.append(self._article_css())
454
-
455
- # ── 1. Featured Image ──
456
- parts.append(self._make_featured_image(article))
457
-
458
- # ── 2. Summary Box ──
459
- summary = article.get("summary", "")
460
- if summary:
461
- parts.append(self._make_summary_box(summary))
462
-
463
- # ── 3. Introduction ──
464
- intro = article.get("introduction", "")
465
- if intro:
466
- parts.append(f'<h2 id="intro">المقدمة</h2><p>{intro}</p>')
467
-
468
- # ── 4. Details Table (first section after introduction) ──
469
- details_table = self._make_details_table(article)
470
- if details_table:
471
- parts.append(details_table)
472
-
473
- # ── 5. Table of Contents + Quick Nav (merged) ──
474
- body = article.get("body", "")
475
- toc, processed_body = self._make_toc(body)
476
- if toc:
477
- parts.append(toc)
478
-
479
- # ── 6. Full Article Body (with apply contacts injected) ──
480
- body_to_process = processed_body or body
481
- body_to_process = self._enhance_body_tables(body_to_process)
482
- body_to_process = self._inject_apply_into_body(article, body_to_process)
483
- if body_to_process:
484
- parts.append(f'<div>{body_to_process}</div>')
485
-
486
- # ── 7. Important Notes ──
487
- notes = article.get("notes", [])
488
- if notes:
489
- parts.append(self._make_notes_box(notes))
490
-
491
- # ── 8. FAQ ──
492
- faq = article.get("faq", [])
493
- if faq:
494
- parts.append(self._make_faq(faq))
495
-
496
- # ── 9. Conclusion (professional end card) ──
497
- conclusion = article.get("conclusion", "")
498
- if conclusion:
499
- parts.append(self._make_conclusion_box(conclusion))
500
-
501
- # ── 10. Hashtags ──
502
- hashtags = article.get("hashtags", [])
503
- logger.info(f"Hashtags Before HTML: {hashtags}")
504
- if hashtags:
505
- parts.append(self._make_hashtags_section(hashtags))
506
-
507
- # ── 11. Source ──
508
- source = article.get("source", {})
509
- if source:
510
- parts.append(self._make_source(source))
511
-
512
- # ── 12. Keywords ──
513
- keywords = article.get("keywords", "")
514
- if keywords:
515
- parts.append(self._make_keywords_section(keywords))
516
-
517
- # ── 13. Schema JSON-LD ──
518
- schema = self._make_schema(article)
519
- if schema:
520
- parts.append(schema)
521
-
522
- return "\n".join(parts)
523
-
524
- def _enhance_body_tables(self, body: str) -> str:
525
- if not body:
526
- return body
527
- def _replace(m):
528
- tag = m.group(0)
529
- if "class=" not in tag:
530
- return '<table class="job-table">'
531
- return tag
532
- return re.sub(r'<table[^>]*>', _replace, body)
533
-
534
- def _make_conclusion_box(self, conclusion: str) -> str:
535
- return f'<div class="article-end"><p>📢 {conclusion}</p></div>'
536
-
537
- def _make_featured_image(self, article: Dict) -> str:
538
- alt_text = article.get("media_alt", {}).get("alt", "")
539
- caption = article.get("media_alt", {}).get("caption", "")
540
- img_src = None
541
- if self.config:
542
- img_src = self.config.get("default_jobs_image", "")
543
- if not img_src:
544
- return ""
545
- alt = alt_text or "صورة المقال"
546
- title = article.get("title", "")[:60]
547
- 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>'
548
- if caption:
549
- img += f'<p style="text-align:center;font-size:13px;color:#666;margin-top:-10px;">{caption}</p>'
550
- return img
551
-
552
- @staticmethod
553
- def _flat(value) -> str:
554
- """Defensively coerce a possibly-list/dict extracted value into a plain string."""
555
- if value is None:
556
- return ""
557
- if isinstance(value, (list, tuple)):
558
- for item in value:
559
- if item:
560
- return str(item).strip()
561
- return ""
562
- if isinstance(value, dict):
563
- return ""
564
- return str(value).strip()
565
-
566
- def _make_details_table(self, article: Dict) -> str:
567
- logger.info("Summary Builder Called")
568
- extracted = article.get("extracted", {}) or {}
569
- entity = ""
570
- for key in ("company", "ministry", "organization", "university", "institute"):
571
- if extracted.get(key):
572
- entity = self._flat(extracted.get(key))
573
- break
574
- location = " – ".join(
575
- filter(None, [self._flat(extracted.get(k)) for k in ("province", "city", "region", "district", "address")])
576
- )
577
- specialty = self._flat(extracted.get("specialization")) or self._flat(extracted.get("job_type"))
578
- apply_method = self._flat(extracted.get("apply_method"))
579
- if not apply_method:
580
- parts = []
581
- if extracted.get("email"):
582
- parts.append("إرسال السيرة الذاتية إلى البريد الإلكتروني")
583
- if extracted.get("phone"):
584
- parts.append("الاتصال على رقم الهاتف")
585
- if extracted.get("apply_url"):
586
- parts.append("التقديم عبر الرابط الإلكتروني")
587
- apply_method = " أو ".join(parts)
588
- rows = [
589
- ("الجهة المعلنة", entity),
590
- ("موقع العمل", location),
591
- ("التخصصات المطلوبة", specialty),
592
- ("آلية التقديم", apply_method),
593
- ]
594
- trows = "".join(f'<tr><th>{label}</th><td>{value or "—"}</td></tr>' for label, value in rows)
595
- return (f'<h2>📋 ملخص تفاصيل الفرصة الوظيفية</h2>'
596
- f'<div class="details-table-wrap"><table class="details-table">{trows}</table></div>')
597
-
598
- def _make_summary_box(self, summary: str) -> str:
599
- return f'<div class="summary-box"><strong style="color:#856404;">📌 ملخص المقال</strong><p style="margin:8px 0 0 0;color:#856404;font-size:15px;">{summary}</p></div>'
600
-
601
- def _make_toc(self, body: str) -> tuple:
602
- if not body:
603
- return "", body
604
- headings = re.findall(r'<h([23])[^>]*>(.*?)</h\1>', body, re.DOTALL)
605
- if len(headings) < 2:
606
- return "", body
607
- icon_map = {
608
- "نبذة": "ℹ️", "تفاصيل": "📋", "بيئة": "🏢", "المهام": "📌",
609
- "مؤهلات": "🎓", "شروط": "📄", "تقديم": "📝", "مميزات": "⭐",
610
- "أسئلة": "❓", "خلاصة": "✅", "تعليمات": "📋", "ملاحظات": "⚠️",
611
- "طريقة": "📝", "شواغر": "👥", "راتب": "💰", "دوام": "🕐",
612
- }
613
- items = []
614
- processed = body
615
- idx = 0
616
- for level, text in headings:
617
- if "التنقل" in text:
618
- processed = re.sub(
619
- rf'<h{level}[^>]*>{re.escape(text)}</h{level}>',
620
- '', processed, count=1
621
- )
622
- continue
623
- anchor = f"sec-{idx}"
624
- icon = "📌"
625
- for keyword, emoji in icon_map.items():
626
- if keyword in text:
627
- icon = emoji
628
- break
629
- items.append(f'<li><a href="#{anchor}">{icon} {text}</a></li>')
630
- processed = processed.replace(
631
- f'<h{level}>{text}</h{level}>',
632
- f'<h{level} id="{anchor}">{text}</h{level}>', 1
633
- )
634
- idx += 1
635
- if len(items) < 2:
636
- return "", processed
637
- toc = f'<div class="toc-box"><strong style="font-size:16px;color:#1a73e8;display:block;margin-bottom:8px;">📋 المحتويات والتنقل السريع</strong><ul>{"".join(items)}</ul></div>'
638
- return toc, processed
639
-
640
- @staticmethod
641
- def _is_iraqi_phone(clean_phone: str) -> bool:
642
- digits = re.sub(r'[^\d]', '', clean_phone)
643
- return digits.startswith("07") or digits.startswith("9647")
644
-
645
- @staticmethod
646
- def _to_whatsapp(clean_phone: str) -> str:
647
- digits = re.sub(r'[^\d]', '', clean_phone)
648
- if digits.startswith("964"):
649
- return digits
650
- if digits.startswith("0"):
651
- return "964" + digits[1:]
652
- return "964" + digits
653
-
654
- def _make_apply_section_html(self, email: str, phone: str, apply_url: str) -> str:
655
- logger.info("Apply Builder Called")
656
- blocks = []
657
- if phone:
658
- clean_phone = re.sub(r'[^\d+]', '', phone)
659
- buttons = f'<a class="apply-btn apply-btn-call" href="tel:{clean_phone}">📞 اتصال</a>'
660
- if self._is_iraqi_phone(clean_phone):
661
- wa = self._to_whatsapp(clean_phone)
662
- buttons += f'<a class="apply-btn apply-btn-whatsapp" href="https://wa.me/{wa}" target="_blank" rel="noopener">💬 واتساب</a>'
663
- blocks.append(
664
- f'<div class="apply-box apply-box-phone">'
665
- f'<div class="apply-box-label">📞 رقم الهاتف</div>'
666
- f'<a class="apply-box-value" href="tel:{clean_phone}">{phone}</a>'
667
- f'<div class="apply-box-actions">{buttons}</div>'
668
- f'</div>'
669
- )
670
- if email:
671
- blocks.append(
672
- f'<div class="apply-box apply-box-mail">'
673
- f'<div class="apply-box-label">✉️ البريد الإلكتروني</div>'
674
- f'<a class="apply-box-value" href="mailto:{email}">{email}</a>'
675
- f'<div class="apply-box-actions">'
676
- f'<a class="apply-btn apply-btn-cv" href="mailto:{email}">📧 إرسال CV</a>'
677
- f'</div>'
678
- f'</div>'
679
- )
680
- if apply_url:
681
- blocks.append(
682
- f'<div class="apply-box apply-box-link">'
683
- f'<div class="apply-box-label">🌐 رابط التقديم</div>'
684
- f'<a class="apply-box-value" href="{apply_url}" target="_blank" rel="noopener">{apply_url}</a>'
685
- f'<div class="apply-box-actions">'
686
- f'<a class="apply-btn apply-btn-now" href="{apply_url}" target="_blank" rel="noopener">التقديم</a>'
687
- f'</div>'
688
- f'</div>'
689
- )
690
- return '<div class="apply-section">' + "".join(blocks) + '</div>'
691
-
692
- def _inject_apply_into_body(self, article: Dict, body: str) -> str:
693
- if not body:
694
- return body
695
- extracted = article.get("extracted", {}) or {}
696
- email = self._flat(extracted.get("email"))
697
- phone = self._flat(extracted.get("phone"))
698
- apply_url = self._flat(extracted.get("apply_url"))
699
- if not (email or phone or apply_url):
700
- return body
701
-
702
- section_html = self._make_apply_section_html(email, phone, apply_url)
703
- intro = ('<p class="apply-intro">يمكنك التقديم على هذه الفرصة عبر إحدى وسائل التواصل التالية:</p>')
704
-
705
- main_patterns = [
706
- r'<h[23][^>]*>(?:آلية التقديم والتواصل|طريقة التقديم والتواصل|طريقة التقديم على الوظيفة|طريقة التقديم|كيفية التقديم|التقديم على الوظيفة)</h[23]>',
707
- ]
708
- for pattern in main_patterns:
709
- match = re.search(pattern, body, re.IGNORECASE)
710
- if match:
711
- heading_tag = match.group(0)
712
- heading_id = re.search(r'id="([^"]+)"', heading_tag)
713
- anchor = heading_id.group(1) if heading_id else "apply"
714
- heading_html = f'<h2 id="{anchor}">آلية التقديم والتواصل</h2>'
715
- rest = body[match.end():]
716
- next_m = re.search(r'<h[23][^>]*>', rest)
717
- strip_end = match.end() + (next_m.start() if next_m else len(rest))
718
- return body[:match.start()] + heading_html + intro + section_html + body[strip_end:]
719
- fallback = re.search(r'<h[23][^>]*>(?:شروط التقديم|التقديم)</h[23]>', body, re.IGNORECASE)
720
- if fallback:
721
- end = fallback.end()
722
- return body[:end] + intro + section_html + body[end:]
723
- return body
724
-
725
- def _make_notes_box(self, notes: list) -> str:
726
- lis = "".join(f"<li>{n}</li>" for n in notes)
727
- return f'<div class="notes-box"><strong style="color:#721c24;">⚠️ ملاحظات مهمة</strong><ul style="margin:8px 0 0 0;color:#721c24;">{lis}</ul></div>'
728
-
729
- def _make_faq(self, faq: list) -> str:
730
- items = ""
731
- for item in faq:
732
- q = item.get("question", "")
733
- a = item.get("answer", "")
734
- if q and a:
735
- 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>'
736
- if not items:
737
- return ""
738
- return f'<h2 style="font-size:18px;font-weight:bold;margin:18px 0 10px 0;color:#222;">الأسئلة الشائعة</h2><div itemscope itemtype="https://schema.org/FAQPage">{items}</div>'
739
-
740
- def _make_source(self, source: dict) -> str:
741
- name = source.get("name", "المصدر")
742
- username = source.get("username", "")
743
- link = source.get("link", "")
744
- if link and username and not username.startswith("private"):
745
- 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>'
746
- return f'<div style="background:#f0f0f0;padding:10px 12px;border-radius:4px;margin:15px 0;font-size:13px;color:#666;"><strong>المصدر:</strong> {name}</div>'
747
-
748
- def _make_keywords_section(self, keywords: str) -> str:
749
- parts = re.split(r'[،,\n]+', keywords)
750
- tags = []
751
- for p in parts:
752
- t = p.strip()
753
- if t:
754
- tags.append(f'<span style="display:inline-block;background:#e3f2fd;color:#1565c0;padding:4px 12px;margin:3px 4px;border-radius:16px;font-size:13px;border:1px solid #90caf9;">{t}</span>')
755
- if not tags:
756
- return ""
757
- return f'<div class="keywords-box"><strong style="display:block;font-size:15px;margin-bottom:8px;color:#333;">🏷️ الكلمات الدلالية</strong><div style="direction:rtl;text-align:center;">{"".join(tags)}</div></div>'
758
-
759
- def _make_hashtags_section(self, hashtags: List[str]) -> str:
760
- tags_items = []
761
- for tag in hashtags:
762
- t = tag.strip()
763
- if t and not t.startswith("#"):
764
- t = "#" + t
765
- if t:
766
- tags_items.append(t)
767
- items = " ".join(tags_items)
768
- return f'<div class="hashtag-box" style="direction:rtl;"><strong style="font-size:14px;display:block;margin-bottom:6px;">🏷️ الهاشتاكات</strong><p style="color:#1a73e8;margin:0;font-size:15px;line-height:1.8;">{items}</p></div>'
769
-
770
- def _make_schema(self, article: Dict) -> str:
771
- title = article.get("title", "")
772
- intro = article.get("introduction", "")
773
- body = article.get("body", "")
774
- apply_pattern = r'<h[23][^>]*>(?:آلية التقديم والتواصل|طريقة التقديم والتواصل|طريقة التقديم على الوظيفة|طريقة التقديم|كيفية التقديم|التقديم على الوظيفة)</h[23]>.*?(?=<h[23]|$)'
775
- body = re.sub(apply_pattern, '', body, flags=re.DOTALL | re.IGNORECASE)
776
- text = re.sub(r'<[^>]+>', '', f"{intro} {body}")[:300]
777
- section = article.get("section", "")
778
- is_news = section not in ("jobs", "وظائف")
779
- schema = {
780
- "@context": "https://schema.org",
781
- "@type": "NewsArticle" if is_news else "Article",
782
- "headline": title,
783
- "description": text[:160],
784
- "articleBody": text,
785
- "inLanguage": "ar",
786
- "author": {"@type": "Organization", "name": "المدونة"},
787
- "publisher": {"@type": "Organization", "name": "المدونة"},
788
- "datePublished": article.get("created_at", ""),
789
- "dateModified": article.get("processed_at", ""),
790
- }
791
- schema_str = json.dumps(schema, ensure_ascii=False)
792
- return f'<script type="application/ld+json">{schema_str}</script>'
793
-
794
- def make_preview_data(self, article: Dict) -> Tuple[Optional[str], str]:
795
- html = self.make_article_html(article)
796
- image = None
797
- media = article.get("media", [])
798
- for m in media:
799
- if m.get("type") == "photo":
800
- image = m.get("file_id")
801
- break
802
- if not image and self.config:
803
- section = article.get("section", "")
804
- if section in ("jobs", "وظائف", "general"):
805
- image = self.config.get("default_jobs_image", "")
806
- telegram_text = self.html_to_telegram(html)
807
- title = article.get("title", "")
808
- if title:
809
- telegram_text = f"<b>{title}</b>\n\n{telegram_text}"
810
- reading_time = article.get("reading_time", 0)
811
- if reading_time:
812
- telegram_text += f"\n⏱️ مدة القراءة: {reading_time} دقيقة"
813
- labels = article.get("labels", [])
814
- if labels:
815
- telegram_text += f"\n🏷 {', '.join(labels)}"
816
- return image, telegram_text
817
-
818
- @staticmethod
819
- def html_to_telegram(html: str) -> str:
820
- html = re.sub(r'<script[^>]*>.*?</script>', '', html, flags=re.DOTALL)
821
-
822
- def _replace_table(m):
823
- rows = re.findall(r'<tr>(.*?)</tr>', m.group(1), re.DOTALL)
824
- lines = []
825
- for row in rows:
826
- cells = re.findall(r'<t[hd][^>]*>(.*?)</t[hd]>', row, re.DOTALL)
827
- if cells:
828
- lines.append(' | '.join(cells))
829
- return '\n'.join(lines) + '\n'
830
- html = re.sub(r'<table[^>]*>(.*?)</table>', _replace_table, html, flags=re.DOTALL)
831
- html = re.sub(r'<img[^>]*>', '', html)
832
- html = re.sub(r'<h([23])[^>]*>(.*?)</h\1>', r'<b>\2</b>', html, flags=re.DOTALL)
833
- html = re.sub(r'<li>(.*?)</li>', r'• \1', html, flags=re.DOTALL)
834
- html = re.sub(r'</?u?[ol][^>]*>', '', html)
835
- html = re.sub(r'<details[^>]*>', '', html)
836
- html = re.sub(r'</details>', '', html)
837
- html = re.sub(r'<summary[^>]*>(.*?)</summary>', r'<b>\1</b>\n', html, flags=re.DOTALL)
838
- html = re.sub(r'</?div[^>]*>', '', html)
839
- html = re.sub(r'</?span[^>]*>', '', html)
840
- html = re.sub(r'<p>(.*?)</p>', r'\1\n', html, flags=re.DOTALL)
841
- html = re.sub(r'<br\s*/?>', '\n', html)
842
- html = re.sub(r'<strong>(.*?)</strong>', r'<b>\1</b>', html)
843
- html = re.sub(r'<em>(.*?)</em>', r'<i>\1</i>', html)
844
- html = re.sub(r'</?t[rdh][^>]*>', '', html)
845
- allowed = {'b', 'i', 'u', 's', 'a', 'code', 'pre', 'em', 'strong'}
846
- html = re.sub(r'<(?!/?(' + '|'.join(allowed) + r')(?:\s[^>]*)?>)[a-z]+[^>]*>', '', html, flags=re.IGNORECASE)
847
- html = re.sub(r'</(?!(' + '|'.join(allowed) + r')\b)[a-z]+>', '', html, flags=re.IGNORECASE)
848
- html = re.sub(r'\n{3,}', '\n\n', html)
849
- return html.strip()