Spaces:
Sleeping
Sleeping
refactor: extract the generate use-case into letter_builder.py (build_letter, default_doc_type, suffix_doc_type); UI keeps only widgets, validation display, and session state — verified docx-identical to pre-refactor output
Browse files- letter_builder.py +88 -0
- streamlit_app.py +13 -49
letter_builder.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
letter_builder — use-case layer: turn the user's inputs into the finished letter.
|
| 4 |
+
|
| 5 |
+
build_letter() owns the whole generate flow (AI body → doc-type งวด suffix →
|
| 6 |
+
docx render → filename) and returns plain data. No streamlit import — the UI
|
| 7 |
+
layer (streamlit_app.py) handles widgets, error display, and session state.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
from io import BytesIO
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
|
| 14 |
+
import ai_clean
|
| 15 |
+
from form_logic import generate_form, clean_vendor_name, DOC_TYPE_OPTIONS
|
| 16 |
+
|
| 17 |
+
TEMPLATES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def template_path_for(form):
|
| 21 |
+
"""Absolute path of the .docx template for a FORM_TYPES entry."""
|
| 22 |
+
return os.path.join(TEMPLATES_DIR, form["filename"])
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def default_doc_type(procurement_type):
|
| 26 |
+
"""Auto-pick the default ประเภทเอกสาร from the PO's procurement type:
|
| 27 |
+
งานจ้าง → แจ้งให้เริ่มเข้าทำงาน, งานซื้อ → แจ้งให้เริ่มส่งมอบสินค้า."""
|
| 28 |
+
return DOC_TYPE_OPTIONS[0] if ai_clean._is_jang(procurement_type) else DOC_TYPE_OPTIONS[1]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def suffix_doc_type(doc_type_final, selected_nguad):
|
| 32 |
+
"""Append the chosen งวด to the doc type: 'แจ้งให้เริ่มเข้าทำงาน (งวดที่ 2)'."""
|
| 33 |
+
if selected_nguad and doc_type_final:
|
| 34 |
+
_ng_num = selected_nguad.get("number")
|
| 35 |
+
_ng_lab = (selected_nguad.get("label") or "").strip()
|
| 36 |
+
if _ng_num:
|
| 37 |
+
doc_type_final += f" (งวดที่ {_ng_num})"
|
| 38 |
+
elif selected_nguad.get("manual") and _ng_lab:
|
| 39 |
+
doc_type_final += f" ({_ng_lab})"
|
| 40 |
+
return doc_type_final
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def build_letter(*, selected_form, doc_number, po_number, doc_type, signer,
|
| 44 |
+
signer_position, lookup_data, start_date, delivery_raw,
|
| 45 |
+
selected_nguad, now=None):
|
| 46 |
+
"""Generate the letter. Returns (docx_bytes, filename, log, used_ai).
|
| 47 |
+
|
| 48 |
+
Raises on render failure (the UI catches and shows the error). The AI body
|
| 49 |
+
itself never raises — ai_clean falls back to the deterministic composer.
|
| 50 |
+
`now` exists only so tests can pin the filename timestamp."""
|
| 51 |
+
template_path = template_path_for(selected_form)
|
| 52 |
+
|
| 53 |
+
# AI-generate the 2-paragraph body in the exact format (deterministic
|
| 54 |
+
# fallback keeps it on-format if the AI Builder flow fails)
|
| 55 |
+
ld = lookup_data or {}
|
| 56 |
+
body_text, used_ai = ai_clean.generate_body({
|
| 57 |
+
"procurement_type": ld.get("procurementType"),
|
| 58 |
+
"work": ld.get("title"),
|
| 59 |
+
"vendor": clean_vendor_name(ld.get("VendorName")),
|
| 60 |
+
"unit": ld.get("prCreatorUnitName"),
|
| 61 |
+
"start_date": ai_clean.thai_date(start_date),
|
| 62 |
+
"days": ld.get("daySLA"),
|
| 63 |
+
"delivery_clause": delivery_raw, # TOR-driven "ภายใน X วัน นับถัดจาก…"
|
| 64 |
+
})
|
| 65 |
+
doc_type_final = doc_type if selected_form['uses_doc_type'] else ""
|
| 66 |
+
doc_type_final = suffix_doc_type(doc_type_final, selected_nguad)
|
| 67 |
+
|
| 68 |
+
output_buffer = BytesIO()
|
| 69 |
+
log = generate_form(
|
| 70 |
+
form_id=selected_form['id'],
|
| 71 |
+
template_path=template_path,
|
| 72 |
+
output_path=output_buffer,
|
| 73 |
+
doc_number=doc_number.strip(),
|
| 74 |
+
po_number=po_number.strip(),
|
| 75 |
+
doc_type=doc_type_final,
|
| 76 |
+
signer=signer.strip(),
|
| 77 |
+
lookup_data=lookup_data,
|
| 78 |
+
signer_position=signer_position.strip(),
|
| 79 |
+
body_text=body_text,
|
| 80 |
+
)
|
| 81 |
+
output_buffer.seek(0)
|
| 82 |
+
output_bytes = output_buffer.getvalue()
|
| 83 |
+
|
| 84 |
+
timestamp = (now or datetime.now()).strftime("%Y%m%d_%H%M%S")
|
| 85 |
+
safe_num = doc_number.replace('/', '-').replace('\\', '-').strip()
|
| 86 |
+
filename = (f"form{selected_form['id']}_{safe_num}_{timestamp}.docx"
|
| 87 |
+
if safe_num else f"form{selected_form['id']}_{timestamp}.docx")
|
| 88 |
+
return output_bytes, filename, log, used_ai
|
streamlit_app.py
CHANGED
|
@@ -10,8 +10,6 @@
|
|
| 10 |
|
| 11 |
import os
|
| 12 |
import sys
|
| 13 |
-
from io import BytesIO
|
| 14 |
-
from datetime import datetime
|
| 15 |
|
| 16 |
import streamlit as st
|
| 17 |
import streamlit.components.v1 as components
|
|
@@ -19,7 +17,6 @@ import streamlit.components.v1 as components
|
|
| 19 |
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 20 |
|
| 21 |
from form_logic import (
|
| 22 |
-
generate_form,
|
| 23 |
clean_vendor_name,
|
| 24 |
FORM_TYPES,
|
| 25 |
DOC_TYPE_OPTIONS,
|
|
@@ -31,6 +28,7 @@ import signer_lookup
|
|
| 31 |
import ai_clean
|
| 32 |
import data_source
|
| 33 |
import gates
|
|
|
|
| 34 |
import theme
|
| 35 |
|
| 36 |
|
|
@@ -376,8 +374,7 @@ with right_col:
|
|
| 376 |
if st.session_state.lookup_data and \
|
| 377 |
st.session_state.get("doc_type_auto_for") != st.session_state.last_po:
|
| 378 |
_ptype = st.session_state.lookup_data.get("procurementType")
|
| 379 |
-
st.session_state.doc_type_widget = (
|
| 380 |
-
DOC_TYPE_OPTIONS[0] if ai_clean._is_jang(_ptype) else DOC_TYPE_OPTIONS[1])
|
| 381 |
st.session_state.doc_type_auto_for = st.session_state.last_po
|
| 382 |
doc_type = st.radio("ประเภทเอกสาร",
|
| 383 |
DOC_TYPE_OPTIONS,
|
|
@@ -473,11 +470,7 @@ with right_col:
|
|
| 473 |
for err in errors:
|
| 474 |
st.error(f"⚠ {err}")
|
| 475 |
else:
|
| 476 |
-
template_path =
|
| 477 |
-
os.path.dirname(os.path.abspath(__file__)),
|
| 478 |
-
'templates',
|
| 479 |
-
selected_form['filename']
|
| 480 |
-
)
|
| 481 |
|
| 482 |
if not os.path.exists(template_path):
|
| 483 |
st.error(f"❌ ไม่พบไฟล์ template: {template_path}")
|
|
@@ -485,49 +478,20 @@ with right_col:
|
|
| 485 |
status_ph = st.empty()
|
| 486 |
try:
|
| 487 |
status_ph.markdown(theme.AI_CREATE_ANIM_HTML, unsafe_allow_html=True)
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
"unit": ld.get("prCreatorUnitName"),
|
| 496 |
-
"start_date": ai_clean.thai_date(start_date_value),
|
| 497 |
-
"days": ld.get("daySLA"),
|
| 498 |
-
"delivery_clause": delivery_raw, # TOR-driven "ภายใน X วัน นับถัดจาก…"
|
| 499 |
-
})
|
| 500 |
-
doc_type_final = doc_type if selected_form['uses_doc_type'] else ""
|
| 501 |
-
if selected_nguad and doc_type_final:
|
| 502 |
-
_ng_num = selected_nguad.get("number")
|
| 503 |
-
_ng_lab = (selected_nguad.get("label") or "").strip()
|
| 504 |
-
if _ng_num:
|
| 505 |
-
doc_type_final += f" (งวดที่ {_ng_num})"
|
| 506 |
-
elif selected_nguad.get("manual") and _ng_lab:
|
| 507 |
-
doc_type_final += f" ({_ng_lab})"
|
| 508 |
-
|
| 509 |
-
output_buffer = BytesIO()
|
| 510 |
-
log = generate_form(
|
| 511 |
-
form_id=selected_form['id'],
|
| 512 |
-
template_path=template_path,
|
| 513 |
-
output_path=output_buffer,
|
| 514 |
-
doc_number=doc_number.strip(),
|
| 515 |
-
po_number=po_number.strip(),
|
| 516 |
-
doc_type=doc_type_final,
|
| 517 |
-
signer=signer.strip(),
|
| 518 |
lookup_data=st.session_state.lookup_data,
|
| 519 |
-
|
| 520 |
-
|
|
|
|
| 521 |
)
|
| 522 |
-
output_buffer.seek(0)
|
| 523 |
-
output_bytes = output_buffer.getvalue()
|
| 524 |
status_ph.empty()
|
| 525 |
|
| 526 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 527 |
-
safe_num = doc_number.replace('/', '-').replace('\\', '-').strip()
|
| 528 |
-
filename = (f"form{selected_form['id']}_{safe_num}_{timestamp}.docx"
|
| 529 |
-
if safe_num else f"form{selected_form['id']}_{timestamp}.docx")
|
| 530 |
-
|
| 531 |
st.session_state.generated_file = output_bytes
|
| 532 |
st.session_state.generated_filename = filename
|
| 533 |
st.session_state.last_gen_po = po_number.strip()
|
|
|
|
| 10 |
|
| 11 |
import os
|
| 12 |
import sys
|
|
|
|
|
|
|
| 13 |
|
| 14 |
import streamlit as st
|
| 15 |
import streamlit.components.v1 as components
|
|
|
|
| 17 |
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 18 |
|
| 19 |
from form_logic import (
|
|
|
|
| 20 |
clean_vendor_name,
|
| 21 |
FORM_TYPES,
|
| 22 |
DOC_TYPE_OPTIONS,
|
|
|
|
| 28 |
import ai_clean
|
| 29 |
import data_source
|
| 30 |
import gates
|
| 31 |
+
import letter_builder
|
| 32 |
import theme
|
| 33 |
|
| 34 |
|
|
|
|
| 374 |
if st.session_state.lookup_data and \
|
| 375 |
st.session_state.get("doc_type_auto_for") != st.session_state.last_po:
|
| 376 |
_ptype = st.session_state.lookup_data.get("procurementType")
|
| 377 |
+
st.session_state.doc_type_widget = letter_builder.default_doc_type(_ptype)
|
|
|
|
| 378 |
st.session_state.doc_type_auto_for = st.session_state.last_po
|
| 379 |
doc_type = st.radio("ประเภทเอกสาร",
|
| 380 |
DOC_TYPE_OPTIONS,
|
|
|
|
| 470 |
for err in errors:
|
| 471 |
st.error(f"⚠ {err}")
|
| 472 |
else:
|
| 473 |
+
template_path = letter_builder.template_path_for(selected_form)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
|
| 475 |
if not os.path.exists(template_path):
|
| 476 |
st.error(f"❌ ไม่พบไฟล์ template: {template_path}")
|
|
|
|
| 478 |
status_ph = st.empty()
|
| 479 |
try:
|
| 480 |
status_ph.markdown(theme.AI_CREATE_ANIM_HTML, unsafe_allow_html=True)
|
| 481 |
+
output_bytes, filename, log, _used_ai = letter_builder.build_letter(
|
| 482 |
+
selected_form=selected_form,
|
| 483 |
+
doc_number=doc_number,
|
| 484 |
+
po_number=po_number,
|
| 485 |
+
doc_type=doc_type,
|
| 486 |
+
signer=signer,
|
| 487 |
+
signer_position=signer_position,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 488 |
lookup_data=st.session_state.lookup_data,
|
| 489 |
+
start_date=start_date_value,
|
| 490 |
+
delivery_raw=delivery_raw,
|
| 491 |
+
selected_nguad=selected_nguad,
|
| 492 |
)
|
|
|
|
|
|
|
| 493 |
status_ph.empty()
|
| 494 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 495 |
st.session_state.generated_file = output_bytes
|
| 496 |
st.session_state.generated_filename = filename
|
| 497 |
st.session_state.last_gen_po = po_number.strip()
|