diff --git a/app/data/action/create_pdf.py b/app/data/action/create_pdf.py index 1a08c9d8d..1045c2b26 100644 --- a/app/data/action/create_pdf.py +++ b/app/data/action/create_pdf.py @@ -1,6 +1,6 @@ from agent_core import action - - + + @action( name="create_pdf", description=( @@ -114,23 +114,35 @@ def create_pdf_file(input_data: dict) -> dict: # ── Input extraction ────────────────────────────────────────────────── simulated_mode = bool(input_data.get("simulated_mode", False)) - file_path = str(input_data.get("file_path", "")).strip() - content = str(input_data.get("content", "")).strip() - theme = str(input_data.get("theme", "default")).strip().lower() - subtitle = str(input_data.get("subtitle", "")).strip() - page_numbers = bool(input_data.get("page_numbers", True)) - + file_path = str(input_data.get("file_path", "")).strip() + content = str(input_data.get("content", "")).strip() + theme = str(input_data.get("theme", "default")).strip().lower() + subtitle = str(input_data.get("subtitle", "")).strip() + page_numbers = bool(input_data.get("page_numbers", True)) + # ── Validation ──────────────────────────────────────────────────────── if not file_path: - return {"status": "error", "path": "", "message": "The 'file_path' field is required."} + return { + "status": "error", + "path": "", + "message": "The 'file_path' field is required.", + } if not content: - return {"status": "error", "path": "", "message": "The 'content' field is required."} + return { + "status": "error", + "path": "", + "message": "The 'content' field is required.", + } if not file_path.lower().endswith(".pdf"): - return {"status": "error", "path": "", "message": "'file_path' must end with .pdf."} - + return { + "status": "error", + "path": "", + "message": "'file_path' must end with .pdf.", + } + if simulated_mode: return {"status": "success", "path": file_path} - + # ── Imports (executor pre-installs via requirement=, this is a fallback) ── import os import re @@ -138,7 +150,7 @@ def create_pdf_file(input_data: dict) -> dict: import subprocess import importlib from html import unescape - + def _ensure(pkg, import_as=None): try: importlib.import_module(import_as or pkg) @@ -148,74 +160,74 @@ def _ensure(pkg, import_as=None): stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) - + _ensure("markdown2") _ensure("fpdf2", "fpdf") - + import markdown2 from fpdf import FPDF from fpdf.fonts import TextStyle, FontFace from fpdf.pattern import LinearGradient - + # ── Themes ──────────────────────────────────────────────────────────── # Keys: hbg=gradient stop colours, accent=link/highlight colour, # h2/h3=heading colours, body=body text, cbg/cc=code bg/fg, # rule=accent rule below banner, htxt=banner text _THEMES = { "default": { - "hbg": [(30, 58, 138), (79, 70, 229)], + "hbg": [(30, 58, 138), (79, 70, 229)], "accent": (79, 70, 229), - "h2": (30, 58, 138), - "h3": (55, 65, 81), - "body": (31, 41, 55), - "cbg": (243, 244, 246), - "cc": (17, 24, 39), - "rule": (199, 210, 254), - "htxt": (255, 255, 255), + "h2": (30, 58, 138), + "h3": (55, 65, 81), + "body": (31, 41, 55), + "cbg": (243, 244, 246), + "cc": (17, 24, 39), + "rule": (199, 210, 254), + "htxt": (255, 255, 255), }, "corporate": { - "hbg": [(0, 72, 148), (0, 120, 212)], + "hbg": [(0, 72, 148), (0, 120, 212)], "accent": (0, 120, 212), - "h2": (0, 72, 148), - "h3": (60, 60, 100), - "body": (31, 41, 55), - "cbg": (240, 247, 255), - "cc": (0, 72, 148), - "rule": (173, 216, 230), - "htxt": (255, 255, 255), + "h2": (0, 72, 148), + "h3": (60, 60, 100), + "body": (31, 41, 55), + "cbg": (240, 247, 255), + "cc": (0, 72, 148), + "rule": (173, 216, 230), + "htxt": (255, 255, 255), }, "minimal": { - "hbg": [(50, 50, 50), (90, 90, 90)], + "hbg": [(50, 50, 50), (90, 90, 90)], "accent": (80, 80, 80), - "h2": (40, 40, 40), - "h3": (80, 80, 80), - "body": (40, 40, 40), - "cbg": (245, 245, 245), - "cc": (30, 30, 30), - "rule": (200, 200, 200), - "htxt": (255, 255, 255), + "h2": (40, 40, 40), + "h3": (80, 80, 80), + "body": (40, 40, 40), + "cbg": (245, 245, 245), + "cc": (30, 30, 30), + "rule": (200, 200, 200), + "htxt": (255, 255, 255), }, "warm": { - "hbg": [(120, 53, 15), (217, 119, 6)], + "hbg": [(120, 53, 15), (217, 119, 6)], "accent": (180, 83, 9), - "h2": (120, 53, 15), - "h3": (92, 72, 44), - "body": (41, 37, 36), - "cbg": (255, 247, 237), - "cc": (120, 53, 15), - "rule": (253, 186, 116), - "htxt": (255, 255, 255), + "h2": (120, 53, 15), + "h3": (92, 72, 44), + "body": (41, 37, 36), + "cbg": (255, 247, 237), + "cc": (120, 53, 15), + "rule": (253, 186, 116), + "htxt": (255, 255, 255), }, "forest": { - "hbg": [(20, 83, 45), (34, 197, 94)], + "hbg": [(20, 83, 45), (34, 197, 94)], "accent": (22, 163, 74), - "h2": (20, 83, 45), - "h3": (55, 65, 55), - "body": (31, 41, 31), - "cbg": (240, 253, 244), - "cc": (20, 83, 45), - "rule": (134, 239, 172), - "htxt": (255, 255, 255), + "h2": (20, 83, 45), + "h3": (55, 65, 55), + "body": (31, 41, 31), + "cbg": (240, 253, 244), + "cc": (20, 83, 45), + "rule": (134, 239, 172), + "htxt": (255, 255, 255), }, } t = _THEMES.get(theme, _THEMES["default"]) @@ -228,21 +240,48 @@ def _ensure(pkg, import_as=None): # safe ASCII equivalents before the HTML reaches fpdf2's parser. # Characters with no mapping are replaced with '?'. _CHAR_MAP = { - "\u2014": "--", "\u2013": "-", "\u2012": "-", - "\u2018": "'", "\u2019": "'", "\u201a": ",", - "\u201c": '"', "\u201d": '"', "\u201e": '"', - "\u2026": "...", "\u00a0": " ", - "\u2022": "*", "\u2010": "-", "\u2011": "-", "\u2015": "--", - "\u2122": "TM", "\u00ae": "(R)", "\u00a9": "(C)", - "\u20ac": "EUR", "\u00a3": "GBP", "\u00a5": "JPY", - "\u2192": "->", "\u2190": "<-", "\u2191": "^", "\u2193": "v", - "\u2713": "[x]", "\u2714": "[x]", "\u2717": "[ ]", - "\u2610": "[ ]", "\u2611": "[x]", - "\u00b0": "deg", "\u2265": ">=", "\u2264": "<=", - "\u00d7": "x", "\u00f7": "/", "\u00b1": "+/-", - "\u2248": "~=", "\u2260": "!=", "\u00b2": "^2", "\u00b3": "^3", + "\u2014": "--", + "\u2013": "-", + "\u2012": "-", + "\u2018": "'", + "\u2019": "'", + "\u201a": ",", + "\u201c": '"', + "\u201d": '"', + "\u201e": '"', + "\u2026": "...", + "\u00a0": " ", + "\u2022": "*", + "\u2010": "-", + "\u2011": "-", + "\u2015": "--", + "\u2122": "TM", + "\u00ae": "(R)", + "\u00a9": "(C)", + "\u20ac": "EUR", + "\u00a3": "GBP", + "\u00a5": "JPY", + "\u2192": "->", + "\u2190": "<-", + "\u2191": "^", + "\u2193": "v", + "\u2713": "[x]", + "\u2714": "[x]", + "\u2717": "[ ]", + "\u2610": "[ ]", + "\u2611": "[x]", + "\u00b0": "deg", + "\u2265": ">=", + "\u2264": "<=", + "\u00d7": "x", + "\u00f7": "/", + "\u00b1": "+/-", + "\u2248": "~=", + "\u2260": "!=", + "\u00b2": "^2", + "\u00b3": "^3", } - + def _sanitize(text): decoded = unescape(text) out = [] @@ -255,7 +294,7 @@ def _sanitize(text): else: out.append(ch) return "".join(out) - + # ── Build PDF ───────────────────────────────────────────────────────── try: # Convert markdown to HTML. @@ -267,16 +306,15 @@ def _sanitize(text): extras=["fenced-code-blocks", "tables", "strike", "footnotes"], ) html = _sanitize(html) - + # Extract the first H1 to use as the banner title, then remove it # from the body so it is not rendered twice. title_match = re.search(r"]*>(.*?)", html, re.IGNORECASE | re.DOTALL) doc_title = ( - re.sub(r"<[^>]+>", "", title_match.group(1)).strip() - if title_match else "" + re.sub(r"<[^>]+>", "", title_match.group(1)).strip() if title_match else "" ) html_body = html.replace(title_match.group(0), "", 1) if title_match else html - + # FPDF setup pdf = FPDF() pdf.set_auto_page_break(auto=True, margin=22) @@ -285,48 +323,93 @@ def _sanitize(text): pdf.set_title(doc_title) pdf.set_creator("CraftBot") pdf.add_page() - + pw = pdf.w - pdf.l_margin - pdf.r_margin # usable page width lm = pdf.l_margin - y0 = 8 # banner top y-position - HH = 50 if subtitle else 40 # banner height - + y0 = 8 # banner top y-position + HH = 50 if subtitle else 40 # banner height + # ── Gradient banner ─────────────────────────────────────────────── grad = LinearGradient(lm, y0, lm + pw, y0, colors=t["hbg"]) with pdf.use_pattern(grad): pdf.rect(lm, y0, pw, HH, style="F") - + if doc_title: pdf.set_font("Helvetica", "B", 20) pdf.set_text_color(*t["htxt"]) title_y = y0 + (HH - 20) / 2 - (5 if subtitle else 0) pdf.set_xy(lm + 8, title_y) pdf.cell(pw - 16, 12, doc_title[:72], align="L") - + if subtitle: pdf.set_font("Helvetica", "I", 9) pdf.set_text_color(200, 210, 240) pdf.set_xy(lm + 8, y0 + HH - 14) pdf.cell(pw - 16, 8, _sanitize(subtitle)[:100], align="L") - + # Thin accent rule below banner pdf.set_draw_color(*t["rule"]) pdf.set_line_width(0.8) pdf.line(lm, y0 + HH + 1, lm + pw, y0 + HH + 1) pdf.set_y(y0 + HH + 7) - + # ── Heading and code styles ─────────────────────────────────────── tag_styles = { - "h1": TextStyle(font_family="Helvetica", font_style="B", font_size_pt=20, color=t["h2"], t_margin=10, b_margin=3), - "h2": TextStyle(font_family="Helvetica", font_style="B", font_size_pt=16, color=t["h2"], t_margin=8, b_margin=2), - "h3": TextStyle(font_family="Helvetica", font_style="B", font_size_pt=13, color=t["h3"], t_margin=6, b_margin=2), - "h4": TextStyle(font_family="Helvetica", font_style="BI", font_size_pt=11, color=t["h3"], t_margin=4, b_margin=1), - "h5": TextStyle(font_family="Helvetica", font_style="I", font_size_pt=10, color=t["h3"], t_margin=3, b_margin=1), - "code": TextStyle(font_family="Courier", font_size_pt=9, color=t["cc"], fill_color=t["cbg"]), - "pre": TextStyle(font_family="Courier", font_size_pt=9, color=t["cc"], fill_color=t["cbg"]), - "a": FontFace(color=t["accent"]), + "h1": TextStyle( + font_family="Helvetica", + font_style="B", + font_size_pt=20, + color=t["h2"], + t_margin=10, + b_margin=3, + ), + "h2": TextStyle( + font_family="Helvetica", + font_style="B", + font_size_pt=16, + color=t["h2"], + t_margin=8, + b_margin=2, + ), + "h3": TextStyle( + font_family="Helvetica", + font_style="B", + font_size_pt=13, + color=t["h3"], + t_margin=6, + b_margin=2, + ), + "h4": TextStyle( + font_family="Helvetica", + font_style="BI", + font_size_pt=11, + color=t["h3"], + t_margin=4, + b_margin=1, + ), + "h5": TextStyle( + font_family="Helvetica", + font_style="I", + font_size_pt=10, + color=t["h3"], + t_margin=3, + b_margin=1, + ), + "code": TextStyle( + font_family="Courier", + font_size_pt=9, + color=t["cc"], + fill_color=t["cbg"], + ), + "pre": TextStyle( + font_family="Courier", + font_size_pt=9, + color=t["cc"], + fill_color=t["cbg"], + ), + "a": FontFace(color=t["accent"]), } - + pdf.set_text_color(*t["body"]) pdf.set_font("Helvetica", size=11) pdf.write_html( @@ -336,7 +419,7 @@ def _sanitize(text): table_line_separators=True, ul_bullet_char="*", ) - + # ── Page number footer ──────────────────────────────────────────── n_pages = len(pdf.pages) if page_numbers: @@ -346,13 +429,13 @@ def _sanitize(text): pdf.set_font("Helvetica", "I", 8) pdf.set_text_color(150, 150, 150) pdf.cell(0, 5, f"Page {pg} of {n_pages}", align="C") - + # ── Write to disk ───────────────────────────────────────────────── abs_path = os.path.abspath(file_path) parent = os.path.dirname(abs_path) if parent: os.makedirs(parent, exist_ok=True) - + pdf.output(abs_path) return { "status": "success", @@ -361,7 +444,7 @@ def _sanitize(text): "size_bytes": os.path.getsize(abs_path), "theme_used": theme, } - + except PermissionError as exc: return { "status": "error", @@ -379,4 +462,4 @@ def _sanitize(text): "status": "error", "path": "", "message": f"PDF generation failed: {type(exc).__name__}: {exc}", - } \ No newline at end of file + } diff --git a/app/data/action/edit_pdf.py b/app/data/action/edit_pdf.py index 734731716..cd3232d1e 100644 --- a/app/data/action/edit_pdf.py +++ b/app/data/action/edit_pdf.py @@ -1,5 +1,6 @@ from agent_core import action + @action( name="edit_pdf", description=( @@ -64,12 +65,41 @@ " fill_field: fill an AcroForm field. Fields: field_name(str), value(str)" ), "example": [ - {"type": "highlight", "pattern": "Invoice", "page": "all", "color": "#fef08a"}, - {"type": "add_text", "page": 1, "text": "PAID", "x": 200, "y": 400, - "font_size": 36, "color": "#16a34a"}, - {"type": "redact", "page": 1, "x0": 31.2, "y0": 791.3, "x1": 86.3, "y1": 807.3}, - {"type": "replace_text", "pattern": "Q3", "replacement": "Q4", "page": "all"}, - {"type": "watermark", "text": "DRAFT", "color": "#bbbbbb", "opacity": 0.2}, + { + "type": "highlight", + "pattern": "Invoice", + "page": "all", + "color": "#fef08a", + }, + { + "type": "add_text", + "page": 1, + "text": "PAID", + "x": 200, + "y": 400, + "font_size": 36, + "color": "#16a34a", + }, + { + "type": "redact", + "page": 1, + "x0": 31.2, + "y0": 791.3, + "x1": 86.3, + "y1": 807.3, + }, + { + "type": "replace_text", + "pattern": "Q3", + "replacement": "Q4", + "page": "all", + }, + { + "type": "watermark", + "text": "DRAFT", + "color": "#bbbbbb", + "opacity": 0.2, + }, ], }, }, @@ -111,7 +141,6 @@ def edit_pdf_file(input_data: dict) -> dict: import os import sys - import re import subprocess import importlib @@ -147,28 +176,28 @@ def _hex_to_rgb(hex_color): h = "".join(c * 2 for c in h) if len(h) != 6: return (0.0, 0.0, 0.0) - return tuple(int(h[i:i+2], 16) / 255.0 for i in (0, 2, 4)) + return tuple(int(h[i : i + 2], 16) / 255.0 for i in (0, 2, 4)) def _color_int_to_rgb(color_int): """Convert PyMuPDF integer color to (r,g,b) float tuple.""" r = ((color_int >> 16) & 0xFF) / 255.0 - g = ((color_int >> 8) & 0xFF) / 255.0 - b = ( color_int & 0xFF) / 255.0 + g = ((color_int >> 8) & 0xFF) / 255.0 + b = (color_int & 0xFF) / 255.0 return (r, g, b) # Base14 fonts always available in PyMuPDF — no embedding needed _BASE14 = { - "Helvetica": "helv", - "Helvetica-Bold": "hebo", + "Helvetica": "helv", + "Helvetica-Bold": "hebo", "Helvetica-BoldOblique": "hebi", - "Times-Roman": "tiro", - "Times-Bold": "tibo", - "Times-Italic": "tiit", - "Times-BoldItalic": "tibi", - "Courier": "cour", - "Courier-Bold": "cobo", - "Courier-Oblique": "coit", - "Courier-BoldOblique": "cobi", + "Times-Roman": "tiro", + "Times-Bold": "tibo", + "Times-Italic": "tiit", + "Times-BoldItalic": "tibi", + "Courier": "cour", + "Courier-Bold": "cobo", + "Courier-Oblique": "coit", + "Courier-BoldOblique": "cobi", } def _best_font(pdf_font_name): @@ -179,21 +208,29 @@ def _best_font(pdf_font_name): if pdf_font_name in _BASE14: return _BASE14[pdf_font_name], False n = pdf_font_name.lower() - is_bold = any(x in n for x in ("bold", "demi", "black", "heavy")) + is_bold = any(x in n for x in ("bold", "demi", "black", "heavy")) is_italic = any(x in n for x in ("italic", "oblique", "slant")) if "times" in n or "roman" in n or "serif" in n: - if is_bold and is_italic: return "tibi", True - if is_bold: return "tibo", True - if is_italic: return "tiit", True + if is_bold and is_italic: + return "tibi", True + if is_bold: + return "tibo", True + if is_italic: + return "tiit", True return "tiro", True if "courier" in n or "mono" in n or "typewriter" in n: - if is_bold and is_italic: return "cobi", True - if is_bold: return "cobo", True - if is_italic: return "coit", True + if is_bold and is_italic: + return "cobi", True + if is_bold: + return "cobo", True + if is_italic: + return "coit", True return "cour", True # Default: Helvetica family - if is_bold and is_italic: return "hebi", True - if is_bold: return "hebo", True + if is_bold and is_italic: + return "hebi", True + if is_bold: + return "hebo", True return "helv", True def _bl_to_rect(x0, y0, x1, y1, ph): @@ -204,6 +241,7 @@ def _bl_to_rect(x0, y0, x1, y1, ph): Conversion: y_mupdf = ph - y_bottomleft """ import fitz + return fitz.Rect(x0, ph - y1, x1, ph - y0) def _resolve_pages(page_spec, total_pages): @@ -227,6 +265,7 @@ def _get_span_at_rect(page, target_rect): Returns the span dict or None. """ import fitz + best_span = None best_area = 0.0 for block in page.get_text("dict")["blocks"]: @@ -243,9 +282,9 @@ def _get_span_at_rect(page, target_rect): # ── Input extraction ────────────────────────────────────────────────── simulated_mode = bool(input_data.get("simulated_mode", False)) - file_path = str(input_data.get("file_path", "")).strip() - output_path = str(input_data.get("output_path", "")).strip() - operations = input_data.get("operations", []) + file_path = str(input_data.get("file_path", "")).strip() + output_path = str(input_data.get("output_path", "")).strip() + operations = input_data.get("operations", []) if not isinstance(operations, list): operations = [] @@ -255,8 +294,8 @@ def _get_span_at_rect(page, target_rect): return _json("success", output_path=output_path, ops_applied=len(operations)) # ── Dependency bootstrap ────────────────────────────────────────────── - _ensure("pymupdf", "fitz") - _ensure("pypdf", "pypdf") + _ensure("pymupdf", "fitz") + _ensure("pypdf", "pypdf") import fitz import pypdf @@ -285,7 +324,13 @@ def _get_span_at_rect(page, target_rect): return _json("error", "'operations' list is required and must not be empty.") # Detect reflow operations — these require create_pdf routing - _REFLOW_OPS = {"rephrase_text", "insert_section", "insert_table", "reformat", "reflow"} + _REFLOW_OPS = { + "rephrase_text", + "insert_section", + "insert_table", + "reformat", + "reflow", + } reflow_ops = [op.get("type") for op in operations if op.get("type") in _REFLOW_OPS] if reflow_ops: return _json( @@ -298,36 +343,39 @@ def _get_span_at_rect(page, target_rect): # ── Apply operations ────────────────────────────────────────────────── try: - doc = fitz.open(file_path) + doc = fitz.open(file_path) total_pgs = len(doc) - warnings = [] - ops_done = 0 + warnings = [] + ops_done = 0 for i, op in enumerate(operations): op_type = str(op.get("type", "")).strip().lower() - op_tag = f"op[{i}] '{op_type}'" + op_tag = f"op[{i}] '{op_type}'" try: - # ── add_text ───────────────────────────────────────────── if op_type == "add_text": page_idx = int(op.get("page", 1)) - 1 if not (0 <= page_idx < total_pgs): - warnings.append(f"{op_tag}: page {op.get('page')} out of range.") + warnings.append( + f"{op_tag}: page {op.get('page')} out of range." + ) continue page = doc[page_idx] - ph = page.rect.height + ph = page.rect.height # x,y are BOTTOMLEFT — convert y to TOPLEFT - x = float(op.get("x", 0)) + x = float(op.get("x", 0)) y_bl = float(op.get("y", 0)) y_tl = ph - y_bl - text = str(op.get("text", "")) + text = str(op.get("text", "")) font_size = float(op.get("font_size", 12)) - color = _hex_to_rgb(op.get("color", "#000000")) + color = _hex_to_rgb(op.get("color", "#000000")) font_code, _ = _best_font(op.get("font", "Helvetica")) page.insert_text( - fitz.Point(x, y_tl), text, - fontname=font_code, fontsize=font_size, + fitz.Point(x, y_tl), + text, + fontname=font_code, + fontsize=font_size, color=color, ) ops_done += 1 @@ -336,9 +384,9 @@ def _get_span_at_rect(page, target_rect): elif op_type == "redact": fill_color = _hex_to_rgb(op.get("fill_color", "#000000")) if "pattern" in op: - pattern = str(op["pattern"]) - page_idxs = _resolve_pages(op.get("page", "all"), total_pgs) - hit_count = 0 + pattern = str(op["pattern"]) + page_idxs = _resolve_pages(op.get("page", "all"), total_pgs) + hit_count = 0 for pi in page_idxs: page = doc[pi] hits = page.search_for(pattern) @@ -353,12 +401,16 @@ def _get_span_at_rect(page, target_rect): else: page_idx = int(op.get("page", 1)) - 1 if not (0 <= page_idx < total_pgs): - warnings.append(f"{op_tag}: page out of range."); continue + warnings.append(f"{op_tag}: page out of range.") + continue page = doc[page_idx] - ph = page.rect.height - r = _bl_to_rect( - float(op["x0"]), float(op["y0"]), - float(op["x1"]), float(op["y1"]), ph + ph = page.rect.height + r = _bl_to_rect( + float(op["x0"]), + float(op["y0"]), + float(op["x1"]), + float(op["y1"]), + ph, ) page.add_redact_annot(r, fill=fill_color) page.apply_redactions() @@ -372,10 +424,14 @@ def _get_span_at_rect(page, target_rect): "strikeout": "add_strikeout_annot", } fn_name = annot_fns[op_type] - color = _hex_to_rgb(op.get("color", "#ffff00")) if op_type == "highlight" else None + color = ( + _hex_to_rgb(op.get("color", "#ffff00")) + if op_type == "highlight" + else None + ) if "pattern" in op: - pattern = str(op["pattern"]) + pattern = str(op["pattern"]) page_idxs = _resolve_pages(op.get("page", "all"), total_pgs) hit_count = 0 for pi in page_idxs: @@ -393,12 +449,16 @@ def _get_span_at_rect(page, target_rect): else: page_idx = int(op.get("page", 1)) - 1 if not (0 <= page_idx < total_pgs): - warnings.append(f"{op_tag}: page out of range."); continue + warnings.append(f"{op_tag}: page out of range.") + continue page = doc[page_idx] - ph = page.rect.height - r = _bl_to_rect( - float(op["x0"]), float(op["y0"]), - float(op["x1"]), float(op["y1"]), ph + ph = page.rect.height + r = _bl_to_rect( + float(op["x0"]), + float(op["y0"]), + float(op["x1"]), + float(op["y1"]), + ph, ) annot = getattr(page, fn_name)(r) if color: @@ -408,11 +468,12 @@ def _get_span_at_rect(page, target_rect): # ── replace_text (font-matched seamless replacement) ────── elif op_type == "replace_text": - pattern = str(op.get("pattern", "")) + pattern = str(op.get("pattern", "")) replacement = str(op.get("replacement", "")) - page_idxs = _resolve_pages(op.get("page", "all"), total_pgs) + page_idxs = _resolve_pages(op.get("page", "all"), total_pgs) if not pattern: - warnings.append(f"{op_tag}: 'pattern' is required."); continue + warnings.append(f"{op_tag}: 'pattern' is required.") + continue hit_count = 0 for pi in page_idxs: page = doc[pi] @@ -420,9 +481,9 @@ def _get_span_at_rect(page, target_rect): for h in hits: span = _get_span_at_rect(page, h) if span: - font_name = span["font"] - font_size = span["size"] - color_rgb = _color_int_to_rgb(span["color"]) + font_name = span["font"] + font_size = span["size"] + color_rgb = _color_int_to_rgb(span["color"]) font_code, was_fb = _best_font(font_name) if was_fb: warnings.append( @@ -439,7 +500,8 @@ def _get_span_at_rect(page, target_rect): # Reinsert with same properties insert_pt = fitz.Point(h.x0, h.y1 - 2) page.insert_text( - insert_pt, replacement, + insert_pt, + replacement, fontname=font_code, fontsize=font_size, color=color_rgb, @@ -451,29 +513,34 @@ def _get_span_at_rect(page, target_rect): # ── add_text_near (form fill: insert value after label) ──── elif op_type == "add_text_near": - label = str(op.get("label", "")) - value = str(op.get("value", "")) - page_idx = int(op.get("page", 1)) - 1 - offset_x = float(op.get("offset_x", 5)) + label = str(op.get("label", "")) + value = str(op.get("value", "")) + page_idx = int(op.get("page", 1)) - 1 + offset_x = float(op.get("offset_x", 5)) font_size = float(op.get("font_size", 11)) - color = _hex_to_rgb(op.get("color", "#000000")) + color = _hex_to_rgb(op.get("color", "#000000")) font_code, _ = _best_font(op.get("font", "Helvetica")) if not label: - warnings.append(f"{op_tag}: 'label' is required."); continue + warnings.append(f"{op_tag}: 'label' is required.") + continue if not (0 <= page_idx < total_pgs): - warnings.append(f"{op_tag}: page out of range."); continue + warnings.append(f"{op_tag}: page out of range.") + continue page = doc[page_idx] hits = page.search_for(label) if not hits: - warnings.append(f"{op_tag}: label '{label}' not found on page {page_idx+1}.") + warnings.append( + f"{op_tag}: label '{label}' not found on page {page_idx + 1}." + ) continue label_rect = hits[0] - insert_pt = fitz.Point( + insert_pt = fitz.Point( label_rect.x1 + offset_x, label_rect.y1 - 2, # baseline approx ) page.insert_text( - insert_pt, value, + insert_pt, + value, fontname=font_code, fontsize=font_size, color=color, @@ -482,18 +549,19 @@ def _get_span_at_rect(page, target_rect): # ── watermark ───────────────────────────────────────────── elif op_type == "watermark": - text = str(op.get("text", "CONFIDENTIAL")) + text = str(op.get("text", "CONFIDENTIAL")) font_size = float(op.get("font_size", 52)) - color = _hex_to_rgb(op.get("color", "#bbbbbb")) + color = _hex_to_rgb(op.get("color", "#bbbbbb")) # opacity in insert_textbox: blend into color lightness - opacity = float(op.get("opacity", 0.25)) + opacity = float(op.get("opacity", 0.25)) # Blend color toward white to simulate opacity - blended = tuple(c + (1.0 - c) * (1.0 - opacity) for c in color) + blended = tuple(c + (1.0 - c) * (1.0 - opacity) for c in color) for page in doc: pw, ph = page.rect.width, page.rect.height - rect = fitz.Rect(40, ph / 2 - 60, pw - 40, ph / 2 + 60) + rect = fitz.Rect(40, ph / 2 - 60, pw - 40, ph / 2 + 60) page.insert_textbox( - rect, text, + rect, + text, fontsize=font_size, color=blended, align=fitz.TEXT_ALIGN_CENTER, @@ -503,11 +571,13 @@ def _get_span_at_rect(page, target_rect): # ── rotate_page ─────────────────────────────────────────── elif op_type == "rotate_page": page_idx = int(op.get("page", 1)) - 1 - degrees = int(op.get("degrees", 90)) + degrees = int(op.get("degrees", 90)) if not (0 <= page_idx < total_pgs): - warnings.append(f"{op_tag}: page out of range."); continue + warnings.append(f"{op_tag}: page out of range.") + continue if degrees not in (90, 180, 270, -90, -180, -270): - warnings.append(f"{op_tag}: degrees must be 90, 180, or 270."); continue + warnings.append(f"{op_tag}: degrees must be 90, 180, or 270.") + continue # Normalize to 0-360 degrees = degrees % 360 current = doc[page_idx].rotation @@ -531,7 +601,7 @@ def _get_span_at_rect(page, target_rect): # ── Write PyMuPDF output ────────────────────────────────────────── abs_output = os.path.abspath(output_path) - parent = os.path.dirname(abs_output) + parent = os.path.dirname(abs_output) if parent: os.makedirs(parent, exist_ok=True) @@ -539,7 +609,9 @@ def _get_span_at_rect(page, target_rect): doc.close() # ── Post-process: AcroForm fill_field via pypdf ─────────────────── - acroform_ops = [op for op in operations if str(op.get("type", "")).lower() == "fill_field"] + acroform_ops = [ + op for op in operations if str(op.get("type", "")).lower() == "fill_field" + ] if acroform_ops: try: reader = pypdf.PdfReader(abs_output) @@ -547,9 +619,9 @@ def _get_span_at_rect(page, target_rect): writer.append(reader) existing_fields = reader.get_fields() or {} for op in acroform_ops: - op_tag = f"op[fill_field]" + op_tag = "op[fill_field]" field_name = str(op.get("field_name", "")) - value = str(op.get("value", "")) + value = str(op.get("value", "")) if not field_name: warnings.append(f"{op_tag}: 'field_name' is required.") continue diff --git a/app/data/action/read_pdf.py b/app/data/action/read_pdf.py index a83df236f..809d8227a 100644 --- a/app/data/action/read_pdf.py +++ b/app/data/action/read_pdf.py @@ -1,6 +1,6 @@ from agent_core import action - - + + @action( name="read_pdf", description=( @@ -61,9 +61,7 @@ }, "pages": [{"page_number": 1, "width": 595.28, "height": 841.89}], "text": "Invoice #1042\nBill To: John Smith", - "tables": [ - [["Description", "Amount"], ["Web Dev", "$1,500.00"]] - ], + "tables": [[["Description", "Amount"], ["Web Dev", "$1,500.00"]]], }, }, "message": { @@ -84,16 +82,16 @@ def read_pdf_file(input_data: dict) -> dict: import sys import subprocess import importlib - + # ── Helpers ─────────────────────────────────────────────────────────── def _json(status, message="", content=None): return {"status": status, "message": message, "content": content or ""} - + _FIELD_RE = re.compile(r"(?:_{4,}|\.{4,}|—{3,}|–{3,})") - + def _is_form_blank(text): return bool(text and _FIELD_RE.search(text.strip())) - + def _parse_page_range(pr, total): """ Parse '1', '1-3', '2,4,6' into a sorted list of 1-based page numbers. @@ -110,7 +108,7 @@ def _parse_page_range(pr, total): if "-" in part: s, e = part.split("-", 1) start = max(1, int(s.strip())) - end = min(total, int(e.strip())) + end = min(total, int(e.strip())) if start > end: # e.g. '5-2' — reversed range, treat as invalid return None @@ -122,7 +120,7 @@ def _parse_page_range(pr, total): except (ValueError, AttributeError): return None return sorted(pages) - + def _words_to_elements(words, page_num, pw, ph): """ Convert pdfplumber word list to v1-compatible element format. @@ -149,16 +147,18 @@ def _words_to_elements(words, page_num, pw, ph): "x1": round(max(0.0, min(1.0, x1 / pw)), 4), "y1": round(max(0.0, min(1.0, y1_bl / ph)), 4), } - out.append({ - "page_number": page_num, - "element_type": "text", - "text": w["text"], - "bbox_abs": abs_bbox, - "bbox_norm": norm_bbox, - "is_form_field_candidate": _is_form_blank(w["text"]), - }) + out.append( + { + "page_number": page_num, + "element_type": "text", + "text": w["text"], + "bbox_abs": abs_bbox, + "bbox_norm": norm_bbox, + "is_form_field_candidate": _is_form_blank(w["text"]), + } + ) return out - + def _docling_to_elements(raw, page_dims): """ Convert docling export_to_dict() output to v1-compatible element list. @@ -195,25 +195,27 @@ def _docling_to_elements(raw, page_dims): "x1": round(max(0.0, min(1.0, abs_bbox["x1"] / pw)), 4), "y1": round(max(0.0, min(1.0, abs_bbox["y1"] / ph)), 4), } - out.append({ - "page_number": pn, - "element_type": label, - "text": text_val, - "bbox_abs": abs_bbox, - "bbox_norm": norm_bbox, - "is_form_field_candidate": _is_form_blank(text_val), - }) + out.append( + { + "page_number": pn, + "element_type": label, + "text": text_val, + "bbox_abs": abs_bbox, + "bbox_norm": norm_bbox, + "is_form_field_candidate": _is_form_blank(text_val), + } + ) return out - + # ── Input extraction ────────────────────────────────────────────────── simulated_mode = bool(input_data.get("simulated_mode", False)) - file_path = str(input_data.get("file_path", "")).strip() - mode = str(input_data.get("mode", "text")).strip().lower() - page_range = str(input_data.get("page_range", "")).strip() - + file_path = str(input_data.get("file_path", "")).strip() + mode = str(input_data.get("mode", "text")).strip().lower() + page_range = str(input_data.get("page_range", "")).strip() + if mode not in ("text", "layout"): mode = "text" - + # ── Simulated mode ──────────────────────────────────────────────────── if simulated_mode: base_content = { @@ -226,18 +228,26 @@ def _docling_to_elements(raw, page_dims): "pages": [{"page_number": 1, "width": 595.28, "height": 841.89}], } if mode == "layout": - base_content["elements"] = [{ - "page_number": 1, - "element_type": "text", - "text": "Test PDF content", - "bbox_abs": {"x0": 10.0, "y0": 20.0, "x1": 100.0, "y1": 40.0, "coord_origin": "BOTTOMLEFT"}, - "bbox_norm": {"x0": 0.05, "y0": 0.02, "x1": 0.2, "y1": 0.05}, - "is_form_field_candidate": False, - }] + base_content["elements"] = [ + { + "page_number": 1, + "element_type": "text", + "text": "Test PDF content", + "bbox_abs": { + "x0": 10.0, + "y0": 20.0, + "x1": 100.0, + "y1": 40.0, + "coord_origin": "BOTTOMLEFT", + }, + "bbox_norm": {"x0": 0.05, "y0": 0.02, "x1": 0.2, "y1": 0.05}, + "is_form_field_candidate": False, + } + ] else: base_content["text"] = "Test PDF content" return _json("success", "", base_content) - + # ── Dependency bootstrap (executor pre-installs via requirement=) ───── def _ensure(pkg, import_as=None): try: @@ -251,14 +261,14 @@ def _ensure(pkg, import_as=None): ) except Exception: pass # executor pre-installs via requirement=; failure here is non-fatal - + _ensure("pdfplumber") _ensure("pypdfium2") _ensure("docling") - + import pdfplumber import pypdfium2 - + # ── Validation ──────────────────────────────────────────────────────── if not file_path: return _json("error", "'file_path' is required.") @@ -279,37 +289,42 @@ def _ensure(pkg, import_as=None): "sections first using a tool like qpdf, then read each part separately " "using the page_range parameter.", ) - + # ── Primary extraction: pdfplumber ──────────────────────────────────── try: - pages_out = [] - text_parts = [] + pages_out = [] + text_parts = [] all_elements = [] - all_tables = [] + all_tables = [] scanned_page_nums = [] # pages where pdfplumber found no text - + with pdfplumber.open(file_path) as doc: - total_pages = len(doc.pages) + total_pages = len(doc.pages) target_pages = _parse_page_range(page_range, total_pages) - + if target_pages is None: - return _json("error", f"Invalid page_range format: '{page_range}'. Use '1', '1-3', or '2,4,6'.") - + return _json( + "error", + f"Invalid page_range format: '{page_range}'. Use '1', '1-3', or '2,4,6'.", + ) + for i, page in enumerate(doc.pages): pn = i + 1 if pn not in target_pages: continue - + pw = page.width ph = page.height - pages_out.append({ - "page_number": pn, - "width": round(pw, 2), - "height": round(ph, 2), - }) - + pages_out.append( + { + "page_number": pn, + "width": round(pw, 2), + "height": round(ph, 2), + } + ) + page_text = page.extract_text() or "" - + if page_text.strip(): # Digital page — pdfplumber can handle it if mode == "text": @@ -327,10 +342,10 @@ def _ensure(pkg, import_as=None): # target page is empty. A single blank page in a digital PDF # should not cause a full docling run. scanned_page_nums.append(pn) - + engine = "pdfplumber" engine_warning = "" - + # ── Fallback: docling for scanned pages ─────────────────────────── # Only triggered when ALL target pages have no extractable text, # which reliably signals a scanned or image-only PDF. @@ -341,13 +356,16 @@ def _ensure(pkg, import_as=None): try: from docling.document_converter import DocumentConverter from docling.datamodel.base_models import ConversionStatus - - conv = DocumentConverter() + + conv = DocumentConverter() result = conv.convert(file_path) - - if result.status in (ConversionStatus.SUCCESS, ConversionStatus.PARTIAL_SUCCESS): + + if result.status in ( + ConversionStatus.SUCCESS, + ConversionStatus.PARTIAL_SUCCESS, + ): engine = "docling" - + if mode == "text": # export_to_markdown gives clean, LLM-ready text fallback_text = result.document.export_to_markdown() or "" @@ -356,19 +374,20 @@ def _ensure(pkg, import_as=None): else: # layout mode: use docling's bbox data raw = result.document.export_to_dict() - + # Rebuild page dims map from the pages we extracted page_dims = { p["page_number"]: {"w": p["width"], "h": p["height"]} for p in pages_out } - + # If pages_out is empty (fully scanned, pdfplumber got nothing) # pull page dimensions from pypdfium2 if not pages_out: pdf2 = pypdfium2.PdfDocument(file_path) target_pages_set = set( - _parse_page_range(page_range, len(pdf2)) or range(1, len(pdf2) + 1) + _parse_page_range(page_range, len(pdf2)) + or range(1, len(pdf2) + 1) ) for idx in range(len(pdf2)): pn = idx + 1 @@ -376,13 +395,15 @@ def _ensure(pkg, import_as=None): continue pg = pdf2.get_page(idx) w, h = pg.get_size() - pages_out.append({ - "page_number": pn, - "width": round(float(w), 2), - "height": round(float(h), 2), - }) + pages_out.append( + { + "page_number": pn, + "width": round(float(w), 2), + "height": round(float(h), 2), + } + ) page_dims[pn] = {"w": float(w), "h": float(h)} - + docling_elements = _docling_to_elements(raw, page_dims) # Filter to target pages only — use the set already computed # at extraction time, which holds original 1-based page numbers. @@ -391,43 +412,46 @@ def _ensure(pkg, import_as=None): # range for any page_range that doesn't start at 1. target_set = set(target_pages) all_elements.extend( - e for e in docling_elements + e + for e in docling_elements if e["page_number"] in target_set ) else: - engine_warning = "Scanned pages detected but OCR extraction returned no content." - + engine_warning = ( + "Scanned pages detected but OCR extraction returned no content." + ) + except Exception as exc: # docling unavailable or failed — surface what pdfplumber got # (empty for scanned PDFs) and warn via metadata. engine_warning = f"Scanned pages detected but OCR fallback failed: {type(exc).__name__}." - + # ── Build output ────────────────────────────────────────────────── meta = { - "file_name": os.path.basename(file_path), - "mimetype": "application/pdf", - "page_count": total_pages, - "engine": engine, + "file_name": os.path.basename(file_path), + "mimetype": "application/pdf", + "page_count": total_pages, + "engine": engine, } if engine_warning: meta["engine_warning"] = engine_warning - + if mode == "text": content = { "document_metadata": meta, - "pages": pages_out, - "text": "\n\n".join(text_parts), + "pages": pages_out, + "text": "\n\n".join(text_parts), } if all_tables: content["tables"] = all_tables else: content = { "document_metadata": meta, - "pages": pages_out, - "elements": all_elements, + "pages": pages_out, + "elements": all_elements, } - + return _json("success", "", content) - + except Exception as exc: - return _json("error", f"{type(exc).__name__}: {exc}") \ No newline at end of file + return _json("error", f"{type(exc).__name__}: {exc}")