Menixis Claude Opus 4.8 (1M context) commited on
Commit
256df8f
·
1 Parent(s): 143187f

Auto-form: generate the body in the exact PTT 2-paragraph format

Browse files

The body is now an AI-generated เนื้อความ matching the real letters: para 1 context
("ตามที่ ปตท. ได้ดำเนินการ[จัดจ้าง/จัดซื้อ] <work> โดย <vendor> เป็น[ผู้รับจ้าง/ผู้ขาย]นั้น")
and para 2 instruction ("<unit> ขอแจ้งให้บริษัทของท่านเริ่มเข้าดำเนินการ[ปฏิบัติงาน/ส่งมอบสินค้า]
ได้นับถัดจากวันที่ <date> เป็นต้นไป [จนกว่างานจะแล้วเสร็จ…ไม่เกิน X วัน] ตาม[ใบสั่งจ้าง/ใบสั่งซื้อ]
ที่อ้างถึงนั้น"). procurementType drives the ซื้อ/จ้าง swaps.

- ai_clean: generate_body() (AI primary + IDENTICAL-format deterministic compose_body fallback
so it's always on-format despite free-model 429s); thai_date(); งวด-aware เรื่อง suffix kept.
- form1.docx: body replaced by a single [เนื้อความ] block; form_logic inserts the 2 paragraphs
(first-line indent preserved) via insert_body_paragraphs().
- streamlit: start-date picker (วันที่เริ่มดำเนินการ); unit from prCreatorUnitName; gathers fields
and calls generate_body during the AI animation.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

Files changed (4) hide show
  1. ai_clean.py +113 -0
  2. form_logic.py +34 -18
  3. streamlit_app.py +18 -9
  4. templates/form1.docx +2 -2
ai_clean.py CHANGED
@@ -19,6 +19,16 @@ import urllib.error
19
 
20
  OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
21
 
 
 
 
 
 
 
 
 
 
 
22
  # Primary = the user's choice; the rest are free fallbacks for when the primary 429s.
23
  MODELS = [
24
  "google/gemma-4-31b-it:free",
@@ -106,6 +116,109 @@ def _call_openrouter(model, user_content, api_key, timeout=45):
106
  return (data["choices"][0]["message"]["content"] or "").strip()
107
 
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  def clean_delivery(clause, selected_label=None, api_key=None, retries=2):
110
  """Rewrite a delivery clause (optionally for a single selected งวด) into clean
111
  letter Thai. Returns (text, used_ai): used_ai=False means the raw fallback was used.
 
19
 
20
  OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
21
 
22
+ THAI_MONTHS = ["", "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน",
23
+ "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"]
24
+
25
+
26
+ def thai_date(d):
27
+ """date/datetime -> '27 กุมภาพันธ์ 2569' (พุทธศักราช). '' if d is None."""
28
+ if d is None:
29
+ return ""
30
+ return f"{d.day} {THAI_MONTHS[d.month]} {d.year + 543}"
31
+
32
  # Primary = the user's choice; the rest are free fallbacks for when the primary 429s.
33
  MODELS = [
34
  "google/gemma-4-31b-it:free",
 
116
  return (data["choices"][0]["message"]["content"] or "").strip()
117
 
118
 
119
+ # ---------------------------------------------------------------------------
120
+ # Body generation (the 2-paragraph เนื้อความ in the exact PTT letter format)
121
+ # ---------------------------------------------------------------------------
122
+ def _is_jang(procurement_type):
123
+ """งานจ้าง -> True (จ้าง/work); งานซื้อ -> False (ซื้อ/goods). Default ซื้อ."""
124
+ return "จ้าง" in (procurement_type or "")
125
+
126
+
127
+ def _variants(procurement_type):
128
+ jang = _is_jang(procurement_type)
129
+ return {
130
+ "action1": "จัดจ้าง" if jang else "จัดซื้อ",
131
+ "role": "ผู้รับจ้าง" if jang else "ผู้ขาย",
132
+ "action2": "ปฏิบัติงาน" if jang else "ส่งมอบสินค้า",
133
+ "doc": "ใบสั่งจ้าง" if jang else "ใบสั่งซื้อ",
134
+ "jang": jang,
135
+ }
136
+
137
+
138
+ def _clean_work(title, procurement_type):
139
+ """Strip a redundant leading procurement verb from the job title (action1 already says it):
140
+ 'งานจัดจ้างบำรุงรักษา…' -> 'บำรุงรักษา…', 'จัดซื้อ Emergency Lamp…' -> 'Emergency Lamp…'."""
141
+ w = (title or "").strip()
142
+ w = re.sub(r"^\s*งาน\s*", "", w)
143
+ w = re.sub(r"^\s*(จัดจ้าง|จัดซื้อ|ว่าจ้าง|จ้าง|ซื้อ)\s*", "", w)
144
+ return w.strip()
145
+
146
+
147
+ def _duration_clause(procurement_type, days):
148
+ """จ้าง with an SLA -> ' จนกว่างานจะแล้วเสร็จโดยใช้เวลาไม่เกิน X วัน'; otherwise ''
149
+ (the ซื้อ examples carry no duration in the body)."""
150
+ days = str(days or "").strip()
151
+ if _is_jang(procurement_type) and days:
152
+ return f" จนกว่างานจะแล้วเสร็จโดยใช้เวลาไม่เกิน {days} วัน"
153
+ return ""
154
+
155
+
156
+ def compose_body(fields):
157
+ """Deterministic 2-paragraph เนื้อความ in the exact format (also the AI fallback)."""
158
+ v = _variants(fields.get("procurement_type"))
159
+ work = _clean_work(fields.get("work"), fields.get("procurement_type"))
160
+ vendor = (fields.get("vendor") or "").strip()
161
+ unit = (fields.get("unit") or "").strip() or "บริษัท ปตท. จำกัด (มหาชน)"
162
+ start = (fields.get("start_date") or "").strip()
163
+ duration = _duration_clause(fields.get("procurement_type"), fields.get("days"))
164
+ # Thai text glues to the verb (no space); English/other takes a space
165
+ sep = "" if (work and "฀" <= work[0] <= "๿") else " "
166
+ p1 = (f"ตามที่ บริษัท ปตท. จำกัด (มหาชน) (“ปตท.”) ได้ดำเนินการ{v['action1']}{sep}{work} "
167
+ f"โดย {vendor} เป็น{v['role']}นั้น")
168
+ p2 = (f"{unit} ขอแจ้งให้บริษัทของท่านเริ่มเข้าดำเนินการ{v['action2']}ได้นับถัดจากวันที่ {start} "
169
+ f"เป็นต้นไป{duration} ตาม{v['doc']}ที่อ้างถึงนั้น")
170
+ return p1 + "\n\n" + p2
171
+
172
+
173
+ _BODY_SYSTEM = (
174
+ "คุณเป็นผู้ช่วยร่างหนังสือราชการจัดซื้อจัดจ้างของ บริษัท ปตท. จำกัด (มหาชน) "
175
+ "จงสร้าง \"เนื้อความ\" ของหนังสือแจ้งให้เริ่มงาน/ส่งมอบ เป็น 2 ย่อหน้าตามรูปแบบที่กำหนดอย่างเคร่งครัด "
176
+ "เติมเฉพาะค่าที่ให้มา ห้ามเพิ่ม/ตัด/เปลี่ยนถ้อยคำอื่น คั่นย่อหน้าด้วยบรรท���ดว่าง "
177
+ "ตอบเฉพาะเนื้อความ 2 ย่อหน้าเท่านั้น"
178
+ )
179
+
180
+
181
+ def generate_body(fields, api_key=None, retries=2):
182
+ """AI-generate the 2-paragraph เนื้อความ in the exact format. Returns (text, used_ai).
183
+ Falls back to the identical-format deterministic compose_body() on missing key / failure /
184
+ if the model drifts off-format — so the output is always exactly on-format."""
185
+ det = compose_body(fields)
186
+ api_key = api_key or os.environ.get("OPENROUTER_API_KEY", "").strip()
187
+ if not api_key:
188
+ return det, False
189
+
190
+ v = _variants(fields.get("procurement_type"))
191
+ user = (
192
+ "รูปแบบ (2 ย่อหน้า):\n"
193
+ "ย่อหน้า 1: ตามที่ บริษัท ปตท. จำกัด (มหาชน) (“ปตท.”) ได้ดำเนินการ{ACTION1} {WORK} "
194
+ "โดย {VENDOR} เป็น{ROLE}นั้น\n"
195
+ "ย่อหน้า 2: {UNIT} ขอแจ้งให้บริษัทของท่านเริ่มเข้าดำเนินการ{ACTION2}ได้นับถัดจากวันที่ {START} "
196
+ "เป็นต้นไป{DURATION} ตาม{DOC}ที่อ้างถึงนั้น\n\nค่า:\n"
197
+ f"ACTION1={v['action1']}\nWORK={_clean_work(fields.get('work'), fields.get('procurement_type'))}\n"
198
+ f"VENDOR={(fields.get('vendor') or '').strip()}\nROLE={v['role']}\n"
199
+ f"UNIT={(fields.get('unit') or '').strip() or 'บริษัท ปตท. จำกัด (มหาชน)'}\n"
200
+ f"ACTION2={v['action2']}\nSTART={(fields.get('start_date') or '').strip()}\n"
201
+ f"DURATION={_duration_clause(fields.get('procurement_type'), fields.get('days'))}\nDOC={v['doc']}"
202
+ )
203
+ for model in MODELS:
204
+ for attempt in range(retries):
205
+ try:
206
+ out = _call_openrouter(model, user, api_key)
207
+ # accept only if on-format (both anchor phrases present); else fall back
208
+ if out and "ตามที่ บริษัท ปตท" in out and "ขอแจ้งให้บริษัทของท่าน" in out:
209
+ return out, True
210
+ break
211
+ except urllib.error.HTTPError as e:
212
+ if e.code in (429, 500, 502, 503) and attempt < retries - 1:
213
+ time.sleep(1.2 * (attempt + 1)); continue
214
+ break
215
+ except Exception: # noqa: BLE001
216
+ if attempt < retries - 1:
217
+ time.sleep(1.0 * (attempt + 1)); continue
218
+ break
219
+ return det, False
220
+
221
+
222
  def clean_delivery(clause, selected_label=None, api_key=None, retries=2):
223
  """Rewrite a delivery clause (optionally for a single selected งวด) into clean
224
  letter Thai. Returns (text, used_ai): used_ai=False means the raw fallback was used.
form_logic.py CHANGED
@@ -8,7 +8,9 @@ Form Logic — pure logic for document generation (no UI dependencies)
8
 
9
  import os
10
  import re
 
11
  from docx import Document
 
12
 
13
 
14
  # =============================================================================
@@ -45,8 +47,7 @@ PLACEHOLDER_SIGNER_F1 = "ผู้มีอำนาจอนุมัติ ห
45
  PLACEHOLDER_POSITION_F1 = "ตำแหน่งผู้ลงนาม"
46
  PLACEHOLDER_VENDOR_F1 = "Vendor"
47
  PLACEHOLDER_WORK_F1 = "ชื่องาน"
48
- PLACEHOLDER_DELIVERY_F1 = "[กำหนดส่งมอบ]" # AI-cleaned การส่งมอบงาน block
49
- PLACEHOLDER_DAYS_F1 = "จำนวนวัน" # filled from daySLA (overall SLA)
50
 
51
  PLACEHOLDER_DOC_NUM_F2_5 = " /"
52
  PLACEHOLDER_SIGNER_F2_5 = "( )"
@@ -118,6 +119,31 @@ def remove_paragraphs_containing(doc, marker):
118
  return count
119
 
120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  def center_text_in_parens(name, total_width=44):
122
  inner = f" {name} ".strip()
123
  if len(inner) >= total_width:
@@ -153,7 +179,7 @@ def clean_vendor_name(value):
153
  # =============================================================================
154
  def generate_form(form_id, template_path, output_path,
155
  doc_number, po_number, doc_type, signer,
156
- lookup_data=None, signer_position=None, delivery_clause=None):
157
  """
158
  สร้างเอกสาร Word จาก template
159
  Args:
@@ -195,24 +221,14 @@ def generate_form(form_id, template_path, output_path,
195
 
196
  if vendor_name:
197
  n = replace_text(doc, PLACEHOLDER_VENDOR_F1, vendor_name)
198
- log.append(f"ชื่อคู่สัญญา (Excel): แทนที่ {n} จุด")
199
  if work_title:
200
  n = replace_text(doc, PLACEHOLDER_WORK_F1, work_title)
201
- log.append(f"ชื่องาน (Excel): แทนที่ {n} จุด")
202
 
203
- days = str((lookup_data or {}).get("daySLA") or "").strip()
204
- if days:
205
- n = replace_text(doc, PLACEHOLDER_DAYS_F1, days)
206
- log.append(f"จำนวนวัน (SLA): แทนที่ {n} จุด")
207
-
208
- # AI-cleaned กำหนดส่งมอบ block: fill it, or drop the empty placeholder paragraph
209
- clause = " ".join((delivery_clause or "").split()) # collapse newlines -> one paragraph
210
- if clause:
211
- n = replace_text(doc, PLACEHOLDER_DELIVERY_F1, clause)
212
- log.append(f"กำหนดส่งมอบ: แทนที่ {n} จุด")
213
- else:
214
- r = remove_paragraphs_containing(doc, PLACEHOLDER_DELIVERY_F1)
215
- log.append(f"กำหนดส่งมอบ: ไม่มีข้อมูล — ลบ {r} ย่อหน้า")
216
  else:
217
  n = replace_text(
218
  doc, PLACEHOLDER_DOC_NUM_F2_5,
 
8
 
9
  import os
10
  import re
11
+ from copy import deepcopy
12
  from docx import Document
13
+ from docx.text.paragraph import Paragraph
14
 
15
 
16
  # =============================================================================
 
47
  PLACEHOLDER_POSITION_F1 = "ตำแหน่งผู้ลงนาม"
48
  PLACEHOLDER_VENDOR_F1 = "Vendor"
49
  PLACEHOLDER_WORK_F1 = "ชื่องาน"
50
+ PLACEHOLDER_BODY_F1 = "[เนื้อความ]" # the AI/deterministic 2-paragraph body
 
51
 
52
  PLACEHOLDER_DOC_NUM_F2_5 = " /"
53
  PLACEHOLDER_SIGNER_F2_5 = "( )"
 
119
  return count
120
 
121
 
122
+ def insert_body_paragraphs(doc, placeholder, body_text):
123
+ """Replace the single `placeholder` paragraph with one paragraph per blank-line-separated
124
+ block of `body_text`, cloning the placeholder's formatting (alignment + first-line indent).
125
+ Returns the number of paragraphs inserted."""
126
+ target = None
127
+ for p in doc.paragraphs:
128
+ if placeholder in p.text:
129
+ target = p
130
+ break
131
+ if target is None:
132
+ return 0
133
+ blocks = [b.strip() for b in re.split(r"\n\s*\n", (body_text or "").strip()) if b.strip()]
134
+ anchor = target._p
135
+ for block in blocks:
136
+ new_el = deepcopy(target._p)
137
+ anchor.addnext(new_el)
138
+ np = Paragraph(new_el, target._parent)
139
+ np.runs[0].text = " ".join(block.split()) # collapse stray newlines within a block
140
+ for r in np.runs[1:]:
141
+ r.text = ""
142
+ anchor = new_el
143
+ target._element.getparent().remove(target._element) # drop the placeholder itself
144
+ return len(blocks)
145
+
146
+
147
  def center_text_in_parens(name, total_width=44):
148
  inner = f" {name} ".strip()
149
  if len(inner) >= total_width:
 
179
  # =============================================================================
180
  def generate_form(form_id, template_path, output_path,
181
  doc_number, po_number, doc_type, signer,
182
+ lookup_data=None, signer_position=None, body_text=None):
183
  """
184
  สร้างเอกสาร Word จาก template
185
  Args:
 
221
 
222
  if vendor_name:
223
  n = replace_text(doc, PLACEHOLDER_VENDOR_F1, vendor_name)
224
+ log.append(f"ชื่อคู่สัญญา (เรียน): แทนที่ {n} จุด")
225
  if work_title:
226
  n = replace_text(doc, PLACEHOLDER_WORK_F1, work_title)
227
+ log.append(f"ชื่องาน (อ้างถึง): แทนที่ {n} จุด")
228
 
229
+ # main body (เนื้อความ) — the AI/deterministic 2-paragraph text in the exact format
230
+ n = insert_body_paragraphs(doc, PLACEHOLDER_BODY_F1, body_text or "")
231
+ log.append(f"เนื้อความ: เพิ่ม {n} ย่อหน้า")
 
 
 
 
 
 
 
 
 
 
232
  else:
233
  n = replace_text(
234
  doc, PLACEHOLDER_DOC_NUM_F2_5,
streamlit_app.py CHANGED
@@ -1464,6 +1464,10 @@ with right_col:
1464
  elif resolved_signers is None:
1465
  st.caption(":material/hourglass_top: กำลังดึงกำหนดส่งมอบจาก TOR…")
1466
 
 
 
 
 
1467
  st.markdown("<div style='height: 0.75rem;'></div>", unsafe_allow_html=True)
1468
 
1469
  generate_clicked = st.button(":material/auto_awesome: สร้างเอกสารด้วย AI",
@@ -1496,15 +1500,20 @@ with right_col:
1496
  status_ph = st.empty()
1497
  try:
1498
  status_ph.markdown(AI_CREATE_ANIM_HTML, unsafe_allow_html=True)
1499
- # AI-clean the SELECTED งวด's delivery clause (best effort: retries +
1500
- # fallback model, and falls back to the raw TOR text if AI is unavailable)
1501
- delivery_text = ""
 
 
 
 
 
 
 
 
1502
  doc_type_final = doc_type if selected_form['uses_doc_type'] else ""
1503
- if delivery_raw and selected_nguad:
1504
- delivery_text, _used_ai = ai_clean.clean_delivery(
1505
- delivery_raw, selected_nguad["label"])
1506
- if selected_nguad.get("number") and doc_type_final:
1507
- doc_type_final += f" (งวดที่ {selected_nguad['number']})"
1508
 
1509
  output_buffer = BytesIO()
1510
  log = generate_form(
@@ -1517,7 +1526,7 @@ with right_col:
1517
  signer=signer.strip(),
1518
  lookup_data=st.session_state.lookup_data,
1519
  signer_position=signer_position.strip(),
1520
- delivery_clause=delivery_text,
1521
  )
1522
  output_buffer.seek(0)
1523
  output_bytes = output_buffer.getvalue()
 
1464
  elif resolved_signers is None:
1465
  st.caption(":material/hourglass_top: กำลังดึงกำหนดส่งมอบจาก TOR…")
1466
 
1467
+ # วันที่เริ่มดำเนินการ — fills the body ("…นับถัดจากวันที่ <date> เป็นต้นไป"). Defaults to today.
1468
+ start_date_value = st.date_input("วันที่เริ่มดำเนินการ / ส่งมอบ", format="DD/MM/YYYY",
1469
+ key="start_date_widget", disabled=not step1_done)
1470
+
1471
  st.markdown("<div style='height: 0.75rem;'></div>", unsafe_allow_html=True)
1472
 
1473
  generate_clicked = st.button(":material/auto_awesome: สร้างเอกสารด้วย AI",
 
1500
  status_ph = st.empty()
1501
  try:
1502
  status_ph.markdown(AI_CREATE_ANIM_HTML, unsafe_allow_html=True)
1503
+ # AI-generate the 2-paragraph body in the exact format (deterministic
1504
+ # fallback keeps it on-format if the free model 429s)
1505
+ ld = st.session_state.lookup_data or {}
1506
+ body_text, _used_ai = ai_clean.generate_body({
1507
+ "procurement_type": ld.get("procurementType"),
1508
+ "work": ld.get("title"),
1509
+ "vendor": clean_vendor_name(ld.get("VendorName")),
1510
+ "unit": ld.get("prCreatorUnitName"),
1511
+ "start_date": ai_clean.thai_date(start_date_value),
1512
+ "days": ld.get("daySLA"),
1513
+ })
1514
  doc_type_final = doc_type if selected_form['uses_doc_type'] else ""
1515
+ if selected_nguad and selected_nguad.get("number") and doc_type_final:
1516
+ doc_type_final += f" (งวดที่ {selected_nguad['number']})"
 
 
 
1517
 
1518
  output_buffer = BytesIO()
1519
  log = generate_form(
 
1526
  signer=signer.strip(),
1527
  lookup_data=st.session_state.lookup_data,
1528
  signer_position=signer_position.strip(),
1529
+ body_text=body_text,
1530
  )
1531
  output_buffer.seek(0)
1532
  output_bytes = output_buffer.getvalue()
templates/form1.docx CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5a2d2155d9920909b547f1a8eb1efd4f61b830ef69358839df00430f3897f748
3
- size 167720
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0929b8bd957ef288ed6108fbdfcf37d0d3cd00b395b5cf088971abc21ed04b3
3
+ size 167252