Spaces:
Runtime error
Runtime error
Download app/core/prompt_manager.py from digitalytics/humanizer-engine: direct link, hf CLI and curl.
- Browser
- Download file 5.6 kB
-
https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/app/core/prompt_manager.py
- Command line
-
hf download hf://spaces/digitalytics/humanizer-engine/app/core/prompt_manager.py
-
curl -L -o prompt_manager.py https://huggingface.co/spaces/digitalytics/humanizer-engine/resolve/main/app/core/prompt_manager.py
5.6 kB
| """ | |
| Prompt Manager -- builds the full LLM prompt from a variant + Stage 1 analysis. | |
| Uses "write from notes" framing to avoid paraphrase detection fingerprint. | |
| The original text is provided alongside notes as a fact-checking reference | |
| to prevent content drift. | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| import random | |
| import re | |
| from typing import Any | |
| from app.prompts.variants import CORE_RULES, VARIANTS | |
| from app.utils.text_utils import count_words | |
| logger = logging.getLogger(__name__) | |
| class PromptManager: | |
| """Manages prompt variant rotation and prompt construction.""" | |
| def __init__(self) -> None: | |
| self._last_idx: int = -1 | |
| def build_prompt( | |
| self, | |
| original_text: str, | |
| analysis_result: dict[str, Any], | |
| ) -> tuple[str, str, str]: | |
| """Build the full prompt for the LLM. | |
| Returns: | |
| Tuple of (system_prompt, user_content, variant_id). | |
| """ | |
| variant = self._pick_variant() | |
| word_count = count_words(original_text) | |
| max_words = int(word_count * 1.35) | |
| hard_max = int(word_count * 1.40) | |
| rules = CORE_RULES.format( | |
| word_count=word_count, | |
| max_words=max_words, | |
| hard_max=hard_max, | |
| ) | |
| system_prompt = ( | |
| f"{variant['role']}\n\n" | |
| f"{rules}\n" | |
| f"{variant['micro']}" | |
| ) | |
| # Build user content: notes + original text as fact-check reference | |
| notes = self._extract_notes(original_text) | |
| analysis_text = self.format_analysis_for_llm(analysis_result) | |
| banned_words = analysis_result.get("banned_words", []) | |
| banned_str = ", ".join(banned_words) if banned_words else "(none)" | |
| user_content = ( | |
| f"{analysis_text}\n\n" | |
| f"WORDS TO AVOID in your output: {banned_str}\n\n" | |
| f"SOURCE NOTES:\n" | |
| f"{notes}\n\n" | |
| f"ORIGINAL TEXT (use ONLY to verify facts,sections and structure -- do NOT copy phrasing):\n" | |
| f"{original_text}\n\n" | |
| f"CONTENT RULES:\n" | |
| f"- Cover EVERY numbered section and heading shown in the source notes, in the same order\n" | |
| f"- Every name, number, URL, tool name, and technical term from the original must appear exactly\n" | |
| f"- Do NOT add new information, claims, or sections not in the original\n" | |
| f"- Do NOT omit or summarize away any section -- match the paragraph count\n" | |
| f"- Write each section fresh -- different sentence structure and phrasing, same information\n\n" | |
| f"Write ONLY the article text. No preamble, no commentary, no meta-text." | |
| ) | |
| logger.info("Using prompt variant: %s", variant["id"]) | |
| return system_prompt, user_content, variant["id"] | |
| def _extract_notes(text: str) -> str: | |
| """Reformat the original text as structured notes. | |
| Converts paragraphs into bullet-pointed notes while keeping ALL | |
| content intact. The "notes" framing comes from the bullet-point | |
| formatting + system prompt, not from stripping content. | |
| """ | |
| lines = text.strip().split('\n') | |
| notes_lines = [] | |
| for line in lines: | |
| stripped = line.strip() | |
| if not stripped: | |
| notes_lines.append('') | |
| continue | |
| # Headings, numbered items, section titles — keep as structural markers | |
| if re.match(r'^(\d+\.|\d+\.\d+\.?|#{1,3}|[A-Z][^.]*:)', stripped): | |
| notes_lines.append(stripped) | |
| else: | |
| # Body text — prefix with bullet to frame as "notes" | |
| notes_lines.append(f"- {stripped}") | |
| return '\n'.join(notes_lines) | |
| def format_analysis_for_llm(analysis_result: dict[str, Any]) -> str: | |
| """Convert Stage 1 analysis into writing guidance.""" | |
| summary = analysis_result.get("summary", {}) | |
| total = summary.get("total_sentences", 0) | |
| high = summary.get("high_risk_sentences", 0) | |
| ai_vocab = summary.get("ai_vocabulary_count", 0) | |
| burst_cv = summary.get("burstiness_cv", 0) | |
| burst_rating = summary.get("burstiness_rating", "unknown") | |
| lines = ["WRITING GUIDANCE:\n"] | |
| if high > 0: | |
| lines.append( | |
| f"- {high} of {total} sentences in the source are highly predictable " | |
| f"(standard AI phrasing). Write with more varied, less expected phrasing." | |
| ) | |
| if ai_vocab > 0: | |
| lines.append( | |
| f"- {ai_vocab} AI vocabulary words found in source. Your output must " | |
| f"avoid these and use simpler, more direct alternatives." | |
| ) | |
| if burst_rating in ("high_uniformity", "moderate_uniformity"): | |
| lines.append( | |
| f"- Source has very uniform sentence lengths (CV: {burst_cv:.2f}). " | |
| f"Mix short (4-8 word) and long (22-35 word) sentences throughout." | |
| ) | |
| lines.append( | |
| "\nWrite from the notes below. Different words, same information. Do not skip any section." | |
| ) | |
| return "\n".join(lines) | |
| def _pick_variant(self) -> dict[str, str]: | |
| """Pick a random variant, ensuring no consecutive repeats.""" | |
| if len(VARIANTS) <= 1: | |
| self._last_idx = 0 | |
| return VARIANTS[0] | |
| while True: | |
| idx = random.randint(0, len(VARIANTS) - 1) | |
| if idx != self._last_idx: | |
| break | |
| self._last_idx = idx | |
| return VARIANTS[idx] | |