feat: initial commit for Blog Expert multi-agent system
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
import winreg
|
||||
from datetime import datetime, timezone
|
||||
|
||||
def get_windows_datetime_format() -> str:
|
||||
try:
|
||||
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Control Panel\International") as key:
|
||||
short_date = winreg.QueryValueEx(key, "sShortDate")[0]
|
||||
time_format = winreg.QueryValueEx(key, "sTimeFormat")[0]
|
||||
|
||||
# Convert Windows date tokens to Python strftime tokens
|
||||
# Longest patterns first to prevent substring matching issues
|
||||
date_map = [
|
||||
("yyyy", "%Y"),
|
||||
("yy", "%y"),
|
||||
("MMMM", "%B"),
|
||||
("MMM", "%b"),
|
||||
("MM", "%m"),
|
||||
("M", "%m"),
|
||||
("dd", "%d"),
|
||||
("d", "%d"),
|
||||
]
|
||||
py_date = short_date
|
||||
for win_tok, py_tok in date_map:
|
||||
py_date = py_date.replace(win_tok, py_tok)
|
||||
|
||||
# Convert Windows time tokens to Python strftime tokens
|
||||
time_map = [
|
||||
("HH", "%H"),
|
||||
("H", "%H"),
|
||||
("hh", "%I"),
|
||||
("h", "%I"),
|
||||
("mm", "%M"),
|
||||
("m", "%M"),
|
||||
("ss", "%S"),
|
||||
("s", "%S"),
|
||||
("tt", "%p"),
|
||||
("t", "%p"),
|
||||
]
|
||||
py_time = time_format
|
||||
for win_tok, py_tok in time_map:
|
||||
py_time = py_time.replace(win_tok, py_tok)
|
||||
|
||||
return f"{py_date} {py_time}"
|
||||
except Exception:
|
||||
# Fallback to a standard readable format
|
||||
return "%d-%b-%Y %I:%M:%S %p"
|
||||
|
||||
def format_local_datetime(utc_iso_str: str) -> str:
|
||||
if not utc_iso_str:
|
||||
return ""
|
||||
try:
|
||||
if utc_iso_str.endswith("Z"):
|
||||
utc_iso_str = utc_iso_str[:-1] + "+00:00"
|
||||
# Handle formats like "2026-07-23 03:39:30" (replace spaces with T)
|
||||
if " " in utc_iso_str and "T" not in utc_iso_str:
|
||||
parts = utc_iso_str.split(" ")
|
||||
utc_iso_str = f"{parts[0]}T{parts[1]}"
|
||||
dt = datetime.fromisoformat(utc_iso_str)
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
|
||||
from datetime import timedelta
|
||||
ist_tz = timezone(timedelta(hours=5, minutes=30))
|
||||
local_dt = dt.astimezone(ist_tz)
|
||||
return local_dt.strftime("%d-%b-%Y %I:%M %p IST")
|
||||
except Exception:
|
||||
return utc_iso_str
|
||||
@@ -0,0 +1,590 @@
|
||||
"""
|
||||
exporter.py
|
||||
|
||||
Exports markdown blog articles to clean, professional Microsoft Word (.docx)
|
||||
and Adobe PDF (.pdf) documents.
|
||||
|
||||
Excludes evaluator scores, metrics, radar charts, and pipeline logs.
|
||||
Includes styled headings, paragraphs, formatted lists, tables, callouts, and embedded images.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from PIL import Image as PILImage
|
||||
|
||||
# ── Clean / Sanitization Helper ───────────────────────────────────────────────
|
||||
|
||||
def clean_blog_markdown(markdown: str) -> str:
|
||||
"""
|
||||
Strips internal evaluation scores, baseline comparison tables,
|
||||
JSON score blocks, and pipeline metadata from the markdown text.
|
||||
"""
|
||||
if not markdown:
|
||||
return ""
|
||||
|
||||
text = markdown.strip()
|
||||
|
||||
# Remove JSON score blocks (e.g. ```json ... "language_score": ... ```)
|
||||
text = re.sub(r"```json\s*\{[\s\S]*?\}\s*```", "", text, flags=re.IGNORECASE)
|
||||
|
||||
# Remove score table markers or evaluation summaries if present
|
||||
patterns = [
|
||||
r"###?\s*Evaluator Scores[\s\S]*?(?=\n##|\Z)",
|
||||
r"###?\s*Baseline Scores[\s\S]*?(?=\n##|\Z)",
|
||||
r"###?\s*Evaluation Summary[\s\S]*?(?=\n##|\Z)",
|
||||
r"<table[\s\S]*?class=['\"]sct['\"][\s\S]*?</table>",
|
||||
]
|
||||
for pattern in patterns:
|
||||
text = re.sub(pattern, "", text, flags=re.IGNORECASE)
|
||||
|
||||
# Clean redundant blank lines
|
||||
text = re.sub(r"\n{3,}", "\n\n", text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def _resolve_image_path(img_ref: str) -> Optional[Path]:
|
||||
"""
|
||||
Resolves local file paths or downloads remote web image URLs (with caching)
|
||||
so images can be embedded directly into PDF and Word exports.
|
||||
"""
|
||||
clean_ref = img_ref.strip().strip("'").strip('"')
|
||||
if not clean_ref:
|
||||
return None
|
||||
|
||||
# 1. Handle HTTP / HTTPS remote image URLs
|
||||
if clean_ref.startswith(("http://", "https://")):
|
||||
try:
|
||||
import hashlib
|
||||
import requests
|
||||
cache_dir = Path.cwd() / "data" / "img_cache"
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
url_hash = hashlib.md5(clean_ref.encode("utf-8")).hexdigest()
|
||||
ext = ".jpg"
|
||||
if ".png" in clean_ref.lower():
|
||||
ext = ".png"
|
||||
elif ".webp" in clean_ref.lower():
|
||||
ext = ".webp"
|
||||
cached_file = cache_dir / f"{url_hash}{ext}"
|
||||
if cached_file.exists() and cached_file.stat().st_size > 500:
|
||||
return cached_file
|
||||
|
||||
resp = requests.get(clean_ref, timeout=8, headers={"User-Agent": "Mozilla/5.0"})
|
||||
if resp.status_code == 200 and len(resp.content) > 500:
|
||||
cached_file.write_bytes(resp.content)
|
||||
return cached_file
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2. Handle Local File Paths
|
||||
p = Path(clean_ref)
|
||||
if p.exists() and p.is_file():
|
||||
return p
|
||||
|
||||
# Check relative to workspace root or generated_images
|
||||
candidates = [
|
||||
Path.cwd() / clean_ref,
|
||||
Path.cwd() / "generated_images" / clean_ref,
|
||||
Path.cwd() / "generated_images" / p.name,
|
||||
Path.cwd() / "data" / "custom_images" / p.name,
|
||||
Path.cwd() / "data" / "img_cache" / p.name,
|
||||
]
|
||||
for cand in candidates:
|
||||
if cand.exists() and cand.is_file():
|
||||
return cand
|
||||
return None
|
||||
|
||||
|
||||
# ── DOCX Export ───────────────────────────────────────────────────────────────
|
||||
|
||||
def export_to_docx(markdown_text: str, title: str = "Blog Article", default_title: str = "Blog Article") -> bytes:
|
||||
"""
|
||||
Converts markdown blog text into a styled Microsoft Word (.docx) document.
|
||||
Returns bytes suitable for downloading via Streamlit.
|
||||
"""
|
||||
from docx import Document
|
||||
from docx.shared import Inches, Pt, RGBColor
|
||||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||
|
||||
doc_title = title or default_title or "Blog Article"
|
||||
cleaned = clean_blog_markdown(markdown_text)
|
||||
doc = Document()
|
||||
|
||||
# Set standard margins (1 inch)
|
||||
for section in doc.sections:
|
||||
section.top_margin = Inches(1.0)
|
||||
section.bottom_margin = Inches(1.0)
|
||||
section.left_margin = Inches(1.0)
|
||||
section.right_margin = Inches(1.0)
|
||||
|
||||
# Palette
|
||||
COLOR_PRIMARY = RGBColor(15, 23, 42) # Slate 900
|
||||
COLOR_SECONDARY = RGBColor(30, 41, 59) # Slate 800
|
||||
COLOR_MUTED = RGBColor(100, 116, 139) # Slate 500
|
||||
COLOR_BODY = RGBColor(30, 41, 59)
|
||||
|
||||
# Configure Normal Style
|
||||
normal_style = doc.styles["Normal"]
|
||||
normal_style.font.name = "Calibri"
|
||||
normal_style.font.size = Pt(11)
|
||||
normal_style.font.color.rgb = COLOR_BODY
|
||||
|
||||
lines = cleaned.splitlines()
|
||||
i = 0
|
||||
in_code_block = False
|
||||
code_lines = []
|
||||
|
||||
def _add_styled_inline(paragraph, text: str, italic: bool = False):
|
||||
"""Parse basic bold/italic inline markdown in paragraph."""
|
||||
tokens = re.split(r"(\*\*.*?\*\*|\*.*?\*|`.*?`)", text)
|
||||
for tok in tokens:
|
||||
if not tok:
|
||||
continue
|
||||
if tok.startswith("**") and tok.endswith("**") and len(tok) >= 4:
|
||||
run = paragraph.add_run(tok[2:-2])
|
||||
run.bold = True
|
||||
if italic:
|
||||
run.italic = True
|
||||
elif tok.startswith("*") and tok.endswith("*") and len(tok) >= 2:
|
||||
run = paragraph.add_run(tok[1:-1])
|
||||
run.italic = True
|
||||
elif tok.startswith("`") and tok.endswith("`") and len(tok) >= 2:
|
||||
run = paragraph.add_run(tok[1:-1])
|
||||
run.font.name = "Consolas"
|
||||
run.font.size = Pt(10)
|
||||
run.font.color.rgb = RGBColor(180, 83, 9)
|
||||
else:
|
||||
run = paragraph.add_run(tok)
|
||||
if italic:
|
||||
run.italic = True
|
||||
|
||||
while i < len(lines):
|
||||
line = lines[i]
|
||||
stripped = line.strip()
|
||||
|
||||
# Handle Code blocks
|
||||
if stripped.startswith("```"):
|
||||
if in_code_block:
|
||||
code_text = "\n".join(code_lines)
|
||||
p = doc.add_paragraph()
|
||||
p.paragraph_format.space_before = Pt(4)
|
||||
p.paragraph_format.space_after = Pt(6)
|
||||
p.paragraph_format.left_indent = Inches(0.3)
|
||||
run = p.add_run(code_text)
|
||||
run.font.name = "Consolas"
|
||||
run.font.size = Pt(9.5)
|
||||
run.font.color.rgb = RGBColor(51, 65, 85)
|
||||
in_code_block = False
|
||||
code_lines = []
|
||||
else:
|
||||
in_code_block = True
|
||||
code_lines = []
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if in_code_block:
|
||||
code_lines.append(line)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Skip empty lines
|
||||
if not stripped:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Image detection: 
|
||||
img_match = re.search(r"^!\[(?P<alt>[^\]]*)\]\((?P<url>[^)]+)\)", stripped)
|
||||
if img_match:
|
||||
alt_text = img_match.group("alt")
|
||||
img_target = img_match.group("url")
|
||||
img_path = _resolve_image_path(img_target)
|
||||
|
||||
if img_path:
|
||||
try:
|
||||
p_img = doc.add_paragraph()
|
||||
p_img.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
p_img.paragraph_format.space_before = Pt(8)
|
||||
p_img.paragraph_format.space_after = Pt(2)
|
||||
run_img = p_img.add_run()
|
||||
run_img.add_picture(str(img_path), width=Inches(5.2))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
caption_text = alt_text
|
||||
if i + 1 < len(lines) and lines[i+1].strip().startswith("*") and lines[i+1].strip().endswith("*"):
|
||||
i += 1
|
||||
caption_text = lines[i].strip().strip("*").strip()
|
||||
|
||||
if caption_text:
|
||||
p_cap = doc.add_paragraph()
|
||||
p_cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
p_cap.paragraph_format.space_before = Pt(0)
|
||||
p_cap.paragraph_format.space_after = Pt(8)
|
||||
run_cap = p_cap.add_run(caption_text)
|
||||
run_cap.italic = True
|
||||
run_cap.font.size = Pt(9.5)
|
||||
run_cap.font.color.rgb = COLOR_MUTED
|
||||
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Headings
|
||||
if stripped.startswith("# "):
|
||||
h = doc.add_heading(level=1)
|
||||
h.paragraph_format.space_before = Pt(16)
|
||||
h.paragraph_format.space_after = Pt(6)
|
||||
h.paragraph_format.keep_with_next = True
|
||||
run = h.add_run(stripped[2:].strip())
|
||||
run.font.name = "Calibri"
|
||||
run.font.size = Pt(20)
|
||||
run.font.bold = True
|
||||
run.font.color.rgb = COLOR_PRIMARY
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if stripped.startswith("## "):
|
||||
h = doc.add_heading(level=2)
|
||||
h.paragraph_format.space_before = Pt(14)
|
||||
h.paragraph_format.space_after = Pt(4)
|
||||
h.paragraph_format.keep_with_next = True
|
||||
run = h.add_run(stripped[3:].strip())
|
||||
run.font.name = "Calibri"
|
||||
run.font.size = Pt(15)
|
||||
run.font.bold = True
|
||||
run.font.color.rgb = COLOR_SECONDARY
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if stripped.startswith("### "):
|
||||
h = doc.add_heading(level=3)
|
||||
h.paragraph_format.space_before = Pt(10)
|
||||
h.paragraph_format.space_after = Pt(3)
|
||||
h.paragraph_format.keep_with_next = True
|
||||
run = h.add_run(stripped[4:].strip())
|
||||
run.font.name = "Calibri"
|
||||
run.font.size = Pt(13)
|
||||
run.font.bold = True
|
||||
run.font.color.rgb = COLOR_SECONDARY
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Bullet List Items
|
||||
if stripped.startswith(("- ", "* ", "+ ")):
|
||||
p = doc.add_paragraph(style="List Bullet")
|
||||
p.paragraph_format.space_before = Pt(0)
|
||||
p.paragraph_format.space_after = Pt(3)
|
||||
_add_styled_inline(p, stripped[2:].strip())
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Numbered List Items
|
||||
num_match = re.match(r"^(\d+)\.\s+(.*)", stripped)
|
||||
if num_match:
|
||||
p = doc.add_paragraph(style="List Number")
|
||||
p.paragraph_format.space_before = Pt(0)
|
||||
p.paragraph_format.space_after = Pt(3)
|
||||
_add_styled_inline(p, num_match.group(2).strip())
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Blockquote
|
||||
if stripped.startswith(">"):
|
||||
p = doc.add_paragraph()
|
||||
p.paragraph_format.left_indent = Inches(0.4)
|
||||
p.paragraph_format.space_before = Pt(4)
|
||||
p.paragraph_format.space_after = Pt(6)
|
||||
_add_styled_inline(p, stripped[1:].strip(), italic=True)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Regular Paragraph
|
||||
p = doc.add_paragraph()
|
||||
p.paragraph_format.space_before = Pt(0)
|
||||
p.paragraph_format.space_after = Pt(6)
|
||||
p.paragraph_format.line_spacing = 1.15
|
||||
_add_styled_inline(p, stripped)
|
||||
i += 1
|
||||
|
||||
buffer = io.BytesIO()
|
||||
doc.save(buffer)
|
||||
buffer.seek(0)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
# ── PDF Export ────────────────────────────────────────────────────────────────
|
||||
|
||||
def export_to_pdf(markdown_text: str, title: str = "Blog Article", default_title: str = "Blog Article") -> bytes:
|
||||
"""
|
||||
Converts markdown blog text into a publication-quality PDF document.
|
||||
Returns bytes suitable for downloading via Streamlit.
|
||||
"""
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib import colors
|
||||
from reportlab.platypus import (
|
||||
SimpleDocTemplate, Paragraph, Spacer, Image as RLImage, KeepTogether
|
||||
)
|
||||
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
||||
from reportlab.lib.enums import TA_CENTER, TA_LEFT
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
doc_title = title or default_title or "Blog Article"
|
||||
cleaned = clean_blog_markdown(markdown_text)
|
||||
|
||||
class NumberedCanvas(canvas.Canvas):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._saved_page_states = []
|
||||
|
||||
def showPage(self):
|
||||
self._saved_page_states.append(dict(self.__dict__))
|
||||
self._startPage()
|
||||
|
||||
def save(self):
|
||||
num_pages = len(self._saved_page_states)
|
||||
for state in self._saved_page_states:
|
||||
self.__dict__.update(state)
|
||||
self.draw_page_number(num_pages)
|
||||
super().showPage()
|
||||
super().save()
|
||||
|
||||
def draw_page_number(self, page_count):
|
||||
self.saveState()
|
||||
self.setFont("Helvetica", 8.5)
|
||||
self.setFillColor(colors.HexColor("#64748B"))
|
||||
|
||||
# Header rule & title
|
||||
self.setLineWidth(0.5)
|
||||
self.setStrokeColor(colors.HexColor("#E2E8F0"))
|
||||
self.line(54, 792 - 40, 612 - 54, 792 - 40)
|
||||
self.drawString(54, 792 - 34, default_title[:60])
|
||||
|
||||
# Footer
|
||||
self.line(54, 45, 612 - 54, 45)
|
||||
page_text = f"Page {self._pageNumber} of {page_count}"
|
||||
self.drawRightString(612 - 54, 32, page_text)
|
||||
self.restoreState()
|
||||
|
||||
buffer = io.BytesIO()
|
||||
doc = SimpleDocTemplate(
|
||||
buffer,
|
||||
pagesize=letter,
|
||||
leftMargin=54,
|
||||
rightMargin=54,
|
||||
topMargin=54,
|
||||
bottomMargin=54,
|
||||
)
|
||||
|
||||
styles = getSampleStyleSheet()
|
||||
|
||||
style_title = ParagraphStyle(
|
||||
"BlogTitle",
|
||||
parent=styles["Heading1"],
|
||||
fontName="Helvetica-Bold",
|
||||
fontSize=20,
|
||||
leading=24,
|
||||
textColor=colors.HexColor("#0F172A"),
|
||||
spaceBefore=10,
|
||||
spaceAfter=10,
|
||||
alignment=TA_LEFT,
|
||||
)
|
||||
style_h2 = ParagraphStyle(
|
||||
"BlogH2",
|
||||
parent=styles["Heading2"],
|
||||
fontName="Helvetica-Bold",
|
||||
fontSize=14,
|
||||
leading=18,
|
||||
textColor=colors.HexColor("#1E293B"),
|
||||
spaceBefore=12,
|
||||
spaceAfter=5,
|
||||
keepWithNext=True,
|
||||
)
|
||||
style_h3 = ParagraphStyle(
|
||||
"BlogH3",
|
||||
parent=styles["Heading3"],
|
||||
fontName="Helvetica-Bold",
|
||||
fontSize=11.5,
|
||||
leading=15,
|
||||
textColor=colors.HexColor("#334155"),
|
||||
spaceBefore=9,
|
||||
spaceAfter=3,
|
||||
keepWithNext=True,
|
||||
)
|
||||
style_body = ParagraphStyle(
|
||||
"BlogBody",
|
||||
parent=styles["Normal"],
|
||||
fontName="Helvetica",
|
||||
fontSize=10,
|
||||
leading=14.5,
|
||||
textColor=colors.HexColor("#1E293B"),
|
||||
spaceBefore=0,
|
||||
spaceAfter=6,
|
||||
alignment=TA_LEFT,
|
||||
)
|
||||
style_bullet = ParagraphStyle(
|
||||
"BlogBullet",
|
||||
parent=style_body,
|
||||
leftIndent=15,
|
||||
firstLineIndent=-10,
|
||||
spaceAfter=3,
|
||||
)
|
||||
style_caption = ParagraphStyle(
|
||||
"BlogCaption",
|
||||
parent=styles["Italic"],
|
||||
fontName="Helvetica-Oblique",
|
||||
fontSize=8.5,
|
||||
leading=11,
|
||||
textColor=colors.HexColor("#64748B"),
|
||||
alignment=TA_CENTER,
|
||||
spaceBefore=2,
|
||||
spaceAfter=8,
|
||||
)
|
||||
style_blockquote = ParagraphStyle(
|
||||
"BlogQuote",
|
||||
parent=style_body,
|
||||
fontName="Helvetica-Oblique",
|
||||
leftIndent=20,
|
||||
rightIndent=20,
|
||||
textColor=colors.HexColor("#475569"),
|
||||
spaceBefore=4,
|
||||
spaceAfter=6,
|
||||
)
|
||||
|
||||
def _md_to_rl_xml(text: str) -> str:
|
||||
"""Convert markdown bold/italic/code syntax to ReportLab XML tags."""
|
||||
t = text.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
t = re.sub(r"\*\*(.*?)\*\*", r"<b>\1</b>", t)
|
||||
t = re.sub(r"\*(.*?)\*", r"<i>\1</i>", t)
|
||||
t = re.sub(r"`(.*?)`", r"<font face='Courier' color='#B45309'>\1</font>", t)
|
||||
return t
|
||||
|
||||
story = []
|
||||
lines = cleaned.splitlines()
|
||||
i = 0
|
||||
in_code_block = False
|
||||
code_lines = []
|
||||
|
||||
while i < len(lines):
|
||||
line = lines[i]
|
||||
stripped = line.strip()
|
||||
|
||||
# Handle Code blocks
|
||||
if stripped.startswith("```"):
|
||||
if in_code_block:
|
||||
code_text = "\n".join(code_lines)
|
||||
xml_code = _md_to_rl_xml(code_text)
|
||||
style_code = ParagraphStyle(
|
||||
"BlogCode",
|
||||
parent=styles["Normal"],
|
||||
fontName="Courier",
|
||||
fontSize=8.5,
|
||||
leading=11.5,
|
||||
textColor=colors.HexColor("#334155"),
|
||||
backColor=colors.HexColor("#F8FAFC"),
|
||||
borderPadding=6,
|
||||
spaceBefore=4,
|
||||
spaceAfter=6,
|
||||
)
|
||||
story.append(Paragraph(xml_code.replace("\n", "<br/>"), style_code))
|
||||
in_code_block = False
|
||||
code_lines = []
|
||||
else:
|
||||
in_code_block = True
|
||||
code_lines = []
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if in_code_block:
|
||||
code_lines.append(line)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if not stripped:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Image detection
|
||||
img_match = re.search(r"^!\[(?P<alt>[^\]]*)\]\((?P<url>[^)]+)\)", stripped)
|
||||
if img_match:
|
||||
alt_text = img_match.group("alt")
|
||||
img_target = img_match.group("url")
|
||||
img_path = _resolve_image_path(img_target)
|
||||
|
||||
caption_text = alt_text
|
||||
if i + 1 < len(lines) and lines[i+1].strip().startswith("*") and lines[i+1].strip().endswith("*"):
|
||||
i += 1
|
||||
caption_text = lines[i].strip().strip("*").strip()
|
||||
|
||||
if img_path:
|
||||
try:
|
||||
with PILImage.open(str(img_path)) as pil_img:
|
||||
orig_w, orig_h = pil_img.size
|
||||
|
||||
max_w = 460
|
||||
max_h = 260
|
||||
scale = min(max_w / orig_w, max_h / orig_h, 1.0)
|
||||
target_w = orig_w * scale
|
||||
target_h = orig_h * scale
|
||||
|
||||
img_flow = RLImage(str(img_path), width=target_w, height=target_h)
|
||||
img_flow.hAlign = "CENTER"
|
||||
|
||||
img_elements = [Spacer(1, 4), img_flow]
|
||||
if caption_text:
|
||||
img_elements.append(Paragraph(_md_to_rl_xml(caption_text), style_caption))
|
||||
story.append(KeepTogether(img_elements))
|
||||
except Exception:
|
||||
pass
|
||||
elif caption_text:
|
||||
story.append(Paragraph(_md_to_rl_xml(f"[{caption_text}]"), style_caption))
|
||||
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Headings
|
||||
if stripped.startswith("# "):
|
||||
story.append(Paragraph(_md_to_rl_xml(stripped[2:].strip()), style_title))
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if stripped.startswith("## "):
|
||||
story.append(Paragraph(_md_to_rl_xml(stripped[3:].strip()), style_h2))
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if stripped.startswith("### "):
|
||||
story.append(Paragraph(_md_to_rl_xml(stripped[4:].strip()), style_h3))
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Bullet List Items
|
||||
if stripped.startswith(("- ", "* ", "+ ")):
|
||||
item_text = f"• {_md_to_rl_xml(stripped[2:].strip())}"
|
||||
story.append(Paragraph(item_text, style_bullet))
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Numbered List Items
|
||||
num_match = re.match(r"^(\d+)\.\s+(.*)", stripped)
|
||||
if num_match:
|
||||
item_text = f"{num_match.group(1)}. {_md_to_rl_xml(num_match.group(2).strip())}"
|
||||
story.append(Paragraph(item_text, style_bullet))
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Blockquote
|
||||
if stripped.startswith(">"):
|
||||
story.append(Paragraph(_md_to_rl_xml(stripped[1:].strip()), style_blockquote))
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Normal Paragraph
|
||||
story.append(Paragraph(_md_to_rl_xml(stripped), style_body))
|
||||
i += 1
|
||||
|
||||
doc.build(story, canvasmaker=NumberedCanvas)
|
||||
buffer.seek(0)
|
||||
return buffer.getvalue()
|
||||
@@ -0,0 +1,5 @@
|
||||
import uuid
|
||||
|
||||
def unique_id():
|
||||
|
||||
return str(uuid.uuid4())
|
||||
@@ -0,0 +1,103 @@
|
||||
import re
|
||||
|
||||
|
||||
def ensure_exact_images_in_markdown(text: str, image_output: list[dict]) -> str:
|
||||
"""
|
||||
Guarantees that:
|
||||
1. Zero duplicate images exist in the markdown article (same URL or duplicate embed removed).
|
||||
2. Exactly all N images in image_output are contextually embedded in distinct body sections.
|
||||
3. Missing images from LLM output are automatically inserted into relevant sections.
|
||||
"""
|
||||
if not text or not image_output:
|
||||
return text
|
||||
|
||||
# 1. Deduplicate any repeated image embeds in text
|
||||
seen_urls = set()
|
||||
|
||||
def _dedup_img(match):
|
||||
alt = match.group(1)
|
||||
url = match.group(2)
|
||||
if url in seen_urls:
|
||||
return "" # strip duplicate
|
||||
seen_urls.add(url)
|
||||
return match.group(0)
|
||||
|
||||
text = re.sub(r"!\[(.*?)\]\((.*?)\)", _dedup_img, text)
|
||||
|
||||
# 2. Check which images from image_output are missing
|
||||
missing = []
|
||||
for idx, img in enumerate(image_output):
|
||||
u = img.get("url", "")
|
||||
lp = img.get("local_path", "")
|
||||
ru = img.get("remote_url", "") or img.get("source_url", "")
|
||||
found = False
|
||||
for target in [u, lp, ru]:
|
||||
if target and target in text:
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
missing.append((idx, img))
|
||||
|
||||
if not missing:
|
||||
return text
|
||||
|
||||
# 3. Insert missing images into distinct body sections
|
||||
sections = re.split(r"(?=\n##\s+)", text)
|
||||
if len(sections) > 1:
|
||||
sec_idx = 1
|
||||
for idx, img in missing:
|
||||
alt = img.get("alt") or img.get("section") or f"Visual Analysis {idx+1}"
|
||||
img_url = img.get("url") or img.get("local_path") or img.get("remote_url")
|
||||
cap = img.get("caption") or alt
|
||||
is_custom = img.get("is_custom", False)
|
||||
src = img.get("source_url") or img.get("remote_url") or ""
|
||||
|
||||
if is_custom or src == "Custom Image" or src == "Custom Upload":
|
||||
caption_line = f"\n\n*Figure {idx+1}: {cap} (Source: Custom Upload)*\n"
|
||||
elif src and "http" in src:
|
||||
src_domain = src.split("/")[2] if "//" in src else src
|
||||
caption_line = f"\n\n*Figure {idx+1}: {cap} (Source: [{src_domain}]({src}))*\n"
|
||||
else:
|
||||
caption_line = f"\n\n*Figure {idx+1}: {cap}*\n"
|
||||
|
||||
img_md = f"\n\n" + caption_line
|
||||
|
||||
# Find a body section that matches image section or doesn't have an image
|
||||
target_sec = None
|
||||
target_heading = (img.get("section") or "").lower()
|
||||
|
||||
# First priority: matching section heading
|
||||
if target_heading:
|
||||
for s_i in range(1, len(sections)):
|
||||
sec_header = sections[s_i].splitlines()[0].lower() if sections[s_i].splitlines() else ""
|
||||
if target_heading in sec_header or any(w in sec_header for w in target_heading.split() if len(w) > 3):
|
||||
target_sec = s_i
|
||||
break
|
||||
|
||||
# Second priority: any section without an image (avoiding FAQ and Conclusion)
|
||||
if target_sec is None:
|
||||
for s_i in range(1, len(sections)):
|
||||
sec_header = sections[s_i].splitlines()[0].lower() if sections[s_i].splitlines() else ""
|
||||
if "![" not in sections[s_i] and "faq" not in sec_header and "conclusion" not in sec_header:
|
||||
target_sec = s_i
|
||||
break
|
||||
|
||||
if target_sec is None:
|
||||
target_sec = min(sec_idx, len(sections) - 1)
|
||||
sec_idx += 1
|
||||
|
||||
paragraphs = sections[target_sec].split("\n\n")
|
||||
if len(paragraphs) >= 2:
|
||||
paragraphs.insert(2, img_md.strip())
|
||||
else:
|
||||
paragraphs.append(img_md.strip())
|
||||
sections[target_sec] = "\n\n".join(paragraphs)
|
||||
|
||||
text = "".join(sections)
|
||||
else:
|
||||
for idx, img in missing:
|
||||
alt = img.get("alt") or f"Visual Analysis {idx+1}"
|
||||
img_url = img.get("url") or img.get("local_path") or img.get("remote_url")
|
||||
text += f"\n\n\n"
|
||||
|
||||
return text
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
job_writer.py — writes live generation progress to SQLite.
|
||||
|
||||
The background thread calls JobWriter.tick() every ~0.5 s and
|
||||
JobWriter.append_stream() on every token. The UI reads from
|
||||
the jobs table via BlogDatabase so it survives page refreshes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class JobWriter:
|
||||
"""
|
||||
Thread-safe progress writer for a single generation job.
|
||||
|
||||
Usage:
|
||||
jw = JobWriter(db, job_id)
|
||||
jw.start() # starts background flush thread
|
||||
jw.set_agent("supervisor", 17) # update active agent + progress %
|
||||
jw.append_stream("token") # accumulate streamed text
|
||||
jw.stop(run_id=42) # mark complete, stop flush thread
|
||||
jw.stop(error="something went wrong") # mark failed
|
||||
"""
|
||||
|
||||
_FLUSH_INTERVAL = 0.8 # seconds between DB writes
|
||||
|
||||
def __init__(self, db, job_id: int):
|
||||
self._db = db
|
||||
self._job_id = job_id
|
||||
self._agent = ""
|
||||
self._pct = 0
|
||||
self._stream = ""
|
||||
self._title = ""
|
||||
self._lock = threading.Lock()
|
||||
self._running = False
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
|
||||
# ── Public API ────────────────────────────────────────────────────────────
|
||||
|
||||
@property
|
||||
def job_id(self) -> int:
|
||||
return self._job_id
|
||||
|
||||
def start(self) -> None:
|
||||
self._running = True
|
||||
self._thread = threading.Thread(target=self._flush_loop, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def set_agent(self, agent: str, pct: int) -> None:
|
||||
with self._lock:
|
||||
self._agent = agent
|
||||
self._pct = pct
|
||||
|
||||
def set_title(self, title: str) -> None:
|
||||
with self._lock:
|
||||
self._title = title
|
||||
|
||||
def append_stream(self, token: str) -> None:
|
||||
with self._lock:
|
||||
self._stream += token
|
||||
|
||||
def is_cancel_requested(self) -> bool:
|
||||
return self._db.is_cancel_requested(self._job_id)
|
||||
|
||||
def stop(self, run_id: Optional[int] = None, error: str = "") -> None:
|
||||
self._running = False
|
||||
if self._thread:
|
||||
self._thread.join(timeout=3)
|
||||
# Final flush
|
||||
with self._lock:
|
||||
agent, pct, stream, title = self._agent, self._pct, self._stream, self._title
|
||||
self._db.update_job(self._job_id,
|
||||
active_agent=agent,
|
||||
progress_pct=pct,
|
||||
streamed_text=stream,
|
||||
title=title)
|
||||
self._db.finish_job(self._job_id, run_id=run_id, error=error)
|
||||
|
||||
# ── Internal ─────────────────────────────────────────────────────────────
|
||||
|
||||
def _flush_loop(self) -> None:
|
||||
while self._running:
|
||||
with self._lock:
|
||||
agent, pct, stream, title = self._agent, self._pct, self._stream, self._title
|
||||
try:
|
||||
self._db.update_job(self._job_id,
|
||||
active_agent=agent,
|
||||
progress_pct=pct,
|
||||
streamed_text=stream,
|
||||
title=title)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(self._FLUSH_INTERVAL)
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
Robust JSON extraction utility.
|
||||
|
||||
Models sometimes wrap JSON in markdown fences, add preamble text, or return
|
||||
partial JSON. This module strips all of that and falls back gracefully rather
|
||||
than raising an OutputParserException.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
|
||||
|
||||
def _strip_fences(text: str) -> str:
|
||||
"""Remove ```json ... ``` or ``` ... ``` wrappers."""
|
||||
# Match ```json\n...\n``` or ```\n...\n```
|
||||
fenced = re.search(r"```(?:json)?\s*\n?(.*?)\n?```", text, re.DOTALL)
|
||||
if fenced:
|
||||
return fenced.group(1).strip()
|
||||
return text.strip()
|
||||
|
||||
|
||||
def _extract_json_object(text: str) -> str:
|
||||
"""
|
||||
Find the first {...} block in text, handling nested braces.
|
||||
Returns the raw JSON string, or the original text if no block found.
|
||||
"""
|
||||
start = text.find("{")
|
||||
if start == -1:
|
||||
return text
|
||||
|
||||
depth = 0
|
||||
in_string = False
|
||||
escape_next = False
|
||||
|
||||
for i, ch in enumerate(text[start:], start=start):
|
||||
if escape_next:
|
||||
escape_next = False
|
||||
continue
|
||||
if ch == "\\" and in_string:
|
||||
escape_next = True
|
||||
continue
|
||||
if ch == '"':
|
||||
in_string = not in_string
|
||||
continue
|
||||
if in_string:
|
||||
continue
|
||||
if ch == "{":
|
||||
depth += 1
|
||||
elif ch == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return text[start : i + 1]
|
||||
|
||||
return text[start:]
|
||||
|
||||
|
||||
def load_json(text) -> dict:
|
||||
"""
|
||||
Parse JSON from an LLM response string or structured content list.
|
||||
|
||||
Handles:
|
||||
- Plain JSON
|
||||
- JSON wrapped in ```json ... ``` fences
|
||||
- JSON with leading/trailing prose
|
||||
- Partial or malformed JSON (returns {} instead of raising)
|
||||
"""
|
||||
if isinstance(text, list):
|
||||
extracted = []
|
||||
for item in text:
|
||||
if isinstance(item, dict) and "text" in item:
|
||||
extracted.append(item["text"])
|
||||
elif isinstance(item, str):
|
||||
extracted.append(item)
|
||||
text = "\n".join(extracted)
|
||||
elif not isinstance(text, str):
|
||||
text = str(text)
|
||||
if not text or not text.strip():
|
||||
return {}
|
||||
|
||||
# Try the raw text first (cheapest path)
|
||||
try:
|
||||
return json.loads(text.strip())
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
# Strip markdown fences and retry
|
||||
stripped = _strip_fences(text)
|
||||
try:
|
||||
return json.loads(stripped)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
# Extract the first {...} block and retry
|
||||
extracted = _extract_json_object(stripped)
|
||||
try:
|
||||
return json.loads(extracted)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
# Last resort: try the raw extracted block from original text
|
||||
extracted_raw = _extract_json_object(text)
|
||||
try:
|
||||
return json.loads(extracted_raw)
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
@@ -0,0 +1,5 @@
|
||||
from markdownify import markdownify
|
||||
|
||||
def html_to_markdown(html):
|
||||
|
||||
return markdownify(html)
|
||||
@@ -0,0 +1,247 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
MEMORY_DIR = Path(__file__).resolve().parents[1] / ".memory"
|
||||
RESEARCH_CACHE_PATH = MEMORY_DIR / "research_cache.json"
|
||||
|
||||
BLOG_PROMPT_LIMIT = 6000
|
||||
RESEARCH_PROMPT_LIMIT = 3500
|
||||
MEMORY_PROMPT_LIMIT = 1800
|
||||
AGENT_OUTPUT_PROMPT_LIMIT = 2200
|
||||
PLAN_PROMPT_LIMIT = 1600
|
||||
|
||||
|
||||
def _now():
|
||||
return datetime.utcnow().isoformat(timespec="seconds") + "Z"
|
||||
|
||||
|
||||
def compact_text(value: Any, limit: int = 1800):
|
||||
if value is None:
|
||||
return ""
|
||||
|
||||
if isinstance(value, str):
|
||||
text = value
|
||||
else:
|
||||
try:
|
||||
text = json.dumps(value, ensure_ascii=True, indent=2)
|
||||
except TypeError:
|
||||
text = str(value)
|
||||
|
||||
text = " ".join(text.split())
|
||||
|
||||
if len(text) <= limit:
|
||||
return text
|
||||
|
||||
return f"{text[:limit].rstrip()}..."
|
||||
|
||||
|
||||
def memory_brief(state: Any, agent: str | None = None):
|
||||
agent_issues = unresolved_issues(state, agent) if agent else unresolved_issues(state)
|
||||
|
||||
sections = [
|
||||
("Context Memory", state.context_memory),
|
||||
("Research Memory", state.research_memory),
|
||||
("Working Memory", state.working_memory),
|
||||
("Evaluation Memory", state.evaluation_memory[-3:]),
|
||||
("Retry History", state.retry_history),
|
||||
("Open Issues", agent_issues),
|
||||
]
|
||||
|
||||
lines = []
|
||||
|
||||
for label, value in sections:
|
||||
brief = compact_text(value, 1200)
|
||||
|
||||
if brief:
|
||||
lines.append(f"{label}: {brief}")
|
||||
|
||||
return "\n".join(lines) or "No memory recorded yet."
|
||||
|
||||
|
||||
def prompt_inputs(state: Any, agent: str | None = None):
|
||||
return {
|
||||
"blog": compact_text(state.cleaned_blog, BLOG_PROMPT_LIMIT),
|
||||
"research": compact_text(state.research_output, RESEARCH_PROMPT_LIMIT),
|
||||
"plan": compact_text(state.planner_output, PLAN_PROMPT_LIMIT),
|
||||
"memory": compact_text(memory_brief(state, agent), MEMORY_PROMPT_LIMIT),
|
||||
}
|
||||
|
||||
|
||||
def build_context_memory(learner_output: dict[str, Any]):
|
||||
fields = [
|
||||
"title",
|
||||
"summary",
|
||||
"audience",
|
||||
"intent",
|
||||
"tone",
|
||||
"writing_style",
|
||||
"seo_intent",
|
||||
"primary_keywords",
|
||||
"secondary_keywords",
|
||||
"structure",
|
||||
]
|
||||
|
||||
return {
|
||||
key: learner_output.get(key)
|
||||
for key in fields
|
||||
if learner_output.get(key) not in (None, "", [], {})
|
||||
}
|
||||
|
||||
|
||||
def record_working_memory(state: Any, agent: str, observations: Any):
|
||||
entries = state.working_memory.setdefault(agent, [])
|
||||
entries.append(
|
||||
{
|
||||
"iteration": state.iteration,
|
||||
"created_at": _now(),
|
||||
"observations": compact_text(observations, 1200),
|
||||
}
|
||||
)
|
||||
state.working_memory[agent] = entries[-5:]
|
||||
|
||||
|
||||
def add_evaluation_memory(state: Any, result: dict[str, Any]):
|
||||
scores = {
|
||||
"language": state.language_score,
|
||||
"facts": state.facts_score,
|
||||
"structure": state.structure_score,
|
||||
"seo": state.seo_score,
|
||||
"geo": state.geo_score,
|
||||
"freshness": state.freshness_score,
|
||||
"overall": state.overall_score,
|
||||
}
|
||||
feedback = {
|
||||
"language": state.language_feedback,
|
||||
"facts": state.facts_feedback,
|
||||
"structure": state.structure_feedback,
|
||||
"seo": state.seo_feedback,
|
||||
"geo": state.geo_feedback,
|
||||
"freshness": state.freshness_feedback,
|
||||
}
|
||||
|
||||
state.evaluation_memory.append(
|
||||
{
|
||||
"iteration": state.iteration,
|
||||
"created_at": _now(),
|
||||
"scores": scores,
|
||||
"feedback": feedback,
|
||||
"raw_result": result,
|
||||
}
|
||||
)
|
||||
state.evaluation_memory = state.evaluation_memory[-8:]
|
||||
|
||||
|
||||
def build_issue_memory(state: Any, result: dict[str, Any]):
|
||||
issues = result.get("issues") or result.get("issue_memory") or []
|
||||
|
||||
if isinstance(issues, dict):
|
||||
issues = list(issues.values())
|
||||
|
||||
normalized = []
|
||||
|
||||
if isinstance(issues, list):
|
||||
for index, issue in enumerate(issues, start=1):
|
||||
if not isinstance(issue, dict):
|
||||
continue
|
||||
|
||||
agent = str(issue.get("agent") or issue.get("category") or "").lower()
|
||||
agent = agent.replace("_agent", "").replace(" agent", "").strip()
|
||||
|
||||
if agent not in {"language", "facts", "structure", "seo", "geo", "freshness", "researcher"}:
|
||||
agent = "researcher" if agent == "research" else agent
|
||||
|
||||
normalized.append(
|
||||
{
|
||||
"id": issue.get("id") or issue.get("issue_id") or f"ISSUE-{index:03d}",
|
||||
"agent": agent or "optimizer",
|
||||
"severity": issue.get("severity") or "medium",
|
||||
"location": issue.get("location") or "",
|
||||
"problem": issue.get("problem") or issue.get("feedback") or issue.get("description") or "",
|
||||
"status": issue.get("status") or "open",
|
||||
"iteration": state.iteration,
|
||||
}
|
||||
)
|
||||
|
||||
feedback_by_agent = {
|
||||
"language": (state.language_score, state.language_feedback),
|
||||
"facts": (state.facts_score, state.facts_feedback),
|
||||
"structure": (state.structure_score, state.structure_feedback),
|
||||
"seo": (state.seo_score, state.seo_feedback),
|
||||
"geo": (state.geo_score, state.geo_feedback),
|
||||
"researcher": (state.freshness_score, state.freshness_feedback),
|
||||
}
|
||||
|
||||
existing_agents = {issue["agent"] for issue in normalized if issue.get("status") == "open"}
|
||||
|
||||
for agent, (score, feedback) in feedback_by_agent.items():
|
||||
if score and score < 70 and feedback and agent not in existing_agents:
|
||||
normalized.append(
|
||||
{
|
||||
"id": f"{agent.upper()}-{state.iteration + 1:03d}",
|
||||
"agent": agent,
|
||||
"severity": "high" if score < 50 else "medium",
|
||||
"location": "",
|
||||
"problem": feedback,
|
||||
"status": "open",
|
||||
"iteration": state.iteration,
|
||||
}
|
||||
)
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def unresolved_issues(state: Any, agent: str | None = None):
|
||||
issues = [
|
||||
issue
|
||||
for issue in state.issue_memory
|
||||
if str(issue.get("status", "open")).lower() == "open"
|
||||
]
|
||||
|
||||
if agent:
|
||||
issues = [
|
||||
issue
|
||||
for issue in issues
|
||||
if str(issue.get("agent", "")).lower() == agent.lower()
|
||||
]
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def increment_retry(state: Any, agent: str):
|
||||
state.retry_history[agent] = int(state.retry_history.get(agent, 0)) + 1
|
||||
|
||||
|
||||
def research_cache_key(query: str):
|
||||
return hashlib.sha256(query.strip().lower().encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _load_research_cache():
|
||||
try:
|
||||
return json.loads(RESEARCH_CACHE_PATH.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return {}
|
||||
|
||||
|
||||
def get_cached_research(query: str):
|
||||
cache = _load_research_cache()
|
||||
return cache.get(research_cache_key(query))
|
||||
|
||||
|
||||
def set_cached_research(query: str, value: dict[str, Any]):
|
||||
MEMORY_DIR.mkdir(parents=True, exist_ok=True)
|
||||
cache = _load_research_cache()
|
||||
cache[research_cache_key(query)] = {
|
||||
**value,
|
||||
"query": query,
|
||||
"cached_at": _now(),
|
||||
}
|
||||
RESEARCH_CACHE_PATH.write_text(
|
||||
json.dumps(cache, ensure_ascii=True, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
if __package__ is None or __package__ == "":
|
||||
sys.path.append(str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from langchain_core.output_parsers import JsonOutputParser
|
||||
|
||||
from utilis.schemas import *
|
||||
|
||||
learner_parser = JsonOutputParser(
|
||||
pydantic_object=LearnerSchema
|
||||
)
|
||||
|
||||
planner_parser = JsonOutputParser(
|
||||
pydantic_object=PlannerSchema
|
||||
)
|
||||
|
||||
research_parser = JsonOutputParser(
|
||||
pydantic_object=ResearchSchema
|
||||
)
|
||||
|
||||
evaluation_parser = JsonOutputParser(
|
||||
pydantic_object=EvaluationSchema
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
if __package__ is None or __package__ == "":
|
||||
sys.path.append(str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
PROMPT_DIR = Path(__file__).resolve().parents[1] / "prompts"
|
||||
|
||||
|
||||
def load_prompt(filename: str):
|
||||
|
||||
with open(PROMPT_DIR / filename, "r", encoding="utf8") as f:
|
||||
|
||||
return f.read()
|
||||
@@ -0,0 +1,151 @@
|
||||
"""
|
||||
research_cache.py — in-process semantic research cache.
|
||||
|
||||
Caches the full LLM-synthesised research brief keyed on a normalised hash
|
||||
of the search query. A cosine-similarity check on a lightweight TF-IDF
|
||||
vector catches near-duplicate queries (e.g. "best AI tools for startups" vs
|
||||
"top AI software for startups") and reuses the cached result.
|
||||
|
||||
Cache is in-memory and process-scoped. Entries expire after TTL_SECONDS
|
||||
(default 6 hours). No external dependencies — just stdlib + math.
|
||||
|
||||
Usage:
|
||||
from utilis.research_cache import ResearchCache
|
||||
cache = ResearchCache() # one instance per agent is fine
|
||||
hit = cache.get(query)
|
||||
if hit:
|
||||
return hit
|
||||
result = ... expensive call ...
|
||||
cache.set(query, result)
|
||||
return result
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import math
|
||||
import re
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Configuration
|
||||
# ---------------------------------------------------------------------------
|
||||
TTL_SECONDS = 6 * 3600 # cached results live for 6 hours
|
||||
SIM_THRESHOLD = 0.82 # cosine similarity above this → cache hit
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Lightweight TF-IDF helpers (no external deps)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_STOPWORDS = frozenset(
|
||||
"a an the is are was were be been for of in on at to by and or with "
|
||||
"this that it its as from how what when where who which will can do "
|
||||
"does did not no so but if then than".split()
|
||||
)
|
||||
|
||||
|
||||
def _tokenize(text: str) -> list[str]:
|
||||
text = text.lower()
|
||||
text = re.sub(r"[^a-z0-9\s]", " ", text)
|
||||
return [t for t in text.split() if t and t not in _STOPWORDS]
|
||||
|
||||
|
||||
def _tf(tokens: list[str]) -> dict[str, float]:
|
||||
counts: dict[str, int] = defaultdict(int)
|
||||
for t in tokens:
|
||||
counts[t] += 1
|
||||
total = len(tokens) or 1
|
||||
return {k: v / total for k, v in counts.items()}
|
||||
|
||||
|
||||
def _cosine(a: dict[str, float], b: dict[str, float]) -> float:
|
||||
keys = set(a) | set(b)
|
||||
dot = sum(a.get(k, 0.0) * b.get(k, 0.0) for k in keys)
|
||||
na = math.sqrt(sum(v * v for v in a.values()))
|
||||
nb = math.sqrt(sum(v * v for v in b.values()))
|
||||
if na == 0 or nb == 0:
|
||||
return 0.0
|
||||
return dot / (na * nb)
|
||||
|
||||
|
||||
def _query_vector(query: str) -> dict[str, float]:
|
||||
return _tf(_tokenize(query))
|
||||
|
||||
|
||||
def _query_hash(query: str) -> str:
|
||||
norm = " ".join(_tokenize(query))
|
||||
return hashlib.sha256(norm.encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cache implementation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class ResearchCache:
|
||||
"""
|
||||
Thread-safe in-memory cache for LLM research briefs.
|
||||
|
||||
Each entry stores:
|
||||
- the normalised query vector (for similarity matching)
|
||||
- the cached result string
|
||||
- the expiry timestamp
|
||||
"""
|
||||
|
||||
def __init__(self, ttl: int = TTL_SECONDS, sim_threshold: float = SIM_THRESHOLD):
|
||||
self._ttl = ttl
|
||||
self._threshold = sim_threshold
|
||||
# { hash_key: {"vec": dict, "result": str, "expires": float} }
|
||||
self._store: dict[str, dict] = {}
|
||||
|
||||
def _evict_expired(self) -> None:
|
||||
now = time.time()
|
||||
expired = [k for k, v in self._store.items() if v["expires"] < now]
|
||||
for k in expired:
|
||||
del self._store[k]
|
||||
|
||||
def get(self, query: str) -> str | None:
|
||||
"""
|
||||
Return a cached result if a sufficiently similar query was seen recently,
|
||||
otherwise return None.
|
||||
"""
|
||||
self._evict_expired()
|
||||
if not self._store:
|
||||
return None
|
||||
|
||||
qvec = _query_vector(query)
|
||||
for entry in self._store.values():
|
||||
sim = _cosine(qvec, entry["vec"])
|
||||
if sim >= self._threshold:
|
||||
return entry["result"]
|
||||
return None
|
||||
|
||||
def set(self, query: str, result: str) -> None:
|
||||
"""Store a result for the given query."""
|
||||
key = _query_hash(query)
|
||||
self._store[key] = {
|
||||
"vec": _query_vector(query),
|
||||
"result": result,
|
||||
"expires": time.time() + self._ttl,
|
||||
}
|
||||
|
||||
def clear(self) -> None:
|
||||
self._store.clear()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Module-level singletons — one cache per agent type so they don't
|
||||
# cross-contaminate (research brief vs targeted research brief).
|
||||
# ---------------------------------------------------------------------------
|
||||
_researcher_cache = ResearchCache()
|
||||
_targeted_researcher_cache = ResearchCache()
|
||||
|
||||
|
||||
def get_researcher_cache() -> ResearchCache:
|
||||
return _researcher_cache
|
||||
|
||||
|
||||
def get_targeted_cache() -> ResearchCache:
|
||||
return _targeted_researcher_cache
|
||||
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
invoke_with_retry — the single call-site for all agent LLM calls.
|
||||
|
||||
Works with both RotatingChatGroq (config/llm.py) and OpenAIChatLLM
|
||||
(config/openai_llm.py). Both expose the same interface:
|
||||
- ._client : raw LangChain chat model (used to build the chain)
|
||||
- ._invoke_chain() : rate-limit-aware invocation
|
||||
|
||||
Rebuilds the chain on every call so model rotation is always reflected.
|
||||
Handles the _RotationOccurred sentinel from RotatingChatGroq by rebuilding
|
||||
the chain with the new active model and retrying.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MAX_ROTATIONS = 3 # maximum model switches before giving up
|
||||
|
||||
|
||||
def invoke_with_retry(prompt, llm, inputs: dict):
|
||||
"""
|
||||
Build a fresh chain from prompt + llm._client and invoke it.
|
||||
|
||||
Compatible with any LLM wrapper that exposes:
|
||||
- llm._client (the raw LangChain chat model)
|
||||
- llm._invoke_chain() (rate-limit + rotation aware invoke)
|
||||
|
||||
On TPD/rotation exhaustion (Groq):
|
||||
- RotatingChatGroq raises _RotationOccurred
|
||||
- invoke_with_retry catches it, rebuilds the chain, retries on
|
||||
the new model — up to _MAX_ROTATIONS times
|
||||
|
||||
On TPM exhaustion (Groq):
|
||||
- RotatingChatGroq sleeps internally and retries — nothing to do here
|
||||
|
||||
On 429 rate-limit (OpenAI):
|
||||
- OpenAIChatLLM handles exponential back-off internally
|
||||
|
||||
Args:
|
||||
prompt: LangChain ChatPromptTemplate
|
||||
llm: RotatingChatGroq or OpenAIChatLLM instance from make_llm()
|
||||
inputs: Dict of template variables
|
||||
|
||||
Returns:
|
||||
LangChain AIMessage
|
||||
"""
|
||||
# Import lazily to avoid circular imports; _RotationOccurred only exists
|
||||
# in the Groq path, so we guard with a fallback sentinel.
|
||||
try:
|
||||
from config.llm import _RotationOccurred
|
||||
except ImportError:
|
||||
_RotationOccurred = type("_RotationOccurred", (Exception,), {})
|
||||
|
||||
for rotation_attempt in range(_MAX_ROTATIONS + 1):
|
||||
chain = prompt | llm._client
|
||||
try:
|
||||
response = llm._invoke_chain(chain, inputs)
|
||||
if hasattr(response, "content") and isinstance(response.content, list):
|
||||
extracted = []
|
||||
for item in response.content:
|
||||
if isinstance(item, dict) and "text" in item:
|
||||
extracted.append(item["text"])
|
||||
elif isinstance(item, str):
|
||||
extracted.append(item)
|
||||
response.content = "\n".join(extracted)
|
||||
try:
|
||||
from utilis.token_counter import add_tokens
|
||||
usage = getattr(response, "usage_metadata", None)
|
||||
if isinstance(usage, dict):
|
||||
p_tok = usage.get("input_tokens", 0)
|
||||
c_tok = usage.get("output_tokens", 0)
|
||||
add_tokens(p_tok, c_tok)
|
||||
else:
|
||||
p_tok = len(str(inputs)) // 4
|
||||
c_tok = len(getattr(response, "content", "")) // 4
|
||||
add_tokens(p_tok, c_tok)
|
||||
except Exception:
|
||||
pass
|
||||
return response
|
||||
except _RotationOccurred:
|
||||
if rotation_attempt >= _MAX_ROTATIONS:
|
||||
raise RuntimeError(
|
||||
"All Groq models exhausted their daily quota. "
|
||||
"Try again tomorrow or upgrade your plan."
|
||||
)
|
||||
logger.info(
|
||||
"Model rotated (attempt %d/%d). Rebuilding chain.",
|
||||
rotation_attempt + 1, _MAX_ROTATIONS,
|
||||
)
|
||||
# Loop: chain will be rebuilt with llm._client pointing
|
||||
# to the new active model at the top of the next iteration.
|
||||
@@ -0,0 +1,75 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class LearnerSchema(BaseModel):
|
||||
|
||||
title: str
|
||||
|
||||
summary: str
|
||||
|
||||
audience: str
|
||||
|
||||
intent: str
|
||||
|
||||
tone: str
|
||||
|
||||
writing_style: str
|
||||
|
||||
seo_intent: str
|
||||
|
||||
primary_keywords: list[str]
|
||||
|
||||
secondary_keywords: list[str]
|
||||
|
||||
structure: list[str]
|
||||
|
||||
|
||||
class PlannerSchema(BaseModel):
|
||||
|
||||
strengths: list[str]
|
||||
|
||||
weaknesses: list[str]
|
||||
|
||||
missing_topics: list[str]
|
||||
|
||||
seo_improvements: list[str]
|
||||
|
||||
research_query: str
|
||||
|
||||
missing_statistics: list[str]
|
||||
|
||||
missing_examples: list[str]
|
||||
|
||||
missing_sections: list[str]
|
||||
|
||||
|
||||
class ResearchSchema(BaseModel):
|
||||
|
||||
updated_facts: list[str]
|
||||
|
||||
statistics: list[str]
|
||||
|
||||
examples: list[str]
|
||||
|
||||
seo_keywords: list[str]
|
||||
|
||||
lsi_keywords: list[str]
|
||||
|
||||
faqs: list[str]
|
||||
|
||||
references: list[str]
|
||||
|
||||
|
||||
class EvaluationSchema(BaseModel):
|
||||
|
||||
language: int
|
||||
|
||||
facts: int
|
||||
|
||||
structure: int
|
||||
|
||||
language_feedback: str
|
||||
|
||||
facts_feedback: str
|
||||
|
||||
structure_feedback: str
|
||||
@@ -0,0 +1,20 @@
|
||||
import threading
|
||||
|
||||
_local = threading.local()
|
||||
|
||||
def reset_token_counter():
|
||||
_local.prompt_tokens = 0
|
||||
_local.completion_tokens = 0
|
||||
_local.total_tokens = 0
|
||||
|
||||
def add_tokens(prompt: int, completion: int):
|
||||
if not hasattr(_local, "prompt_tokens"):
|
||||
reset_token_counter()
|
||||
_local.prompt_tokens += prompt
|
||||
_local.completion_tokens += completion
|
||||
_local.total_tokens += (prompt + completion)
|
||||
|
||||
def get_tokens():
|
||||
if not hasattr(_local, "prompt_tokens"):
|
||||
return 0, 0, 0
|
||||
return _local.prompt_tokens, _local.completion_tokens, _local.total_tokens
|
||||
@@ -0,0 +1,12 @@
|
||||
import functools
|
||||
|
||||
def traceable(func=None, **decorator_kwargs):
|
||||
def decorator(f):
|
||||
@functools.wraps(f)
|
||||
def wrapper(*args, **kwargs):
|
||||
return f(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
if func is not None:
|
||||
return decorator(func)
|
||||
return decorator
|
||||
Reference in New Issue
Block a user