import logging import json from typing import List, Optional, Dict, Any from db.models import Post, TargetChannel from db.repository import Repository from core.llm import LLMClient from core.metrics import DUPLICATES_DETECTED_TOTAL from core.error_logger import log_exception logger = logging.getLogger(__name__) CHANNEL_REWRITE_SYSTEM_PROMPT = """ You are a professional Persian Telegram copywriter and editor. Your job is to rewrite the provided raw post specifically for the target channel: "{channel_title}". CHANNEL PERSONALITY & TONE GUIDELINES: {personality} CRITICAL RULES: 1. Completely REMOVE all original channel usernames (e.g. @source_channel), sponsor tags, author watermarks, and source links. 2. Translate or rewrite into natural, highly engaging, and fluent Persian (فارسی روان، جذاب و حرفه‌ای). 3. Use appropriate emojis and clear paragraph spacing. 4. If a custom footer/tag is provided below, append it cleanly at the very end of the post: {custom_footer} Respond ONLY in valid JSON format: { "rewritten_text": "..." } """ class AIProcessor: def __init__(self, repo: Repository, llm: Optional[LLMClient] = None): self.repo = repo self.llm = llm or LLMClient() async def rewrite_for_target(self, raw_text: str, target: TargetChannel) -> str: """Rewrite raw text according to a specific target channel's personality and custom footer.""" if not raw_text: return "" personality_text = target.personality.strip() if target.personality else "لحن رسمی، جذاب و روان به همراه ایموجی‌های مرتبط و پاراگراف‌بندی مرتب." footer_text = target.custom_footer.strip() if target.custom_footer else (f"@{target.username}" if target.username else "") sys_prompt = CHANNEL_REWRITE_SYSTEM_PROMPT.format( channel_title=target.title or "کانال تلگرام", personality=personality_text, custom_footer=footer_text ) try: res = await self.llm.generate_json( prompt=f"متن اصلی پست برای بازنویسی:\n\n{raw_text}", system_prompt=sys_prompt, action_name="rewrite_target_post" ) rewritten = res.get("rewritten_text") if rewritten: return rewritten.strip() except Exception as e: await log_exception("ai_processor.rewrite", e, {"target_id": target.id, "target_title": target.title}) # Fallback if AI fails: clean basic @mentions and append footer fallback = raw_text if footer_text: fallback = f"{fallback}\n\n{footer_text}" return fallback