Keep the author's header at the gate, and let the gate add and export
Browse filesFour things wrong at the review gate, three of them one cause.
The structure was protected from the agent's edits and the header was not.
Every header field goes into the outline prompt and comes back out of it, and
`restore` returned `{**outline, "chapters": restored}` - so the title, the
audience, the description and the page count stayed whatever the agent sent
back. An audience written carefully by the designer returns paraphrased and
shorter; a page count typed into a form returns as the agent's number, and it
is the number every later stage divides its budget by. Restored now, with one
exception that is the rule rather than an exception to it: a field the author
left blank has no author's version to put back, and a description written for
a book that had none is the agent doing its job.
The fourth: `Chapter.outcome` is required in the schema with a floor of twelve
characters and the prompt prints it in the JSON it asks for, and on a real
two-chapter run both chapters came back empty. That is not only a blank line
at the gate - `book_content` puts «Chapter Outcome:» into the writing prompt
for every subsection of the chapter, so the whole chapter gets written with
nothing said about what it is for. One small call fills only the chapters that
are missing one, from their own section titles; a chapter whose outcome still
cannot be had keeps it empty rather than being given an invented sentence,
because a person writing one line beats a model writing a plausible one.
And two things the gate could not do.
It could delete a row and not add one, which makes it a place to cut a design
down and never to correct it - a محور the reader left out is as wrong as one
they did not want. A new row is shaped from the rows beside it, so a chapter
added at the gate carries every field a chapter has rather than reaching the
next step as a bare title it cannot read.
And it could only be read as a form, one field at a time, which is the wrong
shape for the question the reviewer is actually being asked: does this hold
together. There is now a Word file, rendered by shape like the editor itself -
a bag and a book and a level all print without the renderer knowing what any
of them is - with any unsaved edit saved first so the file is the design on
screen. A blank field prints as «—» rather than vanishing, because an empty
outcome is the thing most worth seeing.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
- apps/api/app/api/v1/routes.py +38 -1
- apps/api/app/pipelines/books/steps.py +28 -0
- apps/api/app/services/blueprint/docx_preview.py +177 -0
- apps/api/app/services/books/outcomes.py +138 -0
- apps/api/app/services/books/outline_fidelity.py +63 -0
- apps/api/tests/test_blueprint_docx_preview.py +116 -0
- apps/api/tests/test_outline_header_fidelity.py +178 -0
- apps/web/src/components/BlueprintReview.tsx +64 -2
- apps/web/src/components/blueprintAdd.test.ts +70 -0
- apps/web/src/lib/api.ts +23 -0
|
@@ -6,8 +6,9 @@ import asyncio
|
|
| 6 |
import json
|
| 7 |
import uuid
|
| 8 |
from datetime import UTC, datetime
|
|
|
|
| 9 |
|
| 10 |
-
from fastapi import HTTPException, Query, status
|
| 11 |
from fastapi.responses import HTMLResponse
|
| 12 |
from pydantic import ValidationError
|
| 13 |
from sqlalchemy import func, select
|
|
@@ -564,6 +565,42 @@ async def read_review(run_id: uuid.UUID, user: ApprovedUser, db: Db) -> dict:
|
|
| 564 |
}
|
| 565 |
|
| 566 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
@router.patch("/runs/{run_id}/review", tags=["runs"])
|
| 568 |
async def update_review(
|
| 569 |
run_id: uuid.UUID, payload: s.ReviewUpdate, user: ApprovedUser, db: Db
|
|
|
|
| 6 |
import json
|
| 7 |
import uuid
|
| 8 |
from datetime import UTC, datetime
|
| 9 |
+
from urllib.parse import quote
|
| 10 |
|
| 11 |
+
from fastapi import HTTPException, Query, Response, status
|
| 12 |
from fastapi.responses import HTMLResponse
|
| 13 |
from pydantic import ValidationError
|
| 14 |
from sqlalchemy import func, select
|
|
|
|
| 565 |
}
|
| 566 |
|
| 567 |
|
| 568 |
+
@router.get("/runs/{run_id}/review.docx", tags=["runs"])
|
| 569 |
+
async def download_review(run_id: uuid.UUID, user: ApprovedUser, db: Db) -> Response:
|
| 570 |
+
"""The blueprint as a Word file, before it is approved.
|
| 571 |
+
|
| 572 |
+
The gate's editor is a form, which is right for correcting a title in place
|
| 573 |
+
and wrong for the question the reviewer is actually asking - does this hold
|
| 574 |
+
together - which needs the whole structure on a page in the order it will
|
| 575 |
+
read. Rendered from what the run is holding right now, so it includes any
|
| 576 |
+
edit already saved.
|
| 577 |
+
"""
|
| 578 |
+
run, row = await _run_at_gate(db, user, run_id)
|
| 579 |
+
step = _gate_step(run.pipeline_key)
|
| 580 |
+
|
| 581 |
+
from app.services.blueprint.docx_preview import render
|
| 582 |
+
|
| 583 |
+
title = (step.gate_title_ar or step.title_ar) if step else "التصور الفني"
|
| 584 |
+
data = await asyncio.to_thread(render, row.output or {}, title_ar=title)
|
| 585 |
+
stamp = datetime.now(UTC).strftime("%Y%m%d-%H%M")
|
| 586 |
+
return Response(
|
| 587 |
+
content=data,
|
| 588 |
+
media_type=(
|
| 589 |
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
| 590 |
+
),
|
| 591 |
+
headers={
|
| 592 |
+
# The filename is ASCII for the header and UTF-8 for anything that
|
| 593 |
+
# reads RFC 5987, so a browser that does not gets a name it can
|
| 594 |
+
# still save rather than a mangled one.
|
| 595 |
+
"Content-Disposition": (
|
| 596 |
+
f'attachment; filename="blueprint-{stamp}.docx"; '
|
| 597 |
+
f"filename*=UTF-8''"
|
| 598 |
+
+ quote(f"التصور الفني - {stamp}.docx")
|
| 599 |
+
),
|
| 600 |
+
},
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
@router.patch("/runs/{run_id}/review", tags=["runs"])
|
| 605 |
async def update_review(
|
| 606 |
run_id: uuid.UUID, payload: s.ReviewUpdate, user: ApprovedUser, db: Db
|
|
@@ -687,6 +687,34 @@ class OutlineStep(Step):
|
|
| 687 |
outline = _trim_subsections(
|
| 688 |
outline, int(brief.get("total_pages") or 0), total
|
| 689 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 690 |
return outline
|
| 691 |
|
| 692 |
|
|
|
|
| 687 |
outline = _trim_subsections(
|
| 688 |
outline, int(brief.get("total_pages") or 0), total
|
| 689 |
)
|
| 690 |
+
|
| 691 |
+
# The structure was protected from the agent's edits and the header was
|
| 692 |
+
# not. Every header field goes into the prompt and comes back out of
|
| 693 |
+
# it, and what came back was kept - so a carefully written target
|
| 694 |
+
# audience returns paraphrased and shorter, a description returns
|
| 695 |
+
# rewritten, and the page count returns as the agent's number rather
|
| 696 |
+
# than the one typed into the form. Only a field the author left blank
|
| 697 |
+
# keeps the agent's version, because there is nothing to put back.
|
| 698 |
+
from app.services.books.outline_fidelity import bare_outcomes, restore_header
|
| 699 |
+
|
| 700 |
+
outline, changed = restore_header(
|
| 701 |
+
outline, units, int(brief.get("total_pages") or 0)
|
| 702 |
+
)
|
| 703 |
+
if changed:
|
| 704 |
+
print(f"↩️ أُعيدت بيانات المؤلف: {' · '.join(changed)}")
|
| 705 |
+
|
| 706 |
+
# A chapter with no outcome is not just a blank line at the gate:
|
| 707 |
+
# `book_content` puts «Chapter Outcome:» into the writing prompt for
|
| 708 |
+
# every subsection under it, so the whole chapter gets written with
|
| 709 |
+
# nothing said about what it is for.
|
| 710 |
+
if bare_outcomes(outline):
|
| 711 |
+
from app.services.books.outcomes import fill_outcomes
|
| 712 |
+
|
| 713 |
+
await ctx.progress("كتابة نواتج التعلّم الناقصة", 1.0)
|
| 714 |
+
outline, filled = fill_outcomes(outline)
|
| 715 |
+
still = bare_outcomes(outline)
|
| 716 |
+
print(f"🎯 نواتج التعلّم: كُتب {filled}"
|
| 717 |
+
+ (f" · ما زال {len(still)} فصلًا بلا ناتج" if still else ""))
|
| 718 |
return outline
|
| 719 |
|
| 720 |
|
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The blueprint as a Word file, for reading before it is approved.
|
| 2 |
+
|
| 3 |
+
The gate is a form. A form is the right thing for correcting a title in place
|
| 4 |
+
and the wrong thing for the question the reviewer is actually asking - does
|
| 5 |
+
this hold together as a book - which needs the whole structure on a page, in
|
| 6 |
+
order, the way it will read.
|
| 7 |
+
|
| 8 |
+
Rendered by shape, like the gate's own editor: a book's chapters, a bag's days
|
| 9 |
+
and a level's units all arrive as nested objects and arrays, so nothing here
|
| 10 |
+
knows what a chapter is. A new task type gets this for free.
|
| 11 |
+
|
| 12 |
+
Nothing is invented and nothing is dropped. A field with no value prints as
|
| 13 |
+
«—» rather than vanishing, because a blank outcome is the thing the reviewer
|
| 14 |
+
most needs to see.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import io
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
#: Keys whose value names the thing rather than describing it. The heading of a
|
| 23 |
+
#: row is the first of these it carries.
|
| 24 |
+
_TITLE_KEYS = ("title", "chapter_title", "section_title", "session_title",
|
| 25 |
+
"unit_title", "topic", "cover", "name", "bag_name", "book_title")
|
| 26 |
+
|
| 27 |
+
#: Printed as a line of their own under the heading, in this order, when a row
|
| 28 |
+
#: carries them. Everything else on the row follows in document order.
|
| 29 |
+
_LEAD = ("outcome", "overview", "purpose", "description", "goal")
|
| 30 |
+
|
| 31 |
+
#: Never printed: bookkeeping the reviewer did not write and cannot act on.
|
| 32 |
+
_SKIP = {"rag_context", "suggested_queries", "angles", "cover_index",
|
| 33 |
+
"topic_number", "day_number", "session_number", "_validation_failed",
|
| 34 |
+
"_missing", "_added_for_coverage"}
|
| 35 |
+
|
| 36 |
+
_LABELS = {
|
| 37 |
+
"chapters": "الفصول", "sections": "المحاور", "subsections": "المواضيع",
|
| 38 |
+
"units": "الوحدات", "topics": "الموضوعات", "covers": "المحاور",
|
| 39 |
+
"days": "الأيام", "sessions": "الجلسات", "points": "النقاط",
|
| 40 |
+
"outcome": "ناتج التعلّم", "overview": "نظرة عامة", "purpose": "الغرض",
|
| 41 |
+
"description": "الوصف", "book_description": "وصف الكتاب",
|
| 42 |
+
"target_audience": "الفئة المستهدفة", "book_title": "اسم الكتاب",
|
| 43 |
+
"bag_name": "اسم الحقيبة", "total_pages": "عدد الصفحات",
|
| 44 |
+
"est_pages": "الصفحات", "difficulty": "المستوى",
|
| 45 |
+
"learning_outcomes": "نواتج التعلّم", "outline_notes": "ملاحظات",
|
| 46 |
+
"goal": "الهدف", "title": "العنوان", "domain": "المجال",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def label(key: str) -> str:
|
| 51 |
+
return _LABELS.get(key, key.replace("_", " "))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def title_of(row: Any, index: int) -> str:
|
| 55 |
+
"""What a repeated row is called."""
|
| 56 |
+
if isinstance(row, str):
|
| 57 |
+
return row
|
| 58 |
+
if isinstance(row, dict):
|
| 59 |
+
for key in _TITLE_KEYS:
|
| 60 |
+
value = str(row.get(key) or "").strip()
|
| 61 |
+
if value:
|
| 62 |
+
return value
|
| 63 |
+
return f"عنصر {index + 1}"
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _is_rows(value: Any) -> bool:
|
| 67 |
+
return isinstance(value, list) and any(isinstance(x, dict) for x in value)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _scalars(row: dict) -> list[tuple[str, Any]]:
|
| 71 |
+
"""The row's own fields, lead fields first, bookkeeping dropped."""
|
| 72 |
+
plain = [(k, v) for k, v in row.items()
|
| 73 |
+
if k not in _SKIP and not isinstance(v, (list, dict))
|
| 74 |
+
and k not in _TITLE_KEYS]
|
| 75 |
+
lead = [kv for kv in plain if kv[0] in _LEAD]
|
| 76 |
+
rest = [kv for kv in plain if kv[0] not in _LEAD]
|
| 77 |
+
return sorted(lead, key=lambda kv: _LEAD.index(kv[0])) + rest
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _write_row(doc, row: Any, index: int, depth: int) -> None:
|
| 81 |
+
from docx.shared import Pt
|
| 82 |
+
|
| 83 |
+
heading = doc.add_paragraph()
|
| 84 |
+
heading.paragraph_format.space_before = Pt(10 if depth < 2 else 6)
|
| 85 |
+
run = heading.add_run(f"{index + 1}. {title_of(row, index)}")
|
| 86 |
+
run.bold = True
|
| 87 |
+
run.font.size = Pt(max(15 - depth * 2, 10))
|
| 88 |
+
|
| 89 |
+
if not isinstance(row, dict):
|
| 90 |
+
return
|
| 91 |
+
|
| 92 |
+
for key, value in _scalars(row):
|
| 93 |
+
text = str(value).strip() if value not in (None, "") else "—"
|
| 94 |
+
para = doc.add_paragraph()
|
| 95 |
+
para.paragraph_format.left_indent = Pt(14 * (depth + 1))
|
| 96 |
+
para.add_run(f"{label(key)}: ").bold = True
|
| 97 |
+
emphasis = para.add_run(text)
|
| 98 |
+
if text == "—":
|
| 99 |
+
emphasis.italic = True
|
| 100 |
+
|
| 101 |
+
for key, value in row.items():
|
| 102 |
+
if key in _SKIP:
|
| 103 |
+
continue
|
| 104 |
+
if _is_rows(value):
|
| 105 |
+
head = doc.add_paragraph()
|
| 106 |
+
head.paragraph_format.left_indent = Pt(14 * (depth + 1))
|
| 107 |
+
head.add_run(f"{label(key)} ({len(value)})").bold = True
|
| 108 |
+
for i, child in enumerate(value):
|
| 109 |
+
_write_row(doc, child, i, depth + 1)
|
| 110 |
+
elif isinstance(value, list) and value:
|
| 111 |
+
for item in value:
|
| 112 |
+
bullet = doc.add_paragraph(style="List Bullet")
|
| 113 |
+
bullet.paragraph_format.left_indent = Pt(14 * (depth + 2))
|
| 114 |
+
bullet.add_run(str(item))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def render(blueprint: dict[str, Any], *, title_ar: str = "التصور الفني") -> bytes:
|
| 118 |
+
"""The blueprint as a .docx, in the order it is held."""
|
| 119 |
+
from docx import Document
|
| 120 |
+
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
| 121 |
+
from docx.shared import Pt
|
| 122 |
+
|
| 123 |
+
from app.services.books.docx_book import force_rtl
|
| 124 |
+
|
| 125 |
+
doc = Document()
|
| 126 |
+
normal = doc.styles["Normal"]
|
| 127 |
+
normal.font.name = "Arial"
|
| 128 |
+
normal.font.size = Pt(11)
|
| 129 |
+
|
| 130 |
+
head = doc.add_paragraph()
|
| 131 |
+
head.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 132 |
+
run = head.add_run(title_ar)
|
| 133 |
+
run.bold = True
|
| 134 |
+
run.font.size = Pt(20)
|
| 135 |
+
|
| 136 |
+
name = next((str(blueprint.get(k)) for k in ("book_title", "bag_name", "title")
|
| 137 |
+
if str(blueprint.get(k) or "").strip()), "")
|
| 138 |
+
if name:
|
| 139 |
+
sub = doc.add_paragraph()
|
| 140 |
+
sub.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 141 |
+
sub.add_run(name).font.size = Pt(14)
|
| 142 |
+
|
| 143 |
+
# The header first - the fields the reviewer said were changing on them -
|
| 144 |
+
# then every repeated level under it.
|
| 145 |
+
for key, value in blueprint.items():
|
| 146 |
+
if key in _SKIP or _is_rows(value) or isinstance(value, dict):
|
| 147 |
+
continue
|
| 148 |
+
if isinstance(value, list):
|
| 149 |
+
if value:
|
| 150 |
+
doc.add_paragraph().add_run(f"{label(key)}:").bold = True
|
| 151 |
+
for item in value:
|
| 152 |
+
doc.add_paragraph(str(item), style="List Bullet")
|
| 153 |
+
continue
|
| 154 |
+
text = str(value).strip() if value not in (None, "") else "—"
|
| 155 |
+
para = doc.add_paragraph()
|
| 156 |
+
para.add_run(f"{label(key)}: ").bold = True
|
| 157 |
+
emphasis = para.add_run(text)
|
| 158 |
+
if text == "—":
|
| 159 |
+
emphasis.italic = True
|
| 160 |
+
|
| 161 |
+
for key, value in blueprint.items():
|
| 162 |
+
if key in _SKIP or not _is_rows(value):
|
| 163 |
+
continue
|
| 164 |
+
section = doc.add_paragraph()
|
| 165 |
+
section.paragraph_format.space_before = Pt(16)
|
| 166 |
+
section.add_run(f"{label(key)} ({len(value)})").bold = True
|
| 167 |
+
section.runs[0].font.size = Pt(16)
|
| 168 |
+
for i, row in enumerate(value):
|
| 169 |
+
_write_row(doc, row, i, 0)
|
| 170 |
+
|
| 171 |
+
force_rtl(doc)
|
| 172 |
+
buffer = io.BytesIO()
|
| 173 |
+
doc.save(buffer)
|
| 174 |
+
return buffer.getvalue()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
__all__ = ["render"]
|
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The learning outcome each chapter is supposed to carry.
|
| 2 |
+
|
| 3 |
+
`Chapter.outcome` is required in the schema with a floor of twelve characters,
|
| 4 |
+
and the outline prompt asks for it by name in the JSON it prints. Chapters
|
| 5 |
+
still come back with an empty one - an instruction is not a constraint, and
|
| 6 |
+
neither is a schema when the reply is read as raw JSON rather than validated
|
| 7 |
+
into the model. On a real two-chapter run both came back blank.
|
| 8 |
+
|
| 9 |
+
Filled here rather than left to the gate, because an empty outcome is not only
|
| 10 |
+
a blank line on the review screen: `book_content` puts «Chapter Outcome:» into
|
| 11 |
+
the writing prompt for every subsection of that chapter, so a chapter with no
|
| 12 |
+
outcome is written with nothing said about what it is for.
|
| 13 |
+
|
| 14 |
+
One call for the whole book, listing only what the chapters are called and what
|
| 15 |
+
is under them - no prose, no evidence. Only the chapters actually missing an
|
| 16 |
+
outcome are asked about, so a book whose agent did its job pays nothing.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import json
|
| 22 |
+
import logging
|
| 23 |
+
import re
|
| 24 |
+
from typing import Any
|
| 25 |
+
|
| 26 |
+
log = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
MODELS_TO_TRY = [
|
| 29 |
+
"openai/gpt-4.1-mini",
|
| 30 |
+
"google/gemini-2.5-flash",
|
| 31 |
+
"openai/gpt-4o-mini",
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
#: Long enough to say something, short enough to stay a sentence. The schema's
|
| 35 |
+
#: own floor is twelve characters; this is the same rule read as words.
|
| 36 |
+
MIN_WORDS = 4
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _digest(chapter: dict) -> dict:
|
| 40 |
+
"""What a chapter is called and what is under it. Titles only."""
|
| 41 |
+
return {
|
| 42 |
+
"chapter_title": str(chapter.get("chapter_title") or ""),
|
| 43 |
+
"sections": [
|
| 44 |
+
str(s.get("title") or "")
|
| 45 |
+
for s in (chapter.get("sections") or [])
|
| 46 |
+
if isinstance(s, dict)
|
| 47 |
+
],
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _ask(missing: list[dict], book_title: str, audience: str) -> dict[str, str]:
|
| 52 |
+
import litellm
|
| 53 |
+
|
| 54 |
+
from app.core.config import settings
|
| 55 |
+
|
| 56 |
+
prompt = (
|
| 57 |
+
"أنت محلل مناهج. أمامك فصول من كتاب، ولكل فصل عنوانه وعناوين محاوره.\n"
|
| 58 |
+
f"الكتاب: {book_title}\nالفئة المستهدفة: {audience}\n\n"
|
| 59 |
+
"اكتب لكل فصل ناتج تعلّم واحدًا: جملة واحدة تصف ما يصير القارئ قادرًا "
|
| 60 |
+
"عليه بعد قراءة الفصل. من 8 إلى 25 كلمة.\n\n"
|
| 61 |
+
"القواعد:\n"
|
| 62 |
+
"1) ابنِ الناتج على محاور الفصل وحدها. لا تضف موضوعًا ليس فيها.\n"
|
| 63 |
+
"2) لا تعد صياغة عنوان الفصل؛ الناتج يصف قدرة، لا يسمّي محتوى.\n"
|
| 64 |
+
"3) بالعربية، وبنفس ترتيب الفصول المعطاة.\n"
|
| 65 |
+
"4) أعد JSON فقط بالشكل: "
|
| 66 |
+
'{"outcomes": [{"chapter_title": "...", "outcome": "..."}]}\n\n'
|
| 67 |
+
"الفصول:\n" + json.dumps(missing, ensure_ascii=False, indent=1)
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
for model in MODELS_TO_TRY:
|
| 71 |
+
try:
|
| 72 |
+
response = litellm.completion(
|
| 73 |
+
model=f"openrouter/{model}",
|
| 74 |
+
api_key=settings.openrouter_api_key,
|
| 75 |
+
api_base="https://openrouter.ai/api/v1",
|
| 76 |
+
messages=[{"role": "user", "content": prompt}],
|
| 77 |
+
response_format={"type": "json_object"},
|
| 78 |
+
timeout=90,
|
| 79 |
+
)
|
| 80 |
+
raw = (response.choices[0].message.content or "").strip()
|
| 81 |
+
raw = re.sub(r"^```(?:json)?|```$", "", raw, flags=re.M).strip()
|
| 82 |
+
data = json.loads(raw[raw.find("{") : raw.rfind("}") + 1])
|
| 83 |
+
return {
|
| 84 |
+
str(x.get("chapter_title") or "").strip():
|
| 85 |
+
str(x.get("outcome") or "").strip()
|
| 86 |
+
for x in (data.get("outcomes") or [])
|
| 87 |
+
if isinstance(x, dict)
|
| 88 |
+
}
|
| 89 |
+
except Exception as exc: # noqa: BLE001 - try the next model
|
| 90 |
+
log.warning("outcome fill failed on %s: %s", model, exc)
|
| 91 |
+
return {}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def fill_outcomes(outline: dict[str, Any]) -> tuple[dict[str, Any], int]:
|
| 95 |
+
"""The outline with every chapter carrying an outcome, and how many were
|
| 96 |
+
filled.
|
| 97 |
+
|
| 98 |
+
Matched back by title, then by position for a chapter whose title the reply
|
| 99 |
+
edited. A chapter whose outcome still cannot be had keeps its empty one
|
| 100 |
+
rather than being given an invented sentence - the gate shows it, and a
|
| 101 |
+
person writing one line is better than a model writing a plausible one.
|
| 102 |
+
"""
|
| 103 |
+
chapters = [c for c in (outline.get("chapters") or []) if isinstance(c, dict)]
|
| 104 |
+
missing = [c for c in chapters if not str(c.get("outcome") or "").strip()]
|
| 105 |
+
if not missing:
|
| 106 |
+
return outline, 0
|
| 107 |
+
|
| 108 |
+
got = _ask(
|
| 109 |
+
[_digest(c) for c in missing],
|
| 110 |
+
str(outline.get("book_title") or ""),
|
| 111 |
+
str(outline.get("target_audience") or ""),
|
| 112 |
+
)
|
| 113 |
+
if not got:
|
| 114 |
+
return outline, 0
|
| 115 |
+
|
| 116 |
+
spare = [v for v in got.values() if len(v.split()) >= MIN_WORDS]
|
| 117 |
+
filled = 0
|
| 118 |
+
out: list[dict] = []
|
| 119 |
+
for chapter in chapters:
|
| 120 |
+
if str(chapter.get("outcome") or "").strip():
|
| 121 |
+
out.append(chapter)
|
| 122 |
+
continue
|
| 123 |
+
title = str(chapter.get("chapter_title") or "").strip()
|
| 124 |
+
text = got.get(title, "")
|
| 125 |
+
if len(text.split()) < MIN_WORDS:
|
| 126 |
+
text = spare.pop(0) if spare else ""
|
| 127 |
+
elif text in spare:
|
| 128 |
+
spare.remove(text)
|
| 129 |
+
if text:
|
| 130 |
+
filled += 1
|
| 131 |
+
out.append({**chapter, "outcome": text})
|
| 132 |
+
else:
|
| 133 |
+
out.append(chapter)
|
| 134 |
+
|
| 135 |
+
return {**outline, "chapters": out}, filled
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
__all__ = ["fill_outcomes"]
|
|
@@ -128,3 +128,66 @@ def restore(outline: dict, units: list[dict]) -> tuple[dict, dict]:
|
|
| 128 |
log.warning("%s محور came back with no subsections", report["sections_bare"])
|
| 129 |
|
| 130 |
return {**outline, "chapters": restored}, report
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
log.warning("%s محور came back with no subsections", report["sections_bare"])
|
| 129 |
|
| 130 |
return {**outline, "chapters": restored}, report
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
#: The header fields the agent re-emits, and what each is called on the units
|
| 134 |
+
#: the author's own design was read into.
|
| 135 |
+
_HEADER = (
|
| 136 |
+
("book_title", "course_name"),
|
| 137 |
+
("target_audience", "course_audience"),
|
| 138 |
+
("book_description", "course_description"),
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def restore_header(outline: dict, units: dict, total_pages: int = 0) -> tuple[dict, list[str]]:
|
| 143 |
+
"""The author's own header, put back over the agent's version of it.
|
| 144 |
+
|
| 145 |
+
The structure was already protected this way and the header was not. Every
|
| 146 |
+
one of these fields goes into the prompt and comes back out of it, and what
|
| 147 |
+
came back was kept - so a target audience written carefully by the designer
|
| 148 |
+
returns paraphrased and shorter, a description returns rewritten, and the
|
| 149 |
+
page count returns as whatever number the agent settled on rather than the
|
| 150 |
+
one that was typed into the form.
|
| 151 |
+
|
| 152 |
+
Blank is the one case where the agent's version wins, and it is not an
|
| 153 |
+
exception to the rule but the rule itself: a field the author left empty
|
| 154 |
+
has no author's version to restore, and a description written for a book
|
| 155 |
+
that had none is the agent doing its job.
|
| 156 |
+
"""
|
| 157 |
+
fixed = dict(outline)
|
| 158 |
+
changed: list[str] = []
|
| 159 |
+
|
| 160 |
+
for field, source in _HEADER:
|
| 161 |
+
supplied = str(units.get(source) or "").strip()
|
| 162 |
+
if not supplied:
|
| 163 |
+
continue
|
| 164 |
+
drawn = str(fixed.get(field) or "").strip()
|
| 165 |
+
if drawn != supplied:
|
| 166 |
+
changed.append(f"{field}: «{drawn[:40]}» ← «{supplied[:40]}»")
|
| 167 |
+
fixed[field] = supplied
|
| 168 |
+
|
| 169 |
+
# The page count is a number a person typed into a form. It decides the
|
| 170 |
+
# budget every later stage divides up, so an agent's opinion about it is
|
| 171 |
+
# not a second opinion - it is a different book.
|
| 172 |
+
if total_pages:
|
| 173 |
+
if int(fixed.get("total_pages") or 0) != int(total_pages):
|
| 174 |
+
changed.append(f"total_pages: {fixed.get('total_pages')} ← {total_pages}")
|
| 175 |
+
fixed["total_pages"] = int(total_pages)
|
| 176 |
+
|
| 177 |
+
return fixed, changed
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def bare_outcomes(outline: dict) -> list[str]:
|
| 181 |
+
"""Chapters that came back with no learning outcome.
|
| 182 |
+
|
| 183 |
+
The schema marks it required with a floor of twelve characters and the
|
| 184 |
+
prompt asks for it by name, and chapters still arrive with an empty one -
|
| 185 |
+
an instruction is not a constraint, and neither, it turns out, is a schema
|
| 186 |
+
when the reply is read as raw JSON. Reported so the gate can show the hole
|
| 187 |
+
instead of printing a heading with nothing under it.
|
| 188 |
+
"""
|
| 189 |
+
return [
|
| 190 |
+
str(ch.get("chapter_title") or "")
|
| 191 |
+
for ch in (outline.get("chapters") or [])
|
| 192 |
+
if isinstance(ch, dict) and not str(ch.get("outcome") or "").strip()
|
| 193 |
+
]
|
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The blueprint as a Word file, read before it is approved.
|
| 2 |
+
|
| 3 |
+
The gate is a form: right for correcting a title in place, wrong for the
|
| 4 |
+
question the reviewer is actually asking - does this hold together as a book -
|
| 5 |
+
which needs the whole structure on a page in the order it will read.
|
| 6 |
+
|
| 7 |
+
Rendered by shape, like the gate's own editor, so a bag and a book and a level
|
| 8 |
+
all print without this module knowing what any of them is.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import io
|
| 14 |
+
|
| 15 |
+
from docx import Document
|
| 16 |
+
|
| 17 |
+
from app.services.blueprint.docx_preview import render, title_of
|
| 18 |
+
|
| 19 |
+
BOOK = {
|
| 20 |
+
"book_title": "عادات استخدام الأدوات الذكية",
|
| 21 |
+
"target_audience": "موظفو الإدارات في القطاع الخاص",
|
| 22 |
+
"total_pages": 24,
|
| 23 |
+
"chapters": [{
|
| 24 |
+
"chapter_title": "الفصل الأول: ما الذي تغيّر",
|
| 25 |
+
"outcome": "",
|
| 26 |
+
"sections": [{
|
| 27 |
+
"title": "الفرق بين الأتمتة والمساعدة",
|
| 28 |
+
"overview": "نستعرض الفرق الجوهري بينهما.",
|
| 29 |
+
"subsections": [
|
| 30 |
+
{"title": "كيف تعمل الأتمتة؟", "purpose": "شرح مبسط",
|
| 31 |
+
"est_pages": 1, "difficulty": "basic",
|
| 32 |
+
"suggested_queries": ["ما هي الأتمتة؟"],
|
| 33 |
+
"rag_context": {"chunks": [{"text": "نص طويل جدًا"}]}},
|
| 34 |
+
],
|
| 35 |
+
}],
|
| 36 |
+
}],
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def text_of(data: bytes) -> list[str]:
|
| 41 |
+
return [p.text for p in Document(io.BytesIO(data)).paragraphs if p.text.strip()]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_the_whole_tree_is_on_the_page_in_order():
|
| 45 |
+
lines = text_of(render(BOOK))
|
| 46 |
+
joined = "\n".join(lines)
|
| 47 |
+
for expected in ("الفصول (1)", "الفصل الأول: ما الذي تغيّر", "المحاور (1)",
|
| 48 |
+
"الفرق بين الأتمتة والمساعدة", "المواضيع (1)",
|
| 49 |
+
"كيف تعمل الأتمتة؟"):
|
| 50 |
+
assert expected in joined, expected
|
| 51 |
+
assert joined.index("الفصل الأول") < joined.index("الفرق بين")
|
| 52 |
+
assert joined.index("الفرق بين") < joined.index("كيف تعمل")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_the_header_the_reviewer_came_to_check_is_at_the_top():
|
| 56 |
+
lines = text_of(render(BOOK))
|
| 57 |
+
head = "\n".join(lines[:8])
|
| 58 |
+
assert "عدد الصفحات: 24" in head
|
| 59 |
+
assert "الفئة المستهدفة: موظفو الإدارات في القطاع الخاص" in head
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_a_blank_field_prints_as_a_gap_rather_than_vanishing():
|
| 63 |
+
"""An empty outcome is the thing the reviewer most needs to see."""
|
| 64 |
+
assert "ناتج التعلّم: —" in "\n".join(text_of(render(BOOK)))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_bookkeeping_the_reviewer_cannot_act_on_is_left_out():
|
| 68 |
+
joined = "\n".join(text_of(render(BOOK)))
|
| 69 |
+
assert "نص طويل جدًا" not in joined # rag_context
|
| 70 |
+
assert "ما هي الأتمتة؟" not in joined # suggested_queries
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def test_what_the_reviewer_can_act_on_is_kept():
|
| 74 |
+
joined = "\n".join(text_of(render(BOOK)))
|
| 75 |
+
assert "الغرض: شرح مبسط" in joined
|
| 76 |
+
assert "الصفحات: 1" in joined
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_a_bag_prints_without_this_module_knowing_what_a_bag_is():
|
| 80 |
+
bag = {"bag_name": "قياس الأثر", "days": [
|
| 81 |
+
{"day_number": 1, "sessions": [
|
| 82 |
+
{"session_number": 1, "session_title": "الجلسة الأولى",
|
| 83 |
+
"topics": [{"topic": "موضوع", "covers": [{"cover": "محور"}]}]}]}]}
|
| 84 |
+
joined = "\n".join(text_of(render(bag)))
|
| 85 |
+
for expected in ("الأيام (1)", "الجلسة الأولى", "الجلسات (1)",
|
| 86 |
+
"الموضوعات (1)", "موضوع", "محور"):
|
| 87 |
+
assert expected in joined, expected
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def test_an_empty_blueprint_still_makes_a_file():
|
| 91 |
+
assert len(render({})) > 0
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_the_document_is_right_to_left():
|
| 95 |
+
from docx.oxml.ns import qn
|
| 96 |
+
|
| 97 |
+
doc = Document(io.BytesIO(render(BOOK)))
|
| 98 |
+
sect = doc.sections[0]._sectPr
|
| 99 |
+
assert sect.findall(qn("w:bidi"))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_a_row_is_named_by_whichever_field_names_it():
|
| 103 |
+
assert title_of({"chapter_title": "فصل"}, 0) == "فصل"
|
| 104 |
+
assert title_of({"cover": "محور"}, 0) == "محور"
|
| 105 |
+
assert title_of("نص", 3) == "نص"
|
| 106 |
+
assert title_of({"est_pages": 2}, 4) == "عنصر 5"
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_the_endpoint_renders_what_the_run_holds_now():
|
| 110 |
+
import inspect
|
| 111 |
+
|
| 112 |
+
from app.api.v1 import routes
|
| 113 |
+
|
| 114 |
+
src = inspect.getsource(routes.download_review)
|
| 115 |
+
assert "render, row.output or {}" in src
|
| 116 |
+
assert "_run_at_gate" in src
|
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The header the author typed, and the outcome every chapter owes.
|
| 2 |
+
|
| 3 |
+
Four complaints from the gate, and one cause behind three of them. Every header
|
| 4 |
+
field goes into the outline prompt and comes back out of it, and what came back
|
| 5 |
+
was kept: `restore` put the chapters back and returned `{**outline, ...}`, so
|
| 6 |
+
the title, the audience, the description and the page count stayed the agent's.
|
| 7 |
+
|
| 8 |
+
«عدد الصفحات بيتغير عن اللي أنا مدخله في الأول»
|
| 9 |
+
«الفئة المستهدفة بتتغير وأوقات بلاقيها بتصغر»
|
| 10 |
+
«الوصف نفس الكلام»
|
| 11 |
+
|
| 12 |
+
The fourth is its own thing: `Chapter.outcome` is required with a floor of
|
| 13 |
+
twelve characters and the prompt prints it in the JSON it asks for, and on a
|
| 14 |
+
real two-chapter run both chapters came back with an empty one.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from app.services.books.outline_fidelity import bare_outcomes, restore_header
|
| 20 |
+
|
| 21 |
+
#: What the author's design was read into.
|
| 22 |
+
UNITS = {
|
| 23 |
+
"course_name": "عادات استخدام الأدوات الذكية",
|
| 24 |
+
"course_audience": "موظفو الإدارات في القطاع الخاص الذين يستخدمون الأدوات "
|
| 25 |
+
"الذكية في مهامهم اليومية",
|
| 26 |
+
"course_description": "كتاب عملي يبني عادة استخدام سليمة على ثلاثة مستويات.",
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
#: What the agent sent back: shortened, paraphrased, and with its own number.
|
| 30 |
+
DRAWN = {
|
| 31 |
+
"book_title": "الأدوات الذكية",
|
| 32 |
+
"target_audience": "الموظفون",
|
| 33 |
+
"book_description": "كتاب عن الأدوات الذكية في العمل.",
|
| 34 |
+
"total_pages": 50,
|
| 35 |
+
"chapters": [{"chapter_title": "الفصل الأول", "outcome": "", "sections": []}],
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_the_audience_the_author_wrote_is_the_one_that_survives():
|
| 40 |
+
"""«بتتغير وأوقات بلاقيها بتصغر» - eleven words back as one."""
|
| 41 |
+
fixed, _ = restore_header(DRAWN, UNITS, 24)
|
| 42 |
+
assert fixed["target_audience"] == UNITS["course_audience"]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_the_description_and_the_title_too():
|
| 46 |
+
fixed, _ = restore_header(DRAWN, UNITS, 24)
|
| 47 |
+
assert fixed["book_description"] == UNITS["course_description"]
|
| 48 |
+
assert fixed["book_title"] == UNITS["course_name"]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_the_page_count_is_the_number_that_was_typed():
|
| 52 |
+
"""It decides the budget every later stage divides up, so the agent's
|
| 53 |
+
opinion about it is not a second opinion - it is a different book."""
|
| 54 |
+
fixed, _ = restore_header(DRAWN, UNITS, 24)
|
| 55 |
+
assert fixed["total_pages"] == 24
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_a_field_the_author_left_blank_keeps_the_agent_s():
|
| 59 |
+
"""Not an exception to the rule - there is nothing to put back, and a
|
| 60 |
+
description written for a book that had none is the agent doing its job."""
|
| 61 |
+
fixed, _ = restore_header(DRAWN, {**UNITS, "course_description": ""}, 24)
|
| 62 |
+
assert fixed["book_description"] == "كتاب عن الأدوات الذكية في العمل."
|
| 63 |
+
assert fixed["target_audience"] == UNITS["course_audience"]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_zero_pages_means_the_author_did_not_say():
|
| 67 |
+
"""The form's own default. Nothing to restore, so nothing is imposed."""
|
| 68 |
+
fixed, _ = restore_header(DRAWN, UNITS, 0)
|
| 69 |
+
assert fixed["total_pages"] == 50
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_every_change_is_reported_rather_than_made_quietly():
|
| 73 |
+
_, changed = restore_header(DRAWN, UNITS, 24)
|
| 74 |
+
assert len(changed) == 4
|
| 75 |
+
assert any("target_audience" in c for c in changed)
|
| 76 |
+
assert any("total_pages" in c for c in changed)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_an_agent_that_left_the_header_alone_reports_nothing():
|
| 80 |
+
honest = {**DRAWN, "book_title": UNITS["course_name"],
|
| 81 |
+
"target_audience": UNITS["course_audience"],
|
| 82 |
+
"book_description": UNITS["course_description"],
|
| 83 |
+
"total_pages": 24}
|
| 84 |
+
fixed, changed = restore_header(honest, UNITS, 24)
|
| 85 |
+
assert changed == []
|
| 86 |
+
assert fixed == honest
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_nothing_else_on_the_outline_is_touched():
|
| 90 |
+
fixed, _ = restore_header(DRAWN, UNITS, 24)
|
| 91 |
+
assert fixed["chapters"] == DRAWN["chapters"]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ───────────────────────────── ناتج التعلّم
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_a_chapter_with_no_outcome_is_named():
|
| 98 |
+
assert bare_outcomes(DRAWN) == ["الفصل الأول"]
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_a_whitespace_outcome_counts_as_none():
|
| 102 |
+
assert bare_outcomes({"chapters": [{"chapter_title": "ف", "outcome": " "}]})
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def test_a_chapter_that_has_one_is_not_reported():
|
| 106 |
+
ok = {"chapters": [{"chapter_title": "ف", "outcome": "أن يميّز القارئ بين الأتمتة والمساعدة."}]}
|
| 107 |
+
assert bare_outcomes(ok) == []
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_the_fill_asks_only_about_the_chapters_that_need_it(monkeypatch):
|
| 111 |
+
from app.services.books import outcomes
|
| 112 |
+
|
| 113 |
+
asked: list[list[dict]] = []
|
| 114 |
+
|
| 115 |
+
def fake(missing, book_title, audience):
|
| 116 |
+
asked.append(missing)
|
| 117 |
+
return {m["chapter_title"]: "أن يبني القارئ عادة استخدام سليمة للأدوات."
|
| 118 |
+
for m in missing}
|
| 119 |
+
|
| 120 |
+
monkeypatch.setattr(outcomes, "_ask", fake)
|
| 121 |
+
outline = {"chapters": [
|
| 122 |
+
{"chapter_title": "أ", "outcome": "ناتج موجود ومكتوب بالفعل هنا"},
|
| 123 |
+
{"chapter_title": "ب", "outcome": ""},
|
| 124 |
+
]}
|
| 125 |
+
fixed, filled = outcomes.fill_outcomes(outline)
|
| 126 |
+
|
| 127 |
+
assert [m["chapter_title"] for m in asked[0]] == ["ب"]
|
| 128 |
+
assert filled == 1
|
| 129 |
+
assert fixed["chapters"][0]["outcome"] == "ناتج موجود ومكتوب بالفعل هنا"
|
| 130 |
+
assert fixed["chapters"][1]["outcome"].startswith("أن يبني")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_a_book_whose_agent_did_its_job_pays_nothing(monkeypatch):
|
| 134 |
+
from app.services.books import outcomes
|
| 135 |
+
|
| 136 |
+
def boom(*a, **k):
|
| 137 |
+
raise AssertionError("should not be called")
|
| 138 |
+
|
| 139 |
+
monkeypatch.setattr(outcomes, "_ask", boom)
|
| 140 |
+
outline = {"chapters": [{"chapter_title": "أ", "outcome": "ناتج مكتوب هنا فعلًا"}]}
|
| 141 |
+
assert outcomes.fill_outcomes(outline) == (outline, 0)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_an_outcome_that_cannot_be_had_stays_empty(monkeypatch):
|
| 145 |
+
"""A person writing one line beats a model writing a plausible one."""
|
| 146 |
+
from app.services.books import outcomes
|
| 147 |
+
|
| 148 |
+
monkeypatch.setattr(outcomes, "_ask", lambda *a, **k: {})
|
| 149 |
+
outline = {"chapters": [{"chapter_title": "أ", "outcome": ""}]}
|
| 150 |
+
fixed, filled = outcomes.fill_outcomes(outline)
|
| 151 |
+
assert filled == 0
|
| 152 |
+
assert fixed["chapters"][0]["outcome"] == ""
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_a_reply_that_renamed_the_chapter_still_lands(monkeypatch):
|
| 156 |
+
"""Matched by title, then by what is left over - the same fallback the
|
| 157 |
+
structure restore uses, for the same reason."""
|
| 158 |
+
from app.services.books import outcomes
|
| 159 |
+
|
| 160 |
+
monkeypatch.setattr(
|
| 161 |
+
outcomes, "_ask",
|
| 162 |
+
lambda *a, **k: {"عنوان مختلف تمامًا": "أن يتعرف القارئ على أسس الأتمتة الحديثة."},
|
| 163 |
+
)
|
| 164 |
+
outline = {"chapters": [{"chapter_title": "أ", "outcome": ""}]}
|
| 165 |
+
fixed, filled = outcomes.fill_outcomes(outline)
|
| 166 |
+
assert filled == 1
|
| 167 |
+
assert fixed["chapters"][0]["outcome"].startswith("أن يتعرف")
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def test_the_step_puts_the_header_back_and_fills_the_outcomes():
|
| 171 |
+
import inspect
|
| 172 |
+
|
| 173 |
+
from app.pipelines.books import steps
|
| 174 |
+
|
| 175 |
+
src = inspect.getsource(steps.OutlineStep.run)
|
| 176 |
+
assert "restore_header(" in src
|
| 177 |
+
assert src.index("restore(outline, given)") < src.index("restore_header(")
|
| 178 |
+
assert "fill_outcomes(outline)" in src
|
|
@@ -12,7 +12,7 @@
|
|
| 12 |
import { useEffect, useMemo, useState } from "react";
|
| 13 |
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
| 14 |
import { useNavigate } from "react-router-dom";
|
| 15 |
-
import { api } from "@/lib/api";
|
| 16 |
import { num } from "@/lib/format";
|
| 17 |
import { Alert, Button, Card, Spinner } from "@/components/ui";
|
| 18 |
import { Icon } from "@/components/Icon";
|
|
@@ -93,6 +93,31 @@ function removeAt(root: Json, path: (string | number)[]): Json {
|
|
| 93 |
return setAt(root, parentPath, parent.filter((_, i) => i !== last));
|
| 94 |
}
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
/** One value, rendered by what it is. */
|
| 97 |
function Node({
|
| 98 |
name,
|
|
@@ -213,6 +238,21 @@ function Node({
|
|
| 213 |
/>
|
| 214 |
))}
|
| 215 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
</div>
|
| 217 |
);
|
| 218 |
}
|
|
@@ -311,6 +351,18 @@ export default function BlueprintReview({ runId }: { runId: string }) {
|
|
| 311 |
},
|
| 312 |
});
|
| 313 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
const change = (path: (string | number)[], value: Json) => {
|
| 315 |
setDraft((current) => setAt(current ?? {}, path, value) as Obj);
|
| 316 |
setDirty(true);
|
|
@@ -348,6 +400,13 @@ export default function BlueprintReview({ runId }: { runId: string }) {
|
|
| 348 |
</p>
|
| 349 |
</div>
|
| 350 |
<div className="flex items-center gap-2">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
<Button
|
| 352 |
variant="ghost"
|
| 353 |
onClick={() => save.mutate()}
|
|
@@ -367,6 +426,9 @@ export default function BlueprintReview({ runId }: { runId: string }) {
|
|
| 367 |
{approve.error && (
|
| 368 |
<Alert tone="err">{(approve.error as Error).message}</Alert>
|
| 369 |
)}
|
|
|
|
|
|
|
|
|
|
| 370 |
</Card>
|
| 371 |
|
| 372 |
<div className="flex flex-col gap-3">
|
|
@@ -386,4 +448,4 @@ export default function BlueprintReview({ runId }: { runId: string }) {
|
|
| 386 |
);
|
| 387 |
}
|
| 388 |
|
| 389 |
-
export { removeAt, setAt, labelFor, rowTitle };
|
|
|
|
| 12 |
import { useEffect, useMemo, useState } from "react";
|
| 13 |
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
| 14 |
import { useNavigate } from "react-router-dom";
|
| 15 |
+
import { api, downloadBlueprint } from "@/lib/api";
|
| 16 |
import { num } from "@/lib/format";
|
| 17 |
import { Alert, Button, Card, Spinner } from "@/components/ui";
|
| 18 |
import { Icon } from "@/components/Icon";
|
|
|
|
| 93 |
return setAt(root, parentPath, parent.filter((_, i) => i !== last));
|
| 94 |
}
|
| 95 |
|
| 96 |
+
/* What an added row looks like.
|
| 97 |
+
|
| 98 |
+
Shaped from the rows already there rather than from knowledge of the task
|
| 99 |
+
type - the same rule the rest of this editor follows. A new chapter gets
|
| 100 |
+
every field a chapter has, emptied, so it reaches the pipeline with the
|
| 101 |
+
shape the pipeline validates instead of as a bare title the next step
|
| 102 |
+
cannot read. Numbers that count the row - day_number, cover_index - carry
|
| 103 |
+
on from the last one; everything else starts blank. */
|
| 104 |
+
function blankLike(siblings: Json[], index: number): Json {
|
| 105 |
+
const model = siblings.find(
|
| 106 |
+
(s) => s && typeof s === "object" && !Array.isArray(s),
|
| 107 |
+
) as Obj | undefined;
|
| 108 |
+
if (!model) return "";
|
| 109 |
+
|
| 110 |
+
const row: Obj = {};
|
| 111 |
+
for (const [k, v] of Object.entries(model)) {
|
| 112 |
+
if (typeof v === "string") row[k] = "";
|
| 113 |
+
else if (typeof v === "number") row[k] = /number|index/i.test(k) ? index + 1 : 0;
|
| 114 |
+
else if (typeof v === "boolean") row[k] = false;
|
| 115 |
+
else if (Array.isArray(v)) row[k] = [];
|
| 116 |
+
else row[k] = null;
|
| 117 |
+
}
|
| 118 |
+
return row;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
/** One value, rendered by what it is. */
|
| 122 |
function Node({
|
| 123 |
name,
|
|
|
|
| 238 |
/>
|
| 239 |
))}
|
| 240 |
</div>
|
| 241 |
+
{/* Deleting was possible and adding was not, which makes the gate a
|
| 242 |
+
place to cut a design down and never to correct it - and a محور the
|
| 243 |
+
reader left out is as wrong as one they did not want. */}
|
| 244 |
+
<button
|
| 245 |
+
type="button"
|
| 246 |
+
onClick={() =>
|
| 247 |
+
onChange(path, [...value, blankLike(value, value.length)])
|
| 248 |
+
}
|
| 249 |
+
className="tap-44 mt-2 rounded-md border border-dashed
|
| 250 |
+
border-[var(--border-base)] px-3 py-1.5 text-micro
|
| 251 |
+
text-[var(--text-muted)] transition
|
| 252 |
+
hover:border-[var(--brand)] hover:text-[var(--brand)]"
|
| 253 |
+
>
|
| 254 |
+
+ أضف {label}
|
| 255 |
+
</button>
|
| 256 |
</div>
|
| 257 |
);
|
| 258 |
}
|
|
|
|
| 351 |
},
|
| 352 |
});
|
| 353 |
|
| 354 |
+
/* Saved first when there are unsaved edits, so the file is the design the
|
| 355 |
+
reviewer is looking at rather than the one the server last heard about. */
|
| 356 |
+
const download = useMutation({
|
| 357 |
+
mutationFn: async () => {
|
| 358 |
+
if (dirty) {
|
| 359 |
+
await api.saveReview(runId, draft ?? {});
|
| 360 |
+
setDirty(false);
|
| 361 |
+
}
|
| 362 |
+
await downloadBlueprint(runId);
|
| 363 |
+
},
|
| 364 |
+
});
|
| 365 |
+
|
| 366 |
const change = (path: (string | number)[], value: Json) => {
|
| 367 |
setDraft((current) => setAt(current ?? {}, path, value) as Obj);
|
| 368 |
setDirty(true);
|
|
|
|
| 400 |
</p>
|
| 401 |
</div>
|
| 402 |
<div className="flex items-center gap-2">
|
| 403 |
+
<Button
|
| 404 |
+
variant="ghost"
|
| 405 |
+
onClick={() => download.mutate()}
|
| 406 |
+
disabled={busy || download.isPending}
|
| 407 |
+
>
|
| 408 |
+
{download.isPending ? "جارٍ التجهيز…" : "تنزيل Word"}
|
| 409 |
+
</Button>
|
| 410 |
<Button
|
| 411 |
variant="ghost"
|
| 412 |
onClick={() => save.mutate()}
|
|
|
|
| 426 |
{approve.error && (
|
| 427 |
<Alert tone="err">{(approve.error as Error).message}</Alert>
|
| 428 |
)}
|
| 429 |
+
{download.error && (
|
| 430 |
+
<Alert tone="err">{(download.error as Error).message}</Alert>
|
| 431 |
+
)}
|
| 432 |
</Card>
|
| 433 |
|
| 434 |
<div className="flex flex-col gap-3">
|
|
|
|
| 448 |
);
|
| 449 |
}
|
| 450 |
|
| 451 |
+
export { removeAt, setAt, labelFor, rowTitle, blankLike };
|
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Adding a row at the gate, and what shape it arrives in.
|
| 2 |
+
|
| 3 |
+
The editor could delete and could not add, which makes the gate a place to
|
| 4 |
+
cut a design down and never to correct it - and a محور the reader left out
|
| 5 |
+
is as wrong as one they did not want.
|
| 6 |
+
|
| 7 |
+
The shape matters as much as the button. A new chapter added as a bare title
|
| 8 |
+
reaches the next step missing every field that step reads, so it is built
|
| 9 |
+
from the rows already beside it: same keys, emptied. */
|
| 10 |
+
|
| 11 |
+
import { describe, expect, it } from "vitest";
|
| 12 |
+
import { blankLike } from "./BlueprintReview";
|
| 13 |
+
|
| 14 |
+
/** `blankLike` returns the editor's own `Json`, which is `unknown`. */
|
| 15 |
+
const row = (value: unknown) => value as Record<string, unknown>;
|
| 16 |
+
|
| 17 |
+
const CHAPTERS = [
|
| 18 |
+
{
|
| 19 |
+
chapter_title: "الفصل الأول",
|
| 20 |
+
outcome: "أن يميّز القارئ بين الأتمتة والمساعدة",
|
| 21 |
+
sections: [{ title: "محور", subsections: [] }],
|
| 22 |
+
},
|
| 23 |
+
];
|
| 24 |
+
|
| 25 |
+
describe("blankLike", () => {
|
| 26 |
+
it("gives a new row every field its siblings have", () => {
|
| 27 |
+
expect(Object.keys(row(blankLike(CHAPTERS, 1))).sort()).toEqual(
|
| 28 |
+
["chapter_title", "outcome", "sections"].sort(),
|
| 29 |
+
);
|
| 30 |
+
});
|
| 31 |
+
|
| 32 |
+
it("empties the text rather than copying it", () => {
|
| 33 |
+
const made = row(blankLike(CHAPTERS, 1));
|
| 34 |
+
expect(made.chapter_title).toBe("");
|
| 35 |
+
expect(made.outcome).toBe("");
|
| 36 |
+
});
|
| 37 |
+
|
| 38 |
+
it("starts nested lists empty, not shared with the row it copied", () => {
|
| 39 |
+
const made = row(blankLike(CHAPTERS, 1));
|
| 40 |
+
expect(made.sections).toEqual([]);
|
| 41 |
+
expect(made.sections).not.toBe(CHAPTERS[0].sections);
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
it("carries on a number that counts the row", () => {
|
| 45 |
+
const days = [{ day_number: 1, sessions: [] }];
|
| 46 |
+
expect(row(blankLike(days, 1)).day_number).toBe(2);
|
| 47 |
+
expect(row(blankLike(days, 4)).day_number).toBe(5);
|
| 48 |
+
});
|
| 49 |
+
|
| 50 |
+
it("zeroes a number that measures rather than counts", () => {
|
| 51 |
+
const subs = [{ title: "موضوع", est_pages: 3 }];
|
| 52 |
+
expect(row(blankLike(subs, 1)).est_pages).toBe(0);
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
it("adds a string to a list of strings", () => {
|
| 56 |
+
expect(blankLike(["موضوع أول", "موضوع ثان"], 2)).toBe("");
|
| 57 |
+
});
|
| 58 |
+
|
| 59 |
+
it("adds a string to an empty list, having nothing to copy", () => {
|
| 60 |
+
expect(blankLike([], 0)).toBe("");
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
it("reads the shape past a stray string in a list of objects", () => {
|
| 64 |
+
const mixed = ["نص خام", { title: "محور", subsections: [] }];
|
| 65 |
+
expect(Object.keys(row(blankLike(mixed, 2))).sort()).toEqual([
|
| 66 |
+
"subsections",
|
| 67 |
+
"title",
|
| 68 |
+
]);
|
| 69 |
+
});
|
| 70 |
+
});
|
|
@@ -393,6 +393,29 @@ export async function downloadArtifact(
|
|
| 393 |
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
| 394 |
}
|
| 395 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
/** Open an HTML report in a new tab. */
|
| 397 |
export async function viewArtifact(id: string): Promise<void> {
|
| 398 |
// The tab is opened synchronously, before the await, or the pop-up blocker
|
|
|
|
| 393 |
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
| 394 |
}
|
| 395 |
|
| 396 |
+
/** Save the blueprint waiting at the gate as a Word file.
|
| 397 |
+
|
| 398 |
+
The reviewer is being asked whether the structure holds together, and a form
|
| 399 |
+
is the wrong shape for that question: it shows one field at a time and never
|
| 400 |
+
the whole thing in order. Rendered server-side from what the run is holding,
|
| 401 |
+
so a saved edit is already in it. */
|
| 402 |
+
export async function downloadBlueprint(runId: string): Promise<void> {
|
| 403 |
+
const res = await fetch(`${API_URL}/v1/runs/${runId}/review.docx`, {
|
| 404 |
+
headers: await authHeader(),
|
| 405 |
+
});
|
| 406 |
+
if (!res.ok) {
|
| 407 |
+
throw new ApiError(res.status, `تعذّر تجهيز الملف (${res.status})`);
|
| 408 |
+
}
|
| 409 |
+
const url = URL.createObjectURL(await res.blob());
|
| 410 |
+
const link = document.createElement("a");
|
| 411 |
+
link.href = url;
|
| 412 |
+
link.download = safeName("التصور الفني", "docx");
|
| 413 |
+
document.body.appendChild(link);
|
| 414 |
+
link.click();
|
| 415 |
+
link.remove();
|
| 416 |
+
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
/** Open an HTML report in a new tab. */
|
| 420 |
export async function viewArtifact(id: string): Promise<void> {
|
| 421 |
// The tab is opened synchronously, before the await, or the pop-up blocker
|