Spaces:
Sleeping

Menixis Claude Opus 4.8 (1M context) commited on
Commit
0941280
·
1 Parent(s): 1c8255f

Auto-form: AI-clean กำหนดส่งมอบ into the document + งวด selector

Browse files

- ai_clean.py (new): parse_nguad() lists selectable งวด (deterministic); clean_delivery()
rewrites the chosen งวด's TOR clause into clean letter Thai via OpenRouter
(gemma-4-31b-it:free primary, llama-3.3-70b + gpt-oss-120b free fallbacks, retry on
429, raw-text fallback so generation never hard-fails). Key from OPENROUTER_API_KEY env.
- streamlit_app: งวดส่งมอบ selector (from the TOR กำหนดส่งมอบ); generate button renamed
"สร้างเอกสารด้วย AI"; on generate, AI-clean the selected งวด and pass it + a "(งวดที่ N)"
เรื่อง suffix to the form.
- form1.docx + form_logic: new [กำหนดส่งมอบ] body block (filled or dropped if empty);
fill the existing จำนวนวัน token from daySLA.

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

Files changed (4) hide show
  1. ai_clean.py +151 -0
  2. form_logic.py +28 -1
  3. streamlit_app.py +30 -3
  4. templates/form1.docx +2 -2
ai_clean.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ ai_clean — turn a TOR กำหนดส่งมอบ (การส่งมอบงาน) clause into clean letter-style Thai,
4
+ and split it into selectable งวด.
5
+
6
+ - parse_nguad(clause) : deterministic; lists the งวด the user can pick (no AI, never fails).
7
+ - clean_delivery(...) : AI rewrite via OpenRouter (free models 429 a lot, so retry + fallback
8
+ model + a raw-text fallback so generation never hard-fails).
9
+
10
+ The API key is read from the OPENROUTER_API_KEY env var (a HF Space secret in prod).
11
+ """
12
+
13
+ import os
14
+ import re
15
+ import json
16
+ import time
17
+ import urllib.request
18
+ 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",
25
+ "meta-llama/llama-3.3-70b-instruct:free",
26
+ "openai/gpt-oss-120b:free",
27
+ ]
28
+
29
+ _SYSTEM = (
30
+ "คุณเป็นผู้ช่วยร่างหนังสือราชการจัดซื้อจัดจ้างของ บริษัท ปตท. จำกัด (มหาชน) "
31
+ "หน้าที่ของคุณคือเรียบเรียงหัวข้อ \"การส่งมอบงาน/กำหนดส่งมอบ\" จาก TOR "
32
+ "ให้เป็นข้อความภาษาไทยที่สะอาด กระชับ เป็นทางการ เหมาะสำหรับใส่ในหนังสือแจ้งให้เริ่มงาน/ส่งมอบ "
33
+ "กติกา: คงข้อเท็จจริงให้ครบ (จำนวนวัน เงื่อนไขวันหยุด และจุดเริ่มนับเวลา) "
34
+ "ตัดเลขหัวข้อ หัวเรื่อง และข้อความซ้ำซ้อนทิ้ง ห้ามแต่งข้อมูลใหม่ "
35
+ "ตอบกลับเป็นข้อความที่เรียบเรียงแล้วเท่านั้น ห้ามมีคำอธิบาย หัวข้อ หรือเครื่องหมายคำพูด"
36
+ )
37
+
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # งวด parsing (deterministic — drives the selector; works even when AI is down)
41
+ # ---------------------------------------------------------------------------
42
+ def parse_nguad(clause):
43
+ """Split a delivery clause into the งวด the user can pick.
44
+
45
+ Returns a list of {"label": str, "number": int|None}. Multi-งวด clauses
46
+ ("...งวดที่ 1 ... งวดที่ 2 ...") yield one entry per งวด; everything else
47
+ (งวดเดียว / On-call / unstructured) yields a single entry.
48
+ """
49
+ if not clause or not str(clause).strip():
50
+ return [{"label": "งวดเดียว", "number": None}]
51
+ text = str(clause)
52
+ nums = []
53
+ for m in re.finditer(r"งวดที่\s*(\d+)", text):
54
+ n = int(m.group(1))
55
+ if n not in nums:
56
+ nums.append(n)
57
+ if nums:
58
+ return [{"label": f"งวดที่ {n}", "number": n} for n in sorted(nums)]
59
+ return [{"label": "งวดเดียว", "number": None}]
60
+
61
+
62
+ # ---------------------------------------------------------------------------
63
+ # AI cleaning
64
+ # ---------------------------------------------------------------------------
65
+ def _raw_fallback(clause, selected_label=None):
66
+ """Deterministic cleanup used when the API key is missing or every model fails:
67
+ drop the section number/heading + the generic boilerplate line, keep the substance."""
68
+ if not clause:
69
+ return ""
70
+ lines = [l.strip() for l in str(clause).splitlines() if l.strip()]
71
+ drop = ("7. การส่งมอบงาน", "การส่งมอบงาน")
72
+ lines = [l for l in lines if l not in drop]
73
+ if selected_label and selected_label.startswith("งวดที่"):
74
+ # keep the lead-in (non-งวด lines) + only the chosen งวด line(s)
75
+ keep, n = [], selected_label.replace("งวดที่", "").strip()
76
+ for l in lines:
77
+ mm = re.match(r"งวดที่\s*(\d+)", l)
78
+ if mm:
79
+ if mm.group(1) == n:
80
+ keep.append(l)
81
+ else:
82
+ keep.append(l)
83
+ lines = keep
84
+ return " ".join(lines).strip()
85
+
86
+
87
+ def _call_openrouter(model, user_content, api_key, timeout=45):
88
+ body = json.dumps({
89
+ "model": model,
90
+ "messages": [
91
+ {"role": "system", "content": _SYSTEM},
92
+ {"role": "user", "content": user_content},
93
+ ],
94
+ "temperature": 0.2,
95
+ }).encode("utf-8")
96
+ req = urllib.request.Request(
97
+ OPENROUTER_URL, data=body,
98
+ headers={
99
+ "Authorization": "Bearer " + api_key,
100
+ "Content-Type": "application/json",
101
+ "HTTP-Referer": "https://procurement-tools-auto-form.hf.space",
102
+ "X-Title": "PTT Auto Form",
103
+ })
104
+ with urllib.request.urlopen(req, timeout=timeout) as r:
105
+ data = json.load(r)
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.
112
+
113
+ Never raises — on missing key or repeated failure it returns the deterministic
114
+ fallback so document generation always proceeds.
115
+ """
116
+ clause = (clause or "").strip()
117
+ if not clause:
118
+ return "", False
119
+ api_key = api_key or os.environ.get("OPENROUTER_API_KEY", "").strip()
120
+ if not api_key:
121
+ return _raw_fallback(clause, selected_label), False
122
+
123
+ if selected_label and selected_label.startswith("งวดที่"):
124
+ instruction = (
125
+ f"ด้านล่างคือหัวข้อการส่งมอบงานทั้งหมดจาก TOR "
126
+ f"ให้เรียบเรียงเฉพาะ \"{selected_label}\" เป็นประโยคแจ้งกำหนดส่งมอบที่สะอาดและสมบูรณ์ในตัว "
127
+ f"(ระบุว่าเป็น {selected_label}, จำนวนวัน, เงื่อนไขวันหยุด และจุดเริ่มนับเวลา):\n\n{clause}"
128
+ )
129
+ else:
130
+ instruction = (
131
+ "เรียบเรียงหัวข้อการส่งมอบงานต่อไปนี้เป็นข้อความแจ้งกำหนดส่งมอบที่สะอาด:\n\n" + clause
132
+ )
133
+
134
+ for model in MODELS:
135
+ for attempt in range(retries):
136
+ try:
137
+ out = _call_openrouter(model, instruction, api_key)
138
+ if out:
139
+ return out, True
140
+ except urllib.error.HTTPError as e:
141
+ # 429 (rate limit) / 5xx -> wait and retry, then fall through to next model
142
+ if e.code in (429, 500, 502, 503) and attempt < retries - 1:
143
+ time.sleep(1.2 * (attempt + 1))
144
+ continue
145
+ break
146
+ except Exception: # noqa: BLE001 — network/timeout/parse
147
+ if attempt < retries - 1:
148
+ time.sleep(1.0 * (attempt + 1))
149
+ continue
150
+ break
151
+ return _raw_fallback(clause, selected_label), False
form_logic.py CHANGED
@@ -45,6 +45,8 @@ PLACEHOLDER_SIGNER_F1 = "ผู้มีอำนาจอนุมัติ ห
45
  PLACEHOLDER_POSITION_F1 = "ตำแหน่งผู้ลงนาม"
46
  PLACEHOLDER_VENDOR_F1 = "Vendor"
47
  PLACEHOLDER_WORK_F1 = "ชื่องาน"
 
 
48
 
49
  PLACEHOLDER_DOC_NUM_F2_5 = " /"
50
  PLACEHOLDER_SIGNER_F2_5 = "( )"
@@ -105,6 +107,17 @@ def replace_text(doc, old_text, new_text):
105
  return count
106
 
107
 
 
 
 
 
 
 
 
 
 
 
 
108
  def center_text_in_parens(name, total_width=44):
109
  inner = f" {name} ".strip()
110
  if len(inner) >= total_width:
@@ -140,7 +153,7 @@ def clean_vendor_name(value):
140
  # =============================================================================
141
  def generate_form(form_id, template_path, output_path,
142
  doc_number, po_number, doc_type, signer,
143
- lookup_data=None, signer_position=None):
144
  """
145
  สร้างเอกสาร Word จาก template
146
  Args:
@@ -186,6 +199,20 @@ def generate_form(form_id, template_path, output_path,
186
  if work_title:
187
  n = replace_text(doc, PLACEHOLDER_WORK_F1, work_title)
188
  log.append(f"ชื่องาน (Excel): แทนที่ {n} จุด")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  else:
190
  n = replace_text(
191
  doc, PLACEHOLDER_DOC_NUM_F2_5,
 
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 = "( )"
 
107
  return count
108
 
109
 
110
+ def remove_paragraphs_containing(doc, marker):
111
+ """Delete every paragraph whose text contains `marker`. Returns the count removed.
112
+ Used to drop an unfilled placeholder block (e.g. กำหนดส่งมอบ when there's no clause)."""
113
+ count = 0
114
+ for p in list(_iter_paragraphs(doc)):
115
+ if marker and marker in p.text:
116
+ p._element.getparent().remove(p._element)
117
+ count += 1
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
  # =============================================================================
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:
 
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,
streamlit_app.py CHANGED
@@ -35,6 +35,7 @@ from form_logic import (
35
  )
36
  from auth_gate import require_login, render_topbar
37
  import signer_lookup
 
38
 
39
  # Browser-side JS bridge: runs the signer fetch in the USER'S browser, which — unlike the HF
40
  # server — can reach the PTT-internal gateway after the user grants the one-time Local Network
@@ -1398,9 +1399,24 @@ with right_col:
1398
  # remember the resolved name for the stepper comparison (read at the top next render)
1399
  st.session_state["current_signer_name"] = signer
1400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1401
  st.markdown("<div style='height: 0.75rem;'></div>", unsafe_allow_html=True)
1402
 
1403
- generate_clicked = st.button(":material/auto_awesome: สร้างเอกสาร",
1404
  type="primary",
1405
  use_container_width=True,
1406
  disabled=not step1_done)
@@ -1428,7 +1444,17 @@ with right_col:
1428
  st.error(f"❌ ไม่พบไฟล์ template: {template_path}")
1429
  else:
1430
  try:
1431
- with st.spinner("กำลังสร้างเอกสาร..."):
 
 
 
 
 
 
 
 
 
 
1432
  output_buffer = BytesIO()
1433
  log = generate_form(
1434
  form_id=selected_form['id'],
@@ -1436,10 +1462,11 @@ with right_col:
1436
  output_path=output_buffer,
1437
  doc_number=doc_number.strip(),
1438
  po_number=po_number.strip(),
1439
- doc_type=doc_type if selected_form['uses_doc_type'] else "",
1440
  signer=signer.strip(),
1441
  lookup_data=st.session_state.lookup_data,
1442
  signer_position=signer_position.strip(),
 
1443
  )
1444
  output_buffer.seek(0)
1445
  output_bytes = output_buffer.getvalue()
 
35
  )
36
  from auth_gate import require_login, render_topbar
37
  import signer_lookup
38
+ import ai_clean
39
 
40
  # Browser-side JS bridge: runs the signer fetch in the USER'S browser, which — unlike the HF
41
  # server — can reach the PTT-internal gateway after the user grants the one-time Local Network
 
1399
  # remember the resolved name for the stepper comparison (read at the top next render)
1400
  st.session_state["current_signer_name"] = signer
1401
 
1402
+ # งวดส่งมอบ — derived from the PR's TOR กำหนดส่งมอบ (same SMP fetch). The user picks
1403
+ # which งวด this letter is for; the AI cleans that งวด's clause into the document at generate.
1404
+ delivery_raw = signer_lookup.pick_delivery(resolved_signers)
1405
+ nguad_opts = ai_clean.parse_nguad(delivery_raw) if delivery_raw else []
1406
+ selected_nguad = None
1407
+ if delivery_raw:
1408
+ labels = [o["label"] for o in nguad_opts]
1409
+ if len(labels) > 1:
1410
+ sel = st.selectbox("งวดส่งมอบ", labels, index=0, key="nguad_widget",
1411
+ disabled=not step1_done)
1412
+ else:
1413
+ sel = labels[0]
1414
+ st.caption(f":material/local_shipping: กำหนดส่งมอบ: {sel}")
1415
+ selected_nguad = next(o for o in nguad_opts if o["label"] == sel)
1416
+
1417
  st.markdown("<div style='height: 0.75rem;'></div>", unsafe_allow_html=True)
1418
 
1419
+ generate_clicked = st.button(":material/auto_awesome: สร้างเอกสารด้วย AI",
1420
  type="primary",
1421
  use_container_width=True,
1422
  disabled=not step1_done)
 
1444
  st.error(f"❌ ไม่พบไฟล์ template: {template_path}")
1445
  else:
1446
  try:
1447
+ with st.spinner("กำลังเรียบเรียงด้วย AI และสร้างเอกสาร..."):
1448
+ # AI-clean the SELECTED งวด's delivery clause (best effort: retries +
1449
+ # fallback model, and falls back to the raw TOR text if AI is unavailable)
1450
+ delivery_text = ""
1451
+ doc_type_final = doc_type if selected_form['uses_doc_type'] else ""
1452
+ if delivery_raw and selected_nguad:
1453
+ delivery_text, _used_ai = ai_clean.clean_delivery(
1454
+ delivery_raw, selected_nguad["label"])
1455
+ if selected_nguad.get("number") and doc_type_final:
1456
+ doc_type_final += f" (งวดที่ {selected_nguad['number']})"
1457
+
1458
  output_buffer = BytesIO()
1459
  log = generate_form(
1460
  form_id=selected_form['id'],
 
1462
  output_path=output_buffer,
1463
  doc_number=doc_number.strip(),
1464
  po_number=po_number.strip(),
1465
+ doc_type=doc_type_final,
1466
  signer=signer.strip(),
1467
  lookup_data=st.session_state.lookup_data,
1468
  signer_position=signer_position.strip(),
1469
+ delivery_clause=delivery_text,
1470
  )
1471
  output_buffer.seek(0)
1472
  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:971e1a55fe3894b3e9e1c1e66a5efb15d8f1bae1304a53c7186753e75fe91f20
3
- size 167657
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a2d2155d9920909b547f1a8eb1efd4f61b830ef69358839df00430f3897f748
3
+ size 167720