Spaces:
Sleeping
Sleeping
Update main.py
Browse files14 unmodified lines151617181919202122232425262728293020212223279 unmodified lines30330430531631731831930630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935032332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636735135235335435535635735835936036136237037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441536336436536636736836937037137237337414 unmodified linesfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import StreamingResponsefrom jinja2 import Templatefrom pydantic import BaseModelfrom reportlab.lib import colorsfrom reportlab.lib.pagesizes import A4from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheetfrom reportlab.lib.units import mmfrom reportlab.platypus import ( HRFlowable, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle,)from weasyprint import HTML
# ββ App Setup βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββapp = FastAPI(279 unmodified lines
# ββ PDF Generator βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def strip_md(text: str) -> str: text = re.sub(r"\*\*(.*?)\*\*", r"\1", text) text = re.sub(r"\*(.*?)\*", r"\1", text) return textTEMPLATE_PATH = os.path.join(os.path.dirname(__file__), "report_template.html")
def md_to_html(text: str) -> str: """Convert basic markdown to clean HTML for the PDF template.""" lines = text.splitlines() html_parts = [] in_ul = False
for line in lines: line = line.strip()
# Close open list if needed if in_ul and not (line.startswith("- ") or line.startswith("* ")): html_parts.append("</ul>") in_ul = False
if not line: continue elif line.startswith("## "): content = re.sub(r"\*\*(.*?)\*\*", r"<strong>\1</strong>", line[3:]) html_parts.append(f"<h2>{content}</h2>") elif line.startswith("### "): content = re.sub(r"\*\*(.*?)\*\*", r"<strong>\1</strong>", line[4:]) html_parts.append(f"<h3>{content}</h3>") elif line.startswith("- ") or line.startswith("* "): if not in_ul: html_parts.append("<ul>") in_ul = True content = re.sub(r"\*\*(.*?)\*\*", r"<strong>\1</strong>", line[2:]) html_parts.append(f"<li>{content}</li>") elif re.match(r"^\d+\.", line): content = re.sub(r"\*\*(.*?)\*\*", r"<strong>\1</strong>", line) html_parts.append(f"<p>{content}</p>") else: content = re.sub(r"\*\*(.*?)\*\*", r"<strong>\1</strong>", line) html_parts.append(f"<p>{content}</p>")
if in_ul: html_parts.append("</ul>")
return "\n".join(html_parts)
def build_pdf(analysis: FullAnalysis, name: str, role: str) -> bytes: """Clean black-and-white PDF report.""" buf = io.BytesIO() INK = colors.HexColor("#111827") INK2 = colors.HexColor("#374151") GRAY = colors.HexColor("#6b7280") LGRAY = colors.HexColor("#d1d5db") W = A4[0] - 48 * mm
doc = SimpleDocTemplate( buf, pagesize=A4, rightMargin=24 * mm, leftMargin=24 * mm, topMargin=24 * mm, bottomMargin=24 * mm, ) styles = getSampleStyleSheet()
s_title = ParagraphStyle("t", parent=styles["Normal"], fontSize=20, fontName="Helvetica-Bold", textColor=INK, spaceAfter=3) s_meta = ParagraphStyle("m", parent=styles["Normal"], fontSize=10, fontName="Helvetica", textColor=GRAY, spaceAfter=14) s_section_head = ParagraphStyle("sh", parent=styles["Normal"], fontSize=11, fontName="Helvetica-Bold", textColor=INK, spaceBefore=20, spaceAfter=2) s_section_num = ParagraphStyle("sn", parent=styles["Normal"], fontSize=10, fontName="Helvetica", textColor=GRAY, spaceAfter=8) s_h2 = ParagraphStyle("h2", parent=styles["Normal"], fontSize=10, fontName="Helvetica-Bold", textColor=INK, spaceBefore=10, spaceAfter=3) s_h3 = ParagraphStyle("h3", parent=styles["Normal"], fontSize=10, fontName="Helvetica-Bold", textColor=INK2, spaceBefore=7, spaceAfter=2) s_body = ParagraphStyle("b", parent=styles["Normal"], fontSize=10, fontName="Helvetica", textColor=INK2, leading=15, spaceAfter=3) s_bullet = ParagraphStyle("bl", parent=styles["Normal"], fontSize=10, fontName="Helvetica", textColor=INK2, leading=15, spaceAfter=2, leftIndent=12, firstLineIndent=-12) s_footer = ParagraphStyle("f", parent=styles["Normal"], fontSize=8, fontName="Helvetica", textColor=GRAY, alignment=1)
SECTIONS = [ ("Problem Analysis", analysis.problem_statement), ("Root Cause", analysis.root_causes), ("Solutions", analysis.solutions), ("Action Plan", analysis.action_plan), ("Reflection", analysis.thinking_feedback), """Render Jinja2 HTML template and convert to PDF via WeasyPrint.""" with open(TEMPLATE_PATH, "r", encoding="utf-8") as f: template = Template(f.read())
sections = [ {"title": "Problem Analysis", "html": md_to_html(analysis.problem_statement)}, {"title": "Root Cause", "html": md_to_html(analysis.root_causes)}, {"title": "Solutions", "html": md_to_html(analysis.solutions)}, {"title": "Action Plan", "html": md_to_html(analysis.action_plan)}, {"title": "Reflection", "html": md_to_html(analysis.thinking_feedback)}, ]
def render_block(md_text: str) -> list: out = [] for line in md_text.splitlines(): line = line.strip() if not line: out.append(Spacer(1, 3)) elif line.startswith("## "): out.append(Paragraph(strip_md(line[3:]), s_h2)) elif line.startswith("### "): out.append(Paragraph(strip_md(line[4:]), s_h3)) elif line.startswith("- ") or line.startswith("* "): out.append(Paragraph(f"β {strip_md(line[2:])}", s_bullet)) elif re.match(r"^\d+\.", line): out.append(Paragraph(strip_md(line), s_body)) else: out.append(Paragraph(strip_md(line), s_body)) return out
story = []
# Header story.append(Paragraph("Problem Analysis", s_title)) story.append(Paragraph( f"{name} Β· {datetime.now().strftime('%d %B %Y')}", s_meta, )) story.append(HRFlowable(width=W, thickness=0.5, color=LGRAY, spaceAfter=4))
# Sections for i, (title, text) in enumerate(SECTIONS, 1): story.append(Spacer(1, 4)) story.append(Paragraph(title, s_section_head)) story.append(HRFlowable(width=W, thickness=0.5, color=LGRAY, spaceAfter=6)) story += render_block(text)
# Footer story.append(Spacer(1, 20)) story.append(HRFlowable(width=W, thickness=0.5, color=LGRAY, spaceAfter=6)) story.append(Paragraph( f"Problem Solver Β· {datetime.now().strftime('%d %B %Y')}", s_footer, ))
doc.build(story) buf.seek(0) return buf.read() html_str = template.render( user_name=name, date=datetime.now().strftime("%d %B %Y"), sections=sections, page_breaks={3, 4}, # start Solutions and Action Plan on new page )
pdf_bytes = HTML(string=html_str, base_url=None).write_pdf() return pdf_bytes
# ββ API Endpoints βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββmain.py+63-107