Download app/utils/exporter.py from rk147/secforge: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/spaces/rk147/secforge/resolve/main/app/utils/exporter.py
- Command line
-
hf download hf://spaces/rk147/secforge/app/utils/exporter.py
-
curl -L -o exporter.py https://huggingface.co/spaces/rk147/secforge/resolve/main/app/utils/exporter.py
13.8 kB
| """Export session data to markdown, docx, or PDF β styled and meaningful.""" | |
| import io | |
| from datetime import datetime | |
| def _build_markdown(session_label: str, messages: list, analysis: dict = None, map_data: dict = None) -> str: | |
| ts = datetime.now().strftime("%Y-%m-%d %H:%M") | |
| lines = [ | |
| f"# π¬ Secforge Analysis Report", | |
| f"**Session:** {session_label} | **Exported:** {ts}", | |
| "", | |
| "---", | |
| "", | |
| ] | |
| if messages: | |
| lines += ["## π¬ Chat History", ""] | |
| for m in messages: | |
| if m["role"] == "user": | |
| lines.append(f"> **You:** {m['content']}") | |
| else: | |
| content = m['content'] | |
| if content and not content.startswith("["): | |
| lines.append(f"**Secforge:** {content}") | |
| lines.append("") | |
| if analysis and not analysis.get("error"): | |
| lines += ["---", "", "## π Code Analysis", ""] | |
| exp = analysis.get("explanation", {}) | |
| lang = analysis.get("language_display", "") | |
| if exp and "error" not in exp: | |
| lines += [ | |
| f"**Language:** `{lang}`", | |
| "", | |
| f"**Summary:** {exp.get('summary', 'N/A')}", | |
| "", | |
| f"**Logic:** {exp.get('logic', 'N/A')}", | |
| "", | |
| f"**Inputs:** {exp.get('inputs', 'N/A')} | **Outputs:** {exp.get('outputs', 'N/A')}", | |
| "", | |
| f"**Assumptions:** {exp.get('assumptions', 'N/A')}", | |
| "", | |
| ] | |
| issues = analysis.get("issues", []) | |
| if issues: | |
| lines += [f"### β οΈ Issues Found ({len(issues)})", ""] | |
| for iss in issues: | |
| sev = iss.get("severity", "low") | |
| dot = {"high": "π΄", "medium": "π‘", "low": "π’"}.get(sev, "βͺ") | |
| lines.append(f"{dot} **Line {iss['line']}** `{iss['symbol']}` β {iss['message']} _(category: {iss['category']}, severity: {sev})_") | |
| lines.append("") | |
| fixes = analysis.get("fixes", []) | |
| if fixes: | |
| lines += ["### π§ Suggested Fixes", ""] | |
| for fix in fixes: | |
| lines += [ | |
| f"**Line {fix['line']}** β {fix['issue']}", | |
| f"```\n{fix['fix']}\n```", | |
| "", | |
| ] | |
| if map_data: | |
| lines += ["---", "", "## πΊοΈ Code Map", ""] | |
| if map_data.get("narrative"): | |
| lines += [ | |
| "> " + map_data["narrative"].replace("\n", "\n> "), | |
| "", | |
| ] | |
| nodes = [n for n in map_data.get("nodes", []) if n.get("kind") != "external"] | |
| if nodes: | |
| lines += [f"### Nodes ({len(nodes)})", ""] | |
| for n in nodes: | |
| desc = f" β {n['description']}" if n.get("description") else "" | |
| expl = f"\n > {n['explanation']}" if n.get("explanation") else "" | |
| lines.append(f"- **{n['label']}** `{n['kind']}` Β· `{n['file']}:{n['line']}`{desc}{expl}") | |
| lines.append("") | |
| edges = map_data.get("edges", []) | |
| meaningful = [e for e in edges if e.get("relationship") and e["relationship"] != "calls"] | |
| if meaningful: | |
| lines += ["### Key Relationships", ""] | |
| for e in meaningful[:30]: | |
| src = e["source"].split("::")[-1] | |
| tgt = e["target"].split("::")[-1] | |
| lines.append(f"- `{src}` β `{tgt}` β _{e['relationship']}_") | |
| lines.append("") | |
| lines += ["---", "", "*Generated by Secforge Β· secforge.hf.space*"] | |
| return "\n".join(lines) | |
| def export_markdown(session_label: str, messages: list, analysis: dict = None, map_data: dict = None) -> bytes: | |
| return _build_markdown(session_label, messages, analysis, map_data).encode("utf-8") | |
| def export_docx(session_label: str, messages: list, analysis: dict = None, map_data: dict = None) -> bytes: | |
| try: | |
| from docx import Document | |
| from docx.shared import Pt, RGBColor, Inches | |
| from docx.enum.text import WD_ALIGN_PARAGRAPH | |
| doc = Document() | |
| # Styles | |
| style = doc.styles["Normal"] | |
| style.font.name = "Calibri" | |
| style.font.size = Pt(11) | |
| # Title block | |
| title = doc.add_heading("π¬ Secforge Analysis Report", 0) | |
| title.alignment = WD_ALIGN_PARAGRAPH.LEFT | |
| sub = doc.add_paragraph() | |
| sub.add_run(f"Session: {session_label}").bold = True | |
| sub.add_run(f" | Exported: {datetime.now().strftime('%Y-%m-%d %H:%M')}") | |
| doc.add_paragraph() | |
| # Chat | |
| if messages: | |
| doc.add_heading("π¬ Chat History", level=1) | |
| for m in messages: | |
| if m["role"] == "user": | |
| p = doc.add_paragraph() | |
| p.add_run("You: ").bold = True | |
| p.add_run(m["content"]) | |
| elif m["content"] and not m["content"].startswith("["): | |
| p = doc.add_paragraph() | |
| p.add_run("Secforge: ").bold = True | |
| p.add_run(m["content"]) | |
| # Analysis | |
| if analysis and not analysis.get("error"): | |
| doc.add_heading("π Code Analysis", level=1) | |
| exp = analysis.get("explanation", {}) | |
| lang = analysis.get("language_display", "") | |
| if exp and "error" not in exp: | |
| for label, key in [("Language", None), ("Summary", "summary"), ("Logic", "logic"), | |
| ("Inputs", "inputs"), ("Outputs", "outputs"), ("Assumptions", "assumptions")]: | |
| p = doc.add_paragraph() | |
| p.add_run(f"{label}: ").bold = True | |
| p.add_run(lang if key is None else exp.get(key, "N/A")) | |
| issues = analysis.get("issues", []) | |
| if issues: | |
| doc.add_heading(f"β οΈ Issues Found ({len(issues)})", level=2) | |
| for iss in issues: | |
| sev = iss.get("severity", "low") | |
| dot = {"high": "π΄", "medium": "π‘", "low": "π’"}.get(sev, "βͺ") | |
| p = doc.add_paragraph(style="List Bullet") | |
| p.add_run(f"{dot} Line {iss['line']} [{iss['symbol']}] ").bold = True | |
| p.add_run(f"{iss['message']} β {iss['category']}, {sev}") | |
| fixes = analysis.get("fixes", []) | |
| if fixes: | |
| doc.add_heading("π§ Suggested Fixes", level=2) | |
| for fix in fixes: | |
| p = doc.add_paragraph() | |
| p.add_run(f"Line {fix['line']}: {fix['issue']}").bold = True | |
| doc.add_paragraph(fix["fix"], style="No Spacing").runs[0].font.name = "Courier New" | |
| # Map | |
| if map_data: | |
| doc.add_heading("πΊοΈ Code Map", level=1) | |
| if map_data.get("narrative"): | |
| p = doc.add_paragraph() | |
| p.add_run("Flow Overview: ").bold = True | |
| p.add_run(map_data["narrative"]) | |
| nodes = [n for n in map_data.get("nodes", []) if n.get("kind") != "external"] | |
| if nodes: | |
| doc.add_heading(f"Nodes ({len(nodes)})", level=2) | |
| for n in nodes: | |
| p = doc.add_paragraph(style="List Bullet") | |
| p.add_run(f"{n['label']} ({n['kind']}) ").bold = True | |
| p.add_run(f"Β· {n['file']}:{n['line']}") | |
| if n.get("description"): | |
| p.add_run(f" β {n['description']}") | |
| if n.get("explanation"): | |
| doc.add_paragraph(f" {n['explanation']}", style="No Spacing") | |
| doc.add_paragraph() | |
| doc.add_paragraph("Generated by Secforge Β· secforge.hf.space").italic = True | |
| buf = io.BytesIO() | |
| doc.save(buf) | |
| return buf.getvalue() | |
| except ImportError: | |
| return export_markdown(session_label, messages, analysis, map_data) | |
| except Exception: | |
| return export_markdown(session_label, messages, analysis, map_data) | |
| def export_pdf(session_label: str, messages: list, analysis: dict = None, map_data: dict = None) -> bytes: | |
| try: | |
| from fpdf import FPDF | |
| import re | |
| class PDF(FPDF): | |
| def header(self): | |
| self.set_font("Helvetica", "B", 9) | |
| self.set_text_color(80, 80, 80) | |
| self.cell(0, 8, "SECFORGE ANALYSIS REPORT", align="L", ln=True) | |
| self.set_draw_color(40, 40, 40) | |
| self.line(10, self.get_y(), 200, self.get_y()) | |
| self.ln(3) | |
| def footer(self): | |
| self.set_y(-12) | |
| self.set_font("Helvetica", "I", 8) | |
| self.set_text_color(120, 120, 120) | |
| self.cell(0, 8, f"secforge.hf.space Β· Page {self.page_no()}", align="C") | |
| pdf = PDF() | |
| pdf.set_auto_page_break(auto=True, margin=18) | |
| pdf.add_page() | |
| def safe(s: str) -> str: | |
| return (s or "").encode("latin-1", errors="replace").decode("latin-1")[:180] | |
| def h1(text): | |
| pdf.ln(4) | |
| pdf.set_font("Helvetica", "B", 13) | |
| pdf.set_text_color(220, 220, 220) | |
| pdf.set_fill_color(25, 25, 30) | |
| pdf.cell(0, 9, safe(text), ln=True, fill=True) | |
| pdf.ln(2) | |
| def h2(text): | |
| pdf.ln(3) | |
| pdf.set_font("Helvetica", "B", 11) | |
| pdf.set_text_color(160, 160, 160) | |
| pdf.cell(0, 7, safe(text), ln=True) | |
| pdf.ln(1) | |
| def body(text, bold=False): | |
| pdf.set_font("Helvetica", "B" if bold else "", 10) | |
| pdf.set_text_color(200, 200, 200) | |
| pdf.multi_cell(0, 6, safe(text)) | |
| def bullet(text): | |
| pdf.set_font("Helvetica", "", 9) | |
| pdf.set_text_color(180, 180, 180) | |
| pdf.cell(5, 6, "β’", ln=False) | |
| pdf.multi_cell(0, 6, safe(text)) | |
| def label_val(label, val): | |
| pdf.set_font("Helvetica", "B", 10) | |
| pdf.set_text_color(140, 140, 140) | |
| pdf.cell(35, 6, safe(label + ":"), ln=False) | |
| pdf.set_font("Helvetica", "", 10) | |
| pdf.set_text_color(200, 200, 200) | |
| pdf.multi_cell(0, 6, safe(val)) | |
| # Set dark background | |
| pdf.set_fill_color(14, 14, 16) | |
| pdf.rect(0, 0, 210, 297, "F") | |
| # Title | |
| pdf.set_font("Helvetica", "B", 18) | |
| pdf.set_text_color(240, 240, 240) | |
| pdf.cell(0, 12, "Secforge", ln=True) | |
| pdf.set_font("Helvetica", "", 10) | |
| pdf.set_text_color(100, 100, 100) | |
| pdf.cell(0, 6, safe(f"Session: {session_label} | {datetime.now().strftime('%Y-%m-%d %H:%M')}"), ln=True) | |
| pdf.ln(6) | |
| if messages: | |
| h1("Chat History") | |
| for m in messages: | |
| if m["role"] == "user": | |
| label_val("You", m["content"][:300]) | |
| elif m.get("content") and not m["content"].startswith("["): | |
| label_val("Secforge", m["content"][:400]) | |
| if analysis and not analysis.get("error"): | |
| h1("Code Analysis") | |
| exp = analysis.get("explanation", {}) | |
| lang = analysis.get("language_display", "") | |
| if exp and "error" not in exp: | |
| label_val("Language", lang) | |
| label_val("Summary", exp.get("summary", "")) | |
| label_val("Logic", exp.get("logic", "")) | |
| label_val("Inputs", exp.get("inputs", "")) | |
| label_val("Outputs", exp.get("outputs", "")) | |
| issues = analysis.get("issues", []) | |
| if issues: | |
| h2(f"Issues Found ({len(issues)})") | |
| for iss in issues: | |
| sev = iss.get("severity", "low") | |
| dot = {"high": "[HIGH]", "medium": "[MED]", "low": "[LOW]"}.get(sev, "") | |
| bullet(f"{dot} Line {iss['line']} [{iss['symbol']}] β {iss['message']}") | |
| fixes = analysis.get("fixes", []) | |
| if fixes: | |
| h2("Suggested Fixes") | |
| for fix in fixes: | |
| bullet(f"Line {fix['line']}: {fix['issue']}") | |
| if map_data: | |
| h1("Code Map") | |
| if map_data.get("narrative"): | |
| pdf.set_font("Helvetica", "I", 10) | |
| pdf.set_text_color(160, 160, 160) | |
| pdf.multi_cell(0, 6, safe(map_data["narrative"])) | |
| pdf.ln(3) | |
| nodes = [n for n in map_data.get("nodes", []) if n.get("kind") != "external"] | |
| if nodes: | |
| h2(f"Nodes ({len(nodes)})") | |
| for n in nodes: | |
| desc = f" β {n['description']}" if n.get("description") else "" | |
| bullet(f"{n['label']} ({n['kind']}) Β· {n['file']}:{n['line']}{desc}") | |
| if n.get("explanation"): | |
| pdf.set_font("Helvetica", "I", 9) | |
| pdf.set_text_color(120, 120, 120) | |
| pdf.cell(8, 5, "", ln=False) | |
| pdf.multi_cell(0, 5, safe(n["explanation"])) | |
| meaningful = [e for e in map_data.get("edges", []) if e.get("relationship") and e["relationship"] != "calls"] | |
| if meaningful: | |
| h2("Key Relationships") | |
| for e in meaningful[:25]: | |
| src = e["source"].split("::")[-1] | |
| tgt = e["target"].split("::")[-1] | |
| bullet(f"{src} β {tgt}: {e['relationship']}") | |
| return bytes(pdf.output()) | |
| except ImportError: | |
| return export_markdown(session_label, messages, analysis, map_data) | |
| except Exception as ex: | |
| print(f"[EXPORT PDF ERROR] {ex}") | |
| return export_markdown(session_label, messages, analysis, map_data) |