Spaces:
Sleeping
Sleeping
Download ai_clean.py from procurement-tools/auto-form: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/spaces/procurement-tools/auto-form/resolve/main/ai_clean.py
- Command line
-
hf download hf://spaces/procurement-tools/auto-form/ai_clean.py
-
curl -L -o ai_clean.py https://huggingface.co/spaces/procurement-tools/auto-form/resolve/main/ai_clean.py
17.3 kB
| # -*- coding: utf-8 -*- | |
| """ | |
| ai_clean — turn a TOR กำหนดส่งมอบ (การส่งมอบงาน) clause into clean letter-style Thai, | |
| and split it into selectable งวด. | |
| - parse_nguad(clause) : deterministic; lists the งวด the user can pick (no AI, never fails). | |
| - clean_delivery(...) : AI rewrite, then a deterministic fallback so generation never hard-fails. | |
| - generate_body(...) : AI-generate the 2-paragraph letter body (deterministic fallback). | |
| AI backend is selected by the AI_BACKEND env var: | |
| "powerautomate" (default) → POST the prompt to the AI Builder flow at AIBUILDER_FLOW_URL. | |
| "off" / "deterministic" → skip AI entirely; use the deterministic composer. | |
| Any backend failure/timeout falls back to the deterministic composer, so output is always | |
| on-format. | |
| """ | |
| import os | |
| import re | |
| import json | |
| import time | |
| import urllib.request | |
| import urllib.error | |
| # --- AI backend selection -------------------------------------------------- | |
| # Default backend is the Power Automate + AI Builder flow. | |
| _DETERMINISTIC_BACKENDS = {"off", "none", "no", "false", "deterministic", ""} | |
| def _backend(): | |
| return (os.environ.get("AI_BACKEND") or "powerautomate").strip().lower() | |
| def _flow_url(): | |
| """HTTP(S) POST URL of the AI Builder Power Automate flow (a HF Space secret in prod).""" | |
| return (os.environ.get("AIBUILDER_FLOW_URL") or "").strip() | |
| THAI_MONTHS =["", "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", | |
| "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"] | |
| def thai_date(d): | |
| """date/datetime -> '27 กุมภาพันธ์ 2569' (พุทธศักราช). '' if d is None.""" | |
| if d is None: | |
| return "" | |
| return f"{d.day} {THAI_MONTHS[d.month]} {d.year + 543}" | |
| _SYSTEM = ( | |
| "คุณเป็นผู้ช่วยร่างหนังสือราชการจัดซื้อจัดจ้างของ บริษัท ปตท. จำกัด (มหาชน) " | |
| "หน้าที่ของคุณคือเรียบเรียงหัวข้อ \"การส่งมอบงาน/กำหนดส่งมอบ\" จาก TOR " | |
| "ให้เป็นข้อความภาษาไทยที่สะอาด กระชับ เป็นทางการ เหมาะสำหรับใส่ในหนังสือแจ้งให้เริ่มงาน/ส่งมอบ " | |
| "กติกา: คงข้อเท็จจริงให้ครบ (จำนวนวัน เงื่อนไขวันหยุด และจุดเริ่มนับเวลา) " | |
| "ตัดเลขหัวข้อ หัวเรื่อง และข้อความซ้ำซ้อนทิ้ง ห้ามแต่งข้อมูลใหม่ " | |
| "ตอบกลับเป็นข้อความที่เรียบเรียงแล้วเท่านั้น ห้ามมีคำอธิบาย หัวข้อ หรือเครื่องหมายคำพูด" | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # งวด parsing (deterministic — drives the selector; works even when AI is down) | |
| # --------------------------------------------------------------------------- | |
| def parse_nguad(clause): | |
| """Split a delivery clause into the งวด the user can pick. | |
| Returns a list of {"label": str, "number": int|None}. Multi-งวด clauses | |
| ("...งวดที่ 1 ... งวดที่ 2 ...") yield one entry per งวด; everything else | |
| (งวดเดียว / On-call / unstructured) yields a single entry. | |
| """ | |
| if not clause or not str(clause).strip(): | |
| return [{"label": "งวดเดียว", "number": None}] | |
| text = str(clause) | |
| nums = [] | |
| for m in re.finditer(r"งวดที่\s*(\d+)", text): | |
| n = int(m.group(1)) | |
| if n not in nums: | |
| nums.append(n) | |
| if nums: | |
| return [{"label": f"งวดที่ {n}", "number": n} for n in sorted(nums)] | |
| return [{"label": "งวดเดียว", "number": None}] | |
| # --------------------------------------------------------------------------- | |
| # AI cleaning | |
| # --------------------------------------------------------------------------- | |
| def _raw_fallback(clause, selected_label=None): | |
| """Deterministic cleanup used when the API key is missing or every model fails: | |
| drop the section number/heading + the generic boilerplate line, keep the substance.""" | |
| if not clause: | |
| return "" | |
| lines = [l.strip() for l in str(clause).splitlines() if l.strip()] | |
| drop = ("7. การส่งมอบงาน", "การส่งมอบงาน") | |
| lines = [l for l in lines if l not in drop] | |
| if selected_label and selected_label.startswith("งวดที่"): | |
| # keep the lead-in (non-งวด lines) + only the chosen งวด line(s) | |
| keep, n = [], selected_label.replace("งวดที่", "").strip() | |
| for l in lines: | |
| mm = re.match(r"งวดที่\s*(\d+)", l) | |
| if mm: | |
| if mm.group(1) == n: | |
| keep.append(l) | |
| else: | |
| keep.append(l) | |
| lines = keep | |
| return " ".join(lines).strip() | |
| def _call_powerautomate(url, prompt, timeout=90): | |
| """POST the prompt to the AI Builder Power Automate flow and return its text. | |
| Request : {"prompt": <full instruction text>} | |
| Response: either plain text, or JSON with the generated text under one of | |
| text / result / output / response (the flow's Respond action shape).""" | |
| body = json.dumps({"prompt": prompt}).encode("utf-8") | |
| req = urllib.request.Request( | |
| url, data=body, headers={"Content-Type": "application/json"}) | |
| with urllib.request.urlopen(req, timeout=timeout) as r: | |
| raw = r.read().decode("utf-8", "ignore").strip() | |
| try: | |
| data = json.loads(raw) | |
| except Exception: # plain-text response | |
| return raw | |
| if isinstance(data, dict): | |
| for k in ("text", "result", "output", "response"): | |
| v = data.get(k) | |
| if v: | |
| return str(v).strip() | |
| return "" # unexpected JSON shape → fall back | |
| return str(data).strip() | |
| def _complete_powerautomate(system, user_content, accept, retries=2): | |
| """Run one completion through the Power Automate / AI Builder flow. The flow takes a | |
| single instruction, so system + user are merged. Returns the accepted text, or None | |
| (caller then uses the deterministic composer).""" | |
| url = _flow_url() | |
| if not url: | |
| return None | |
| prompt = (system + "\n\n" + user_content) if system else user_content | |
| for attempt in range(retries): | |
| try: | |
| out = _call_powerautomate(url, prompt) | |
| if out and accept(out): | |
| return out | |
| return None # responded but off-format → fallback | |
| except urllib.error.HTTPError as e: | |
| if e.code in (429, 500, 502, 503) and attempt < retries - 1: | |
| time.sleep(0.8 * (attempt + 1)); continue | |
| return None | |
| except Exception: # noqa: BLE001 — network/timeout/parse | |
| if attempt < retries - 1: | |
| time.sleep(0.8 * (attempt + 1)); continue | |
| return None | |
| return None | |
| def _complete(user_content, accept, retries=2, system=_SYSTEM): | |
| """Dispatch one completion to the selected AI backend and return the accepted text, | |
| or None (the caller then uses the deterministic composer). The only AI backend is | |
| the Power Automate / AI Builder flow.""" | |
| if _backend() in _DETERMINISTIC_BACKENDS: | |
| return None | |
| return _complete_powerautomate(system, user_content, accept, retries) | |
| # --------------------------------------------------------------------------- | |
| # Body generation (the 2-paragraph เนื้อความ in the exact PTT letter format) | |
| # --------------------------------------------------------------------------- | |
| def _is_jang(procurement_type): | |
| """งานจ้าง -> True (จ้าง/work); งานซื้อ -> False (ซื้อ/goods). Default ซื้อ.""" | |
| return "จ้าง" in (procurement_type or "") | |
| def _verb(procurement_type): | |
| """คำจัดหาในวลี 'ได้มีข้อตกลงในการ___กับ' : 'จัดจ้าง' (งานจ้าง) / 'จัดซื้อ' (งานซื้อ).""" | |
| return "จัดจ้าง" if _is_jang(procurement_type) else "จัดซื้อ" | |
| def _duration_from_tor(delivery_clause, days_fallback): | |
| """The completion/duration clause, TOR-driven: | |
| 'โดยกำหนดให้แล้วเสร็จภายใน X วัน [(วันหยุด)] นับถัดจาก <เหตุ>' — the X วัน, the holiday note, | |
| and the start-event are lifted from the TOR delivery clause. Falls back to the SLA days + | |
| the standard 'นับถัดจาก วันที่ ปตท. มีหนังสือแจ้งให้ปฏิบัติงาน' when the TOR has no 'ภายใน X วัน'.""" | |
| c = re.sub(r"\s+", " ", (delivery_clause or "")).strip() | |
| # 'ภายใน X วัน ...' — tolerate a spelled-out คำอ่าน between the number and วัน | |
| # (e.g. 'ภายใน 160 (หนึ่งร้อยหกสิบ) วัน') and an optional leading 'ส่งมอบ/แล้วเสร็จ'. | |
| m = re.search(r"ภายใน\s*\d+\s*(?:\([^)]*\)\s*)?วัน.*?(?=\s*ทั้งนี้|$)", c) | |
| if m: | |
| return "โดยกำหนดให้แล้วเสร็จ" + m.group(0).strip() | |
| days = str(days_fallback or "").strip() | |
| if days: | |
| return f"โดยกำหนดให้แล้วเสร็จภายใน {days} วัน นับถัดจาก วันที่ ปตท. มีหนังสือแจ้งให้ปฏิบัติงาน" | |
| return "" | |
| def compose_body(fields): | |
| """Deterministic 2-paragraph เนื้อความ in the exact format (also the AI fallback).""" | |
| verb = _verb(fields.get("procurement_type")) | |
| work = (fields.get("work") or "").strip() # full job title, kept as-is | |
| vendor = (fields.get("vendor") or "").strip() | |
| unit = (fields.get("unit") or "").strip() | |
| start = (fields.get("start_date") or "").strip() | |
| duration = _duration_from_tor(fields.get("delivery_clause"), fields.get("days")) | |
| unit_pre = f"{unit} " if unit else "" | |
| p2_subj = unit or "บริษัท ปตท. จำกัด (มหาชน)" | |
| parts = [f"ตามที่ {unit_pre}บริษัท ปตท. จำกัด (มหาชน) (ปตท.) ได้มีข้อตกลงในการ{verb}กับ {vendor} " | |
| f"ให้ดำเนินการ {work}"] | |
| if duration: | |
| parts.append(duration) | |
| parts.append("ทั้งนี้ไม่นับรวมระยะเวลาที่ ปตท. ไม่อนุญาตให้เข้าดำเนินงาน/สั่งหยุดงาน") | |
| p1 = " ".join(parts) | |
| p2 = (f"{p2_subj} จึงขอแจ้งให้ {vendor} เริ่มเข้าดำเนินการได้นับถัดจากวันที่ {start} เป็นต้นไป") | |
| return p1 + "\n\n" + p2 | |
| _BODY_SYSTEM = ( | |
| "คุณเป็นผู้ช่วยร่างหนังสือราชการจัดซื้อจัดจ้างของ บริษัท ปตท. จำกัด (มหาชน) " | |
| "จงสร้าง \"เนื้อความ\" ของหนังสือแจ้งให้เริ่มงาน/ส่งมอบ เป็น 2 ย่อหน้าตามรูปแบบที่กำหนดอย่างเคร่งครัด " | |
| "เติมเฉพาะค่าที่ให้มา ห้ามเพิ่ม/ตัด/เปลี่ยนถ้อยคำอื่น คั่นย่อหน้าด้วยบรรทัดว่าง " | |
| "ตอบเฉพาะเนื้อความ 2 ย่อหน้าเท่านั้น" | |
| ) | |
| def generate_body(fields, retries=2): | |
| """AI-generate the 2-paragraph เนื้อความ in the exact format. Returns (text, used_ai). | |
| Falls back to the identical-format deterministic compose_body() on failure / | |
| if the model drifts off-format — so the output is always exactly on-format.""" | |
| det = compose_body(fields) | |
| if _backend() in _DETERMINISTIC_BACKENDS: | |
| return det, False | |
| verb = _verb(fields.get("procurement_type")) | |
| unit = (fields.get("unit") or "").strip() | |
| unit_pre = f"{unit} " if unit else "" | |
| p2_subj = unit or "บริษัท ปตท. จำกัด (มหาชน)" | |
| duration = _duration_from_tor(fields.get("delivery_clause"), fields.get("days")) | |
| user = ( | |
| "รูปแบบ (2 ย่อหน้า):\n" | |
| f"ย่อหน้า 1: ตามที่ {unit_pre}บริษัท ปตท. จำกัด (มหาชน) (ปตท.) ได้มีข้อตกลงในการ{verb}กับ {{VENDOR}} " | |
| "ให้ดำเนินการ {WORK} {DURATION} ทั้งนี้ไม่นับรวมระยะเวลาที่ ปตท. ไม่อนุญาตให้เข้าดำเนินงาน/สั่งหยุดงาน\n" | |
| f"ย่อหน้า 2: {p2_subj} จึงขอแจ้งให้ {{VENDOR}} เริ่มเข้าดำเนินการได้นับถัดจากวันที่ {{START}} เป็นต้นไป\n\nค่า:\n" | |
| f"VENDOR={(fields.get('vendor') or '').strip()}\nWORK={(fields.get('work') or '').strip()}\n" | |
| f"DURATION={duration}\nSTART={(fields.get('start_date') or '').strip()}" | |
| ) | |
| # accept only if on-format: both anchor phrases present AND, when a duration was | |
| # supplied, its day-number survived (models occasionally drop the DURATION value) | |
| _dur_m = re.search(r"ภายใน\s*(\d+)", duration) | |
| _dur_num = _dur_m.group(1) if _dur_m else None | |
| out = _complete(user, | |
| lambda o: "ตามที่" in o and "จึงขอแจ้งให้" in o | |
| and (not _dur_num or _dur_num in o), | |
| retries, system=_BODY_SYSTEM) | |
| return (out, True) if out else (det, False) | |
| def clean_delivery(clause, selected_label=None, retries=2): | |
| """Rewrite a delivery clause (optionally for a single selected งวด) into clean | |
| letter Thai. Returns (text, used_ai): used_ai=False means the raw fallback was used. | |
| Never raises — on repeated failure it returns the deterministic | |
| fallback so document generation always proceeds. | |
| """ | |
| clause = (clause or "").strip() | |
| if not clause: | |
| return "", False | |
| if _backend() in _DETERMINISTIC_BACKENDS: | |
| return _raw_fallback(clause, selected_label), False | |
| if selected_label and selected_label.startswith("งวดที่"): | |
| instruction = ( | |
| f"หนังสือฉบับนี้ออกสำหรับ \"{selected_label}\" ของการส่งมอบ " | |
| f"จงเรียบเรียงประโยคแจ้งกำหนดส่งมอบสำหรับ \"{selected_label}\" ให้สะอาดและสมบูรณ์ในตัว " | |
| f"(ระบุว่าเป็น {selected_label}, จำนวนวัน, เงื่อนไขวันหยุด และจุดเริ่มนับเวลา) " | |
| f"โดยใช้รายละเอียดจากหัวข้อการส่งมอบงานด้านล่าง: ถ้ามีรายละเอียดเฉพาะของ {selected_label} ให้ใช้รายละเอียดนั้น " | |
| f"ถ้าไม่มี ให้ใช้กำหนดเวลาส่งมอบโดยรวมแล้วระบุว่าเป็น {selected_label}:\n\n{clause}" | |
| ) | |
| else: | |
| instruction = ( | |
| "เรียบเรียงหัวข้อการส่งมอบงานต่อไปนี้เป็นข้อความแจ้งกำหนดส่งมอบที่สะอาด:\n\n" + clause | |
| ) | |
| out = _complete(instruction, lambda o: bool(o), retries) | |
| return (out, True) if out else (_raw_fallback(clause, selected_label), False) | |